resetting manifest requested domain to floor
[platform/upstream/ccache.git] / util.c
1 /*
2  * Copyright (C) 2002 Andrew Tridgell
3  * Copyright (C) 2009-2011 Joel Rosdahl
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 3 of the License, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 #include "ccache.h"
21
22 #include <zlib.h>
23
24 #ifdef HAVE_PWD_H
25 #include <pwd.h>
26 #endif
27 #ifdef HAVE_SYS_TIME_H
28 #include <sys/time.h>
29 #endif
30
31 #ifdef _WIN32
32 #include <windows.h>
33 #include <sys/locking.h>
34 #endif
35
36 static FILE *logfile;
37
38 static bool
39 init_log(void)
40 {
41         extern char *cache_logfile;
42
43         if (logfile) {
44                 return true;
45         }
46         if (!cache_logfile) {
47                 return false;
48         }
49         logfile = fopen(cache_logfile, "a");
50         if (logfile) {
51                 return true;
52         } else {
53                 return false;
54         }
55 }
56
57 static void
58 log_prefix(void)
59 {
60 #ifdef HAVE_GETTIMEOFDAY
61         char timestamp[100];
62         struct timeval tv;
63         struct tm *tm;
64
65         gettimeofday(&tv, NULL);
66 #ifdef __MINGW64_VERSION_MAJOR
67         tm = _localtime32(&tv.tv_sec);
68 #else
69         tm = localtime(&tv.tv_sec);
70 #endif
71         strftime(timestamp, sizeof(timestamp), "%Y-%m-%dT%H:%M:%S", tm);
72         fprintf(logfile, "[%s.%06d %-5d] ", timestamp, (int)tv.tv_usec,
73                 (int)getpid());
74 #else
75         fprintf(logfile, "[%-5d] ", (int)getpid());
76 #endif
77 }
78
79 /*
80  * Write a message to the CCACHE_LOGFILE location (adding a newline).
81  */
82 void
83 cc_log(const char *format, ...)
84 {
85         va_list ap;
86
87         if (!init_log()) {
88                 return;
89         }
90
91         log_prefix();
92         va_start(ap, format);
93         vfprintf(logfile, format, ap);
94         va_end(ap);
95         fprintf(logfile, "\n");
96         fflush(logfile);
97 }
98
99 /*
100  * Log an executed command to the CCACHE_LOGFILE location.
101  */
102 void
103 cc_log_argv(const char *prefix, char **argv)
104 {
105         if (!init_log()) {
106                 return;
107         }
108
109         log_prefix();
110         fputs(prefix, logfile);
111         print_command(logfile, argv);
112         fflush(logfile);
113 }
114
115 /* something went badly wrong! */
116 void
117 fatal(const char *format, ...)
118 {
119         va_list ap;
120         char msg[1000];
121
122         va_start(ap, format);
123         vsnprintf(msg, sizeof(msg), format, ap);
124         va_end(ap);
125
126         cc_log("FATAL: %s", msg);
127         fprintf(stderr, "ccache: FATAL: %s\n", msg);
128
129         exit(1);
130 }
131
132 /*
133  * Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
134  */
135 void
136 copy_fd(int fd_in, int fd_out)
137 {
138         char buf[10240];
139         int n;
140         gzFile gz_in;
141
142         gz_in = gzdopen(dup(fd_in), "rb");
143
144         if (!gz_in) {
145                 fatal("Failed to copy fd");
146         }
147
148         while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
149                 ssize_t count, written = 0;
150                 do {
151                         count = write(fd_out, buf + written, n - written);
152                         if (count == -1 && errno != EINTR) {
153                                 fatal("Failed to copy fd");
154                         }
155                         written += count;
156                 } while (written < n);
157         }
158
159         gzclose(gz_in);
160 }
161
162 #ifndef HAVE_MKSTEMP
163 /* cheap and nasty mkstemp replacement */
164 int
165 mkstemp(char *template)
166 {
167         mktemp(template);
168         return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
169 }
170 #endif
171
172 /*
173  * Copy src to dest, decompressing src if needed. compress_dest decides whether
174  * dest will be compressed.
175  */
176 int
177 copy_file(const char *src, const char *dest, int compress_dest)
178 {
179         int fd_in = -1, fd_out = -1;
180         gzFile gz_in = NULL, gz_out = NULL;
181         char buf[10240];
182         int n, written;
183         char *tmp_name;
184 #ifndef _WIN32
185         mode_t mask;
186 #endif
187         struct stat st;
188         int errnum;
189
190         tmp_name = format("%s.%s.XXXXXX", dest, tmp_string());
191         cc_log("Copying %s to %s via %s (%s)",
192                src, dest, tmp_name, compress_dest ? "compressed": "uncompressed");
193
194         /* open source file */
195         fd_in = open(src, O_RDONLY | O_BINARY);
196         if (fd_in == -1) {
197                 cc_log("open error: %s", strerror(errno));
198                 return -1;
199         }
200
201         gz_in = gzdopen(fd_in, "rb");
202         if (!gz_in) {
203                 cc_log("gzdopen(src) error: %s", strerror(errno));
204                 close(fd_in);
205                 return -1;
206         }
207
208         /* open destination file */
209         fd_out = mkstemp(tmp_name);
210         if (fd_out == -1) {
211                 cc_log("mkstemp error: %s", strerror(errno));
212                 goto error;
213         }
214
215         if (compress_dest) {
216                 /*
217                  * A gzip file occupies at least 20 bytes, so it will always
218                  * occupy an entire filesystem block, even for empty files.
219                  * Turn off compression for empty files to save some space.
220                  */
221                 if (fstat(fd_in, &st) != 0) {
222                         cc_log("fstat error: %s", strerror(errno));
223                         goto error;
224                 }
225                 if (file_size(&st) == 0) {
226                         compress_dest = 0;
227                 }
228         }
229
230         if (compress_dest) {
231                 gz_out = gzdopen(dup(fd_out), "wb");
232                 if (!gz_out) {
233                         cc_log("gzdopen(dest) error: %s", strerror(errno));
234                         goto error;
235                 }
236         }
237
238         while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
239                 if (compress_dest) {
240                         written = gzwrite(gz_out, buf, n);
241                 } else {
242                         ssize_t count;
243                         written = 0;
244                         do {
245                                 count = write(fd_out, buf + written, n - written);
246                                 if (count == -1 && errno != EINTR) {
247                                         break;
248                                 }
249                                 written += count;
250                         } while (written < n);
251                 }
252                 if (written != n) {
253                         if (compress_dest) {
254                                 cc_log("gzwrite error: %s (errno: %s)",
255                                        gzerror(gz_in, &errnum),
256                                        strerror(errno));
257                         } else {
258                                 cc_log("write error: %s", strerror(errno));
259                         }
260                         goto error;
261                 }
262         }
263
264         /*
265          * gzeof won't tell if there's an error in the trailing CRC, so we must check
266          * gzerror before considering everything OK.
267          */
268         gzerror(gz_in, &errnum);
269         if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
270                 cc_log("gzread error: %s (errno: %s)",
271                        gzerror(gz_in, &errnum), strerror(errno));
272                 gzclose(gz_in);
273                 if (gz_out) {
274                         gzclose(gz_out);
275                 }
276                 close(fd_out);
277                 tmp_unlink(tmp_name);
278                 free(tmp_name);
279                 return -1;
280         }
281
282         gzclose(gz_in);
283         gz_in = NULL;
284         if (gz_out) {
285                 gzclose(gz_out);
286                 gz_out = NULL;
287         }
288
289 #ifndef _WIN32
290         /* get perms right on the tmp file */
291         mask = umask(0);
292         fchmod(fd_out, 0666 & ~mask);
293         umask(mask);
294 #endif
295
296         /* the close can fail on NFS if out of space */
297         if (close(fd_out) == -1) {
298                 cc_log("close error: %s", strerror(errno));
299                 goto error;
300         }
301
302         if (x_rename(tmp_name, dest) == -1) {
303                 cc_log("rename error: %s", strerror(errno));
304                 goto error;
305         }
306
307         free(tmp_name);
308
309         return 0;
310
311 error:
312         if (gz_in) {
313                 gzclose(gz_in);
314         }
315         if (gz_out) {
316                 gzclose(gz_out);
317         }
318         if (fd_out != -1) {
319                 close(fd_out);
320         }
321         tmp_unlink(tmp_name);
322         free(tmp_name);
323         return -1;
324 }
325
326 /* Run copy_file() and, if successful, delete the source file. */
327 int
328 move_file(const char *src, const char *dest, int compress_dest)
329 {
330         int ret;
331
332         ret = copy_file(src, dest, compress_dest);
333         if (ret != -1) {
334                 x_unlink(src);
335         }
336         return ret;
337 }
338
339 /*
340  * Like move_file(), but assumes that src is uncompressed and that src and dest
341  * are on the same file system.
342  */
343 int
344 move_uncompressed_file(const char *src, const char *dest, int compress_dest)
345 {
346         if (compress_dest) {
347                 return move_file(src, dest, compress_dest);
348         } else {
349                 return x_rename(src, dest);
350         }
351 }
352
353 /* test if a file is zlib compressed */
354 bool
355 file_is_compressed(const char *filename)
356 {
357         FILE *f;
358
359         f = fopen(filename, "rb");
360         if (!f) {
361                 return false;
362         }
363
364         /* test if file starts with 1F8B, which is zlib's
365          * magic number */
366         if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
367                 fclose(f);
368                 return false;
369         }
370
371         fclose(f);
372         return true;
373 }
374
375 /* make sure a directory exists */
376 int
377 create_dir(const char *dir)
378 {
379         struct stat st;
380         if (stat(dir, &st) == 0) {
381                 if (S_ISDIR(st.st_mode)) {
382                         return 0;
383                 }
384                 errno = ENOTDIR;
385                 return 1;
386         }
387         if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
388                 return 1;
389         }
390         return 0;
391 }
392
393 /*
394  * Return a static string with the current hostname.
395  */
396 const char *
397 get_hostname(void)
398 {
399         static char hostname[200] = "";
400
401         if (!hostname[0]) {
402                 strcpy(hostname, "unknown");
403 #if HAVE_GETHOSTNAME
404                 gethostname(hostname, sizeof(hostname)-1);
405 #endif
406                 hostname[sizeof(hostname)-1] = 0;
407         }
408
409         return hostname;
410 }
411
412 /*
413  * Return a string to be used to distinguish temporary files. Also tries to
414  * cope with NFS by adding the local hostname.
415  */
416 const char *
417 tmp_string(void)
418 {
419         static char *ret;
420
421         if (!ret) {
422                 ret = format("%s.%u", get_hostname(), (unsigned)getpid());
423         }
424
425         return ret;
426 }
427
428 /* Return the hash result as a hex string. Caller frees. */
429 char *
430 format_hash_as_string(const unsigned char *hash, unsigned size)
431 {
432         char *ret;
433         int i;
434
435         ret = x_malloc(53);
436         for (i = 0; i < 16; i++) {
437                 sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
438         }
439         sprintf(&ret[i*2], "-%u", size);
440
441         return ret;
442 }
443
444 char const CACHEDIR_TAG[] =
445         "Signature: 8a477f597d28d172789f06886806bc55\n"
446         "# This file is a cache directory tag created by ccache.\n"
447         "# For information about cache directory tags, see:\n"
448         "#      http://www.brynosaurus.com/cachedir/\n";
449
450 int
451 create_cachedirtag(const char *dir)
452 {
453         struct stat st;
454         FILE *f;
455         char *filename = format("%s/CACHEDIR.TAG", dir);
456         if (stat(filename, &st) == 0) {
457                 if (S_ISREG(st.st_mode)) {
458                         goto success;
459                 }
460                 errno = EEXIST;
461                 goto error;
462         }
463         f = fopen(filename, "w");
464         if (!f) goto error;
465         if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
466                 fclose(f);
467                 goto error;
468         }
469         if (fclose(f)) goto error;
470 success:
471         free(filename);
472         return 0;
473 error:
474         free(filename);
475         return 1;
476 }
477
478 /* Construct a string according to a format. Caller frees. */
479 char *
480 format(const char *format, ...)
481 {
482         va_list ap;
483         char *ptr = NULL;
484
485         va_start(ap, format);
486         if (vasprintf(&ptr, format, ap) == -1) {
487                 fatal("Out of memory in format");
488         }
489         va_end(ap);
490
491         if (!*ptr) fatal("Internal error in format");
492         return ptr;
493 }
494
495 /*
496   this is like strdup() but dies if the malloc fails
497 */
498 char *
499 x_strdup(const char *s)
500 {
501         char *ret;
502         ret = strdup(s);
503         if (!ret) {
504                 fatal("Out of memory in x_strdup");
505         }
506         return ret;
507 }
508
509 /*
510   this is like strndup() but dies if the malloc fails
511 */
512 char *
513 x_strndup(const char *s, size_t n)
514 {
515         char *ret;
516 #ifndef HAVE_STRNDUP
517         size_t m;
518
519         if (!s)
520                 return NULL;
521         m = 0;
522         while (m < n && s[m]) {
523                 m++;
524         }
525         ret = malloc(m + 1);
526         if (ret) {
527                 memcpy(ret, s, m);
528                 ret[m] = '\0';
529         }
530 #else
531         ret = strndup(s, n);
532 #endif
533         if (!ret) {
534                 fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
535         }
536         return ret;
537 }
538
539 /*
540   this is like malloc() but dies if the malloc fails
541 */
542 void *
543 x_malloc(size_t size)
544 {
545         void *ret;
546         if (size == 0) {
547                 /*
548                  * malloc() may return NULL if size is zero, so always do this to make sure
549                  * that the code handles it regardless of platform.
550                  */
551                 return NULL;
552         }
553         ret = malloc(size);
554         if (!ret) {
555                 fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
556         }
557         return ret;
558 }
559
560 /* This is like calloc() but dies if the allocation fails. */
561 void *
562 x_calloc(size_t nmemb, size_t size)
563 {
564         void *ret;
565         if (nmemb * size == 0) {
566                 /*
567                  * calloc() may return NULL if nmemb or size is 0, so always do this to
568                  * make sure that the code handles it regardless of platform.
569                  */
570                 return NULL;
571         }
572         ret = calloc(nmemb, size);
573         if (!ret) {
574                 fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
575         }
576         return ret;
577 }
578
579 /*
580   this is like realloc() but dies if the malloc fails
581 */
582 void *
583 x_realloc(void *ptr, size_t size)
584 {
585         void *p2;
586         if (!ptr) return x_malloc(size);
587         p2 = realloc(ptr, size);
588         if (!p2) {
589                 fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
590         }
591         return p2;
592 }
593
594
595 /*
596  * This is like x_asprintf() but frees *ptr if *ptr != NULL.
597  */
598 void
599 x_asprintf2(char **ptr, const char *format, ...)
600 {
601         char *saved = *ptr;
602         va_list ap;
603
604         *ptr = NULL;
605         va_start(ap, format);
606         if (vasprintf(ptr, format, ap) == -1) {
607                 fatal("Out of memory in x_asprintf2");
608         }
609         va_end(ap);
610
611         if (!ptr) fatal("Out of memory in x_asprintf2");
612         if (saved) {
613                 free(saved);
614         }
615 }
616
617 /*
618  * Recursive directory traversal. fn() is called on all entries in the tree.
619  */
620 void
621 traverse(const char *dir, void (*fn)(const char *, struct stat *))
622 {
623         DIR *d;
624         struct dirent *de;
625
626         d = opendir(dir);
627         if (!d) return;
628
629         while ((de = readdir(d))) {
630                 char *fname;
631                 struct stat st;
632
633                 if (str_eq(de->d_name, ".")) continue;
634                 if (str_eq(de->d_name, "..")) continue;
635
636                 if (strlen(de->d_name) == 0) continue;
637
638                 fname = format("%s/%s", dir, de->d_name);
639                 if (lstat(fname, &st)) {
640                         if (errno != ENOENT) {
641                                 perror(fname);
642                         }
643                         free(fname);
644                         continue;
645                 }
646
647                 if (S_ISDIR(st.st_mode)) {
648                         traverse(fname, fn);
649                 }
650
651                 fn(fname, &st);
652                 free(fname);
653         }
654
655         closedir(d);
656 }
657
658
659 /* return the base name of a file - caller frees */
660 char *
661 basename(const char *s)
662 {
663         char *p;
664         p = strrchr(s, '/');
665         if (p) s = p + 1;
666 #ifdef _WIN32
667         p = strrchr(s, '\\');
668         if (p) s = p + 1;
669 #endif
670
671         return x_strdup(s);
672 }
673
674 /* return the dir name of a file - caller frees */
675 char *
676 dirname(char *s)
677 {
678         char *p;
679         char *p2 = NULL;
680         s = x_strdup(s);
681         p = strrchr(s, '/');
682 #ifdef _WIN32
683         p2 = strrchr(s, '\\');
684 #endif
685         if (p < p2)
686                 p = p2;
687         if (p) {
688                 *p = 0;
689                 return s;
690         } else {
691                 free(s);
692                 return x_strdup(".");
693         }
694 }
695
696 /*
697  * Return the file extension (including the dot) of a path as a pointer into
698  * path. If path has no file extension, the empty string and the end of path is
699  * returned.
700  */
701 const char *
702 get_extension(const char *path)
703 {
704         size_t len = strlen(path);
705         const char *p;
706
707         for (p = &path[len - 1]; p >= path; --p) {
708                 if (*p == '.') {
709                         return p;
710                 }
711                 if (*p == '/') {
712                         break;
713                 }
714         }
715         return &path[len];
716 }
717
718 /*
719  * Return a string containing the given path without the filename extension.
720  * Caller frees.
721  */
722 char *
723 remove_extension(const char *path)
724 {
725         return x_strndup(path, strlen(path) - strlen(get_extension(path)));
726 }
727
728 /* return size on disk of a file */
729 size_t
730 file_size(struct stat *st)
731 {
732 #ifdef _WIN32
733         return (st->st_size + 1023) & ~1023;
734 #else
735         size_t size = st->st_blocks * 512;
736         if ((size_t)st->st_size > size) {
737                 /* probably a broken stat() call ... */
738                 size = (st->st_size + 1023) & ~1023;
739         }
740         return size;
741 #endif
742 }
743
744 /* a safe open/create for read-write */
745 int
746 safe_open(const char *fname)
747 {
748         int fd = open(fname, O_RDWR|O_BINARY);
749         if (fd == -1 && errno == ENOENT) {
750                 fd = open(fname, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0666);
751                 if (fd == -1 && errno == EEXIST) {
752                         fd = open(fname, O_RDWR|O_BINARY);
753                 }
754         }
755         return fd;
756 }
757
758 /* Format a size (in KiB) as a human-readable string. Caller frees. */
759 char *
760 format_size(size_t v)
761 {
762         char *s;
763         if (v >= 1024*1024) {
764                 s = format("%.1f Gbytes", v/((double)(1024*1024)));
765         } else if (v >= 1024) {
766                 s = format("%.1f Mbytes", v/((double)(1024)));
767         } else {
768                 s = format("%.0f Kbytes", (double)v);
769         }
770         return s;
771 }
772
773 /* return a value in multiples of 1024 give a string that can end
774    in K, M or G
775 */
776 size_t
777 value_units(const char *s)
778 {
779         char m;
780         double v = atof(s);
781         m = s[strlen(s)-1];
782         switch (m) {
783         case 'G':
784         case 'g':
785         default:
786                 v *= 1024*1024;
787                 break;
788         case 'M':
789         case 'm':
790                 v *= 1024;
791                 break;
792         case 'K':
793         case 'k':
794                 v *= 1;
795                 break;
796         }
797         return (size_t)v;
798 }
799
800 #ifndef _WIN32
801 static long
802 path_max(const char *path)
803 {
804 #ifdef PATH_MAX
805         (void)path;
806         return PATH_MAX;
807 #elif defined(MAXPATHLEN)
808         (void)path;
809         return MAXPATHLEN;
810 #elif defined(_PC_PATH_MAX)
811         long maxlen = pathconf(path, _PC_PATH_MAX);
812         if (maxlen >= 4096) {
813                 return maxlen;
814         } else {
815                 return 4096;
816         }
817 #endif
818 }
819
820 /*
821   a sane realpath() function, trying to cope with stupid path limits and
822   a broken API
823 */
824 char *
825 x_realpath(const char *path)
826 {
827         long maxlen = path_max(path);
828         char *ret, *p;
829
830         ret = x_malloc(maxlen);
831
832 #if HAVE_REALPATH
833         p = realpath(path, ret);
834 #else
835         /* yes, there are such systems. This replacement relies on
836            the fact that when we call x_realpath we only care about symlinks */
837         {
838                 int len = readlink(path, ret, maxlen-1);
839                 if (len == -1) {
840                         free(ret);
841                         return NULL;
842                 }
843                 ret[len] = 0;
844                 p = ret;
845         }
846 #endif
847         if (p) {
848                 p = x_strdup(p);
849                 free(ret);
850                 return p;
851         }
852         free(ret);
853         return NULL;
854 }
855 #endif /* !_WIN32 */
856
857 /* a getcwd that will returns an allocated buffer */
858 char *
859 gnu_getcwd(void)
860 {
861         unsigned size = 128;
862
863         while (1) {
864                 char *buffer = (char *)x_malloc(size);
865                 if (getcwd(buffer, size) == buffer) {
866                         return buffer;
867                 }
868                 free(buffer);
869                 if (errno != ERANGE) {
870                         cc_log("getcwd error: %d (%s)", errno, strerror(errno));
871                         return NULL;
872                 }
873                 size *= 2;
874         }
875 }
876
877 /* create an empty file */
878 int
879 create_empty_file(const char *fname)
880 {
881         int fd;
882
883         fd = open(fname, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL|O_BINARY, 0666);
884         if (fd == -1) {
885                 return -1;
886         }
887         close(fd);
888         return 0;
889 }
890
891 /*
892  * Return current user's home directory, or NULL if it can't be determined.
893  */
894 const char *
895 get_home_directory(void)
896 {
897         const char *p = getenv("HOME");
898         if (p) {
899                 return p;
900         }
901 #ifdef HAVE_GETPWUID
902         {
903                 struct passwd *pwd = getpwuid(getuid());
904                 if (pwd) {
905                         return pwd->pw_dir;
906                 }
907         }
908 #endif
909         return NULL;
910 }
911
912 /*
913  * Get the current directory by reading $PWD. If $PWD isn't sane, gnu_getcwd()
914  * is used. Caller frees.
915  */
916 char *
917 get_cwd(void)
918 {
919         char *pwd;
920         char *cwd;
921         struct stat st_pwd;
922         struct stat st_cwd;
923
924         cwd = gnu_getcwd();
925         if (!cwd) {
926                 return NULL;
927         }
928         pwd = getenv("PWD");
929         if (!pwd) {
930                 return cwd;
931         }
932         if (stat(pwd, &st_pwd) != 0) {
933                 return cwd;
934         }
935         if (stat(cwd, &st_cwd) != 0) {
936                 return cwd;
937         }
938         if (st_pwd.st_dev == st_cwd.st_dev && st_pwd.st_ino == st_cwd.st_ino) {
939                 free(cwd);
940                 return x_strdup(pwd);
941         } else {
942                 return cwd;
943         }
944 }
945
946 /*
947  * Check whether s1 and s2 have the same executable name.
948  */
949 bool
950 same_executable_name(const char *s1, const char *s2)
951 {
952 #ifdef _WIN32
953         bool eq = strcasecmp(s1, s2) == 0;
954         if (!eq) {
955                 char *tmp = format("%s.exe", s2);
956                 eq = strcasecmp(s1, tmp) == 0;
957                 free(tmp);
958         }
959         return eq;
960 #else
961         return str_eq(s1, s2);
962 #endif
963 }
964
965 /*
966  * Compute the length of the longest directory path that is common to two
967  * strings.
968  */
969 size_t
970 common_dir_prefix_length(const char *s1, const char *s2)
971 {
972         const char *p1 = s1;
973         const char *p2 = s2;
974
975         while (*p1 && *p2 && *p1 == *p2) {
976                 ++p1;
977                 ++p2;
978         }
979         while (p1 > s1 && ((*p1 && *p1 != '/' ) || (*p2 && *p2 != '/'))) {
980                 p1--;
981                 p2--;
982         }
983         return p1 - s1;
984 }
985
986 /*
987  * Compute a relative path from from to to. Caller frees.
988  */
989 char *
990 get_relative_path(const char *from, const char *to)
991 {
992         size_t common_prefix_len;
993         int i;
994         const char *p;
995         char *result;
996
997         if (!*to || *to != '/') {
998                 return x_strdup(to);
999         }
1000
1001         result = x_strdup("");
1002         common_prefix_len = common_dir_prefix_length(from, to);
1003         for (p = from + common_prefix_len; *p; p++) {
1004                 if (*p == '/') {
1005                         x_asprintf2(&result, "../%s", result);
1006                 }
1007         }
1008         if (strlen(to) > common_prefix_len) {
1009                 p = to + common_prefix_len + 1;
1010                 while (*p == '/') {
1011                         p++;
1012                 }
1013                 x_asprintf2(&result, "%s%s", result, p);
1014         }
1015         i = strlen(result) - 1;
1016         while (i >= 0 && result[i] == '/') {
1017                 result[i] = '\0';
1018                 i--;
1019         }
1020         if (str_eq(result, "")) {
1021                 free(result);
1022                 result = x_strdup(".");
1023         }
1024         return result;
1025 }
1026
1027 /*
1028  * Return whether path is absolute.
1029  */
1030 bool
1031 is_absolute_path(const char *path)
1032 {
1033 #ifdef _WIN32
1034         return path[0] && path[1] == ':';
1035 #else
1036         return path[0] == '/';
1037 #endif
1038 }
1039
1040 /*
1041  * Return whether the argument is a full path.
1042  */
1043 bool
1044 is_full_path(const char *path)
1045 {
1046         if (strchr(path, '/'))
1047                 return 1;
1048 #ifdef _WIN32
1049         if (strchr(path, '\\'))
1050                 return 1;
1051 #endif
1052         return 0;
1053 }
1054
1055 /*
1056  * Update the modification time of a file in the cache to save it from LRU
1057  * cleanup.
1058  */
1059 void
1060 update_mtime(const char *path)
1061 {
1062 #ifdef HAVE_UTIMES
1063         utimes(path, NULL);
1064 #else
1065         utime(path, NULL);
1066 #endif
1067 }
1068
1069 /*
1070  * Rename oldpath to newpath (deleting newpath).
1071  */
1072 int
1073 x_rename(const char *oldpath, const char *newpath)
1074 {
1075 #ifdef _WIN32
1076         /* Windows' rename() refuses to overwrite an existing file. */
1077         unlink(newpath);  /* not x_unlink, as x_unlink calls x_rename */
1078 #endif
1079         return rename(oldpath, newpath);
1080 }
1081
1082 /*
1083  * Remove path, NFS hazardous. Use only for temporary files that will not exist
1084  * on other systems. That is, the path should include tmp_string().
1085  */
1086 int
1087 tmp_unlink(const char *path)
1088 {
1089         cc_log("Unlink %s (as-tmp)", path);
1090         return unlink(path);
1091 }
1092
1093 /*
1094  * Remove path, NFS safe.
1095  */
1096 int
1097 x_unlink(const char *path)
1098 {
1099         /*
1100          * If path is on an NFS share, unlink isn't atomic, so we rename to a temp
1101          * file. We don't care if the temp file is trashed, so it's always safe to
1102          * unlink it first.
1103          */
1104         const char* tmp_name = format("%s.%s.rmXXXXXX", path, tmp_string());
1105         cc_log("Unlink %s via %s", path, tmp_name);
1106         if (x_rename(path, tmp_name) == -1) {
1107                 return -1;
1108         }
1109         if (unlink(tmp_name) == -1) {
1110                 return -1;
1111         }
1112         return 0;
1113 }
1114
1115 #ifndef _WIN32
1116 /* Like readlink() but returns the string or NULL on failure. Caller frees. */
1117 char *
1118 x_readlink(const char *path)
1119 {
1120         long maxlen = path_max(path);
1121         ssize_t len;
1122         char *buf;
1123 #ifdef PATH_MAX
1124         maxlen = PATH_MAX;
1125 #elif defined(MAXPATHLEN)
1126         maxlen = MAXPATHLEN;
1127 #elif defined(_PC_PATH_MAX)
1128         maxlen = pathconf(path, _PC_PATH_MAX);
1129 #endif
1130         if (maxlen < 4096) maxlen = 4096;
1131
1132         buf = x_malloc(maxlen);
1133         len = readlink(path, buf, maxlen-1);
1134         if (len == -1) {
1135                 free(buf);
1136                 return NULL;
1137         }
1138         buf[len] = 0;
1139         return buf;
1140 }
1141 #endif
1142
1143 /*
1144  * Reads the content of a file. Size hint 0 means no hint. Returns true on
1145  * success, otherwise false.
1146  */
1147 bool
1148 read_file(const char *path, size_t size_hint, char **data, size_t *size)
1149 {
1150         int fd, ret;
1151         size_t pos = 0, allocated;
1152
1153         if (size_hint == 0) {
1154                 struct stat st;
1155                 if (stat(path, &st) == 0) {
1156                         size_hint = st.st_size;
1157                 }
1158         }
1159         size_hint = (size_hint < 1024) ? 1024 : size_hint;
1160
1161         fd = open(path, O_RDONLY);
1162         if (fd == -1) {
1163                 return false;
1164         }
1165         allocated = size_hint;
1166         *data = x_malloc(allocated);
1167         ret = 0;
1168         while (true) {
1169                 if (pos > allocated / 2) {
1170                         allocated *= 2;
1171                         *data = x_realloc(*data, allocated);
1172                 }
1173                 ret = read(fd, *data + pos, allocated - pos);
1174                 if (ret == 0 || (ret == -1 && errno != EINTR)) {
1175                         break;
1176                 }
1177                 if (ret > 0) {
1178                         pos += ret;
1179                 }
1180         }
1181         close(fd);
1182         if (ret == -1) {
1183                 cc_log("Failed reading %s", path);
1184                 free(*data);
1185                 *data = NULL;
1186                 return false;
1187         }
1188
1189         *size = pos;
1190         return true;
1191 }
1192
1193 /*
1194  * Return the content (with NUL termination) of a text file, or NULL on error.
1195  * Caller frees.
1196  */
1197 char *
1198 read_text_file(const char *path)
1199 {
1200         size_t size;
1201         char *data;
1202
1203         if (read_file(path, 0, &data, &size)) {
1204                 data = x_realloc(data, size + 1);
1205                 data[size] = '\0';
1206                 return data;
1207         } else {
1208                 return NULL;
1209         }
1210 }