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