Imported Upstream version 3.2.5
[platform/upstream/ccache.git] / util.c
1 /*
2  * Copyright (C) 2002 Andrew Tridgell
3  * Copyright (C) 2009-2016 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 struct conf *conf;
42
43         if (logfile) {
44                 return true;
45         }
46         assert(conf);
47         if (str_eq(conf->log_file, "")) {
48                 return false;
49         }
50         logfile = fopen(conf->log_file, "a");
51         if (logfile) {
52 #ifndef _WIN32
53                 int fd = fileno(logfile);
54                 int flags = fcntl(fd, F_GETFD, 0);
55                 if (flags >= 0) {
56                         fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
57                 }
58 #endif
59                 return true;
60         } else {
61                 return false;
62         }
63 }
64
65 static void
66 log_prefix(bool log_updated_time)
67 {
68 #ifdef HAVE_GETTIMEOFDAY
69         static char prefix[200];
70
71         if (log_updated_time) {
72                 char timestamp[100];
73                 struct tm *tm;
74                 struct timeval tv;
75                 gettimeofday(&tv, NULL);
76 #ifdef __MINGW64_VERSION_MAJOR
77                 tm = localtime((time_t *)&tv.tv_sec);
78 #else
79                 tm = localtime(&tv.tv_sec);
80 #endif
81                 strftime(timestamp, sizeof(timestamp), "%Y-%m-%dT%H:%M:%S", tm);
82                 snprintf(prefix, sizeof(prefix),
83                          "[%s.%06d %-5d] ", timestamp, (int)tv.tv_usec, (int)getpid());
84         }
85         fputs(prefix, logfile);
86 #else
87         fprintf(logfile, "[%-5d] ", (int)getpid());
88 #endif
89 }
90
91 static long
92 path_max(const char *path)
93 {
94 #ifdef PATH_MAX
95         (void)path;
96         return PATH_MAX;
97 #elif defined(MAXPATHLEN)
98         (void)path;
99         return MAXPATHLEN;
100 #elif defined(_PC_PATH_MAX)
101         long maxlen = pathconf(path, _PC_PATH_MAX);
102         if (maxlen >= 4096) {
103                 return maxlen;
104         } else {
105                 return 4096;
106         }
107 #endif
108 }
109
110 /*
111  * Warn about failure writing to the log file and then exit.
112  */
113 static void
114 warn_log_fail(void)
115 {
116         extern struct conf *conf;
117
118         /* Note: Can't call fatal() since that would lead to recursion. */
119         fprintf(stderr, "ccache: error: Failed to write to %s: %s\n",
120                 conf->log_file, strerror(errno));
121         x_exit(EXIT_FAILURE);
122 }
123
124 static void
125 vlog(const char *format, va_list ap, bool log_updated_time)
126 {
127         int rc1, rc2;
128         if (!init_log()) {
129                 return;
130         }
131
132         log_prefix(log_updated_time);
133         rc1 = vfprintf(logfile, format, ap);
134         rc2 = fprintf(logfile, "\n");
135         if (rc1 < 0 || rc2 < 0) {
136                 warn_log_fail();
137         }
138 }
139
140 /*
141  * Write a message to the log file (adding a newline) and flush.
142  */
143 void
144 cc_log(const char *format, ...)
145 {
146         va_list ap;
147         va_start(ap, format);
148         vlog(format, ap, true);
149         va_end(ap);
150         if (logfile) {
151                 fflush(logfile);
152         }
153 }
154
155 /*
156  * Write a message to the log file (adding a newline) without flushing and with
157  * a reused timestamp.
158  */
159 void
160 cc_bulklog(const char *format, ...)
161 {
162         va_list ap;
163         va_start(ap, format);
164         vlog(format, ap, false);
165         va_end(ap);
166 }
167
168 /*
169  * Log an executed command to the CCACHE_LOGFILE location.
170  */
171 void
172 cc_log_argv(const char *prefix, char **argv)
173 {
174         int rc;
175         if (!init_log()) {
176                 return;
177         }
178
179         log_prefix(true);
180         fputs(prefix, logfile);
181         print_command(logfile, argv);
182         rc = fflush(logfile);
183         if (rc) {
184                 warn_log_fail();
185         }
186 }
187
188 /* something went badly wrong! */
189 void
190 fatal(const char *format, ...)
191 {
192         va_list ap;
193         char msg[1000];
194
195         va_start(ap, format);
196         vsnprintf(msg, sizeof(msg), format, ap);
197         va_end(ap);
198
199         cc_log("FATAL: %s", msg);
200         fprintf(stderr, "ccache: error: %s\n", msg);
201
202         x_exit(1);
203 }
204
205 /*
206  * Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
207  */
208 void
209 copy_fd(int fd_in, int fd_out)
210 {
211         char buf[10240];
212         int n;
213         gzFile gz_in;
214
215         gz_in = gzdopen(dup(fd_in), "rb");
216
217         if (!gz_in) {
218                 fatal("Failed to copy fd");
219         }
220
221         while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
222                 ssize_t written = 0;
223                 do {
224                         ssize_t count = write(fd_out, buf + written, n - written);
225                         if (count == -1) {
226                                 if (errno != EAGAIN && errno != EINTR) {
227                                         fatal("Failed to copy fd");
228                                 }
229                         } else {
230                                 written += count;
231                         }
232                 } while (written < n);
233         }
234
235         gzclose(gz_in);
236 }
237
238 #ifndef HAVE_MKSTEMP
239 /* cheap and nasty mkstemp replacement */
240 int
241 mkstemp(char *template)
242 {
243         mktemp(template);
244         return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
245 }
246 #endif
247
248 #ifndef _WIN32
249 static mode_t
250 get_umask(void)
251 {
252         static bool mask_retrieved = false;
253         static mode_t mask;
254         if (!mask_retrieved) {
255                 mask = umask(0);
256                 umask(mask);
257                 mask_retrieved = true;
258         }
259         return mask;
260 }
261 #endif
262
263 /*
264  * Copy src to dest, decompressing src if needed. compress_level > 0 decides
265  * whether dest will be compressed, and with which compression level. Returns 0
266  * on success and -1 on failure. On failure, errno represents the error.
267  */
268 int
269 copy_file(const char *src, const char *dest, int compress_level)
270 {
271         int fd_in, fd_out;
272         gzFile gz_in = NULL, gz_out = NULL;
273         char buf[10240];
274         int n, written;
275         char *tmp_name;
276         struct stat st;
277         int errnum;
278         int saved_errno = 0;
279
280         /* open destination file */
281         tmp_name = x_strdup(dest);
282         fd_out = create_tmp_fd(&tmp_name);
283         cc_log("Copying %s to %s via %s (%scompressed)",
284                src, dest, tmp_name, compress_level > 0 ? "" : "un");
285
286         /* open source file */
287         fd_in = open(src, O_RDONLY | O_BINARY);
288         if (fd_in == -1) {
289                 saved_errno = errno;
290                 cc_log("open error: %s", strerror(saved_errno));
291                 goto error;
292         }
293
294         gz_in = gzdopen(fd_in, "rb");
295         if (!gz_in) {
296                 saved_errno = errno;
297                 cc_log("gzdopen(src) error: %s", strerror(saved_errno));
298                 close(fd_in);
299                 goto error;
300         }
301
302         if (compress_level > 0) {
303                 /*
304                  * A gzip file occupies at least 20 bytes, so it will always
305                  * occupy an entire filesystem block, even for empty files.
306                  * Turn off compression for empty files to save some space.
307                  */
308                 if (x_fstat(fd_in, &st) != 0) {
309                         goto error;
310                 }
311                 if (file_size(&st) == 0) {
312                         compress_level = 0;
313                 }
314         }
315
316         if (compress_level > 0) {
317                 gz_out = gzdopen(dup(fd_out), "wb");
318                 if (!gz_out) {
319                         saved_errno = errno;
320                         cc_log("gzdopen(dest) error: %s", strerror(saved_errno));
321                         goto error;
322                 }
323                 gzsetparams(gz_out, compress_level, Z_DEFAULT_STRATEGY);
324         }
325
326         while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
327                 if (compress_level > 0) {
328                         written = gzwrite(gz_out, buf, n);
329                 } else {
330                         written = 0;
331                         do {
332                                 ssize_t count = write(fd_out, buf + written, n - written);
333                                 if (count == -1 && errno != EINTR) {
334                                         saved_errno = errno;
335                                         break;
336                                 }
337                                 written += count;
338                         } while (written < n);
339                 }
340                 if (written != n) {
341                         if (compress_level > 0) {
342                                 cc_log("gzwrite error: %s (errno: %s)",
343                                        gzerror(gz_in, &errnum),
344                                        strerror(saved_errno));
345                         } else {
346                                 cc_log("write error: %s", strerror(saved_errno));
347                         }
348                         goto error;
349                 }
350         }
351
352         /*
353          * gzeof won't tell if there's an error in the trailing CRC, so we must check
354          * gzerror before considering everything OK.
355          */
356         gzerror(gz_in, &errnum);
357         if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
358                 saved_errno = errno;
359                 cc_log("gzread error: %s (errno: %s)",
360                        gzerror(gz_in, &errnum), strerror(saved_errno));
361                 gzclose(gz_in);
362                 if (gz_out) {
363                         gzclose(gz_out);
364                 }
365                 close(fd_out);
366                 tmp_unlink(tmp_name);
367                 free(tmp_name);
368                 return -1;
369         }
370
371         gzclose(gz_in);
372         gz_in = NULL;
373         if (gz_out) {
374                 gzclose(gz_out);
375                 gz_out = NULL;
376         }
377
378 #ifndef _WIN32
379         fchmod(fd_out, 0666 & ~get_umask());
380 #endif
381
382         /* the close can fail on NFS if out of space */
383         if (close(fd_out) == -1) {
384                 saved_errno = errno;
385                 cc_log("close error: %s", strerror(saved_errno));
386                 goto error;
387         }
388
389         if (x_rename(tmp_name, dest) == -1) {
390                 saved_errno = errno;
391                 cc_log("rename error: %s", strerror(saved_errno));
392                 goto error;
393         }
394
395         free(tmp_name);
396
397         return 0;
398
399 error:
400         if (gz_in) {
401                 gzclose(gz_in);
402         }
403         if (gz_out) {
404                 gzclose(gz_out);
405         }
406         if (fd_out != -1) {
407                 close(fd_out);
408         }
409         tmp_unlink(tmp_name);
410         free(tmp_name);
411         errno = saved_errno;
412         return -1;
413 }
414
415 /* Run copy_file() and, if successful, delete the source file. */
416 int
417 move_file(const char *src, const char *dest, int compress_level)
418 {
419         int ret;
420
421         ret = copy_file(src, dest, compress_level);
422         if (ret != -1) {
423                 x_unlink(src);
424         }
425         return ret;
426 }
427
428 /*
429  * Like move_file(), but assumes that src is uncompressed and that src and dest
430  * are on the same file system.
431  */
432 int
433 move_uncompressed_file(const char *src, const char *dest, int compress_level)
434 {
435         if (compress_level > 0) {
436                 return move_file(src, dest, compress_level);
437         } else {
438                 return x_rename(src, dest);
439         }
440 }
441
442 /* test if a file is zlib compressed */
443 bool
444 file_is_compressed(const char *filename)
445 {
446         FILE *f;
447
448         f = fopen(filename, "rb");
449         if (!f) {
450                 return false;
451         }
452
453         /* test if file starts with 1F8B, which is zlib's
454          * magic number */
455         if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
456                 fclose(f);
457                 return false;
458         }
459
460         fclose(f);
461         return true;
462 }
463
464 /* make sure a directory exists */
465 int
466 create_dir(const char *dir)
467 {
468         struct stat st;
469         if (stat(dir, &st) == 0) {
470                 if (S_ISDIR(st.st_mode)) {
471                         return 0;
472                 }
473                 errno = ENOTDIR;
474                 return 1;
475         }
476         if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
477                 return 1;
478         }
479         return 0;
480 }
481
482 /* Create directories leading to path. Returns 0 on success, otherwise -1. */
483 int
484 create_parent_dirs(const char *path)
485 {
486         struct stat st;
487         int res;
488         char *parent = dirname(path);
489
490         if (stat(parent, &st) == 0) {
491                 if (S_ISDIR(st.st_mode)) {
492                         res = 0;
493                 } else {
494                         res = -1;
495                         errno = ENOTDIR;
496                 }
497         } else {
498                 res = create_parent_dirs(parent);
499                 if (res == 0) {
500                         res = mkdir(parent, 0777);
501                         /* Have to handle the condition of the directory already existing because
502                          * the file system could have changed in between calling stat and
503                          * actually creating the directory. This can happen when there are
504                          * multiple instances of ccache running and trying to create the same
505                          * directory chain, which usually is the case when the cache root does
506                          * not initially exist. As long as one of the processes creates the
507                          * directories then our condition is satisfied and we avoid a race
508                          * condition.
509                          */
510                         if (res != 0 && errno == EEXIST) {
511                                 res = 0;
512                         }
513                 } else {
514                         res = -1;
515                 }
516         }
517         free(parent);
518         return res;
519 }
520
521 /*
522  * Return a static string with the current hostname.
523  */
524 const char *
525 get_hostname(void)
526 {
527         static char hostname[260] = "";
528
529         if (hostname[0]) {
530                 return hostname;
531         }
532
533         strcpy(hostname, "unknown");
534 #if HAVE_GETHOSTNAME
535         gethostname(hostname, sizeof(hostname) - 1);
536 #elif defined(_WIN32)
537         const char *computer_name = getenv("COMPUTERNAME");
538         if (computer_name) {
539                 snprintf(hostname, sizeof(hostname), "%s", computer_name);
540                 return hostname;
541         }
542
543         WORD wVersionRequested;
544         WSADATA wsaData;
545         int err;
546
547         wVersionRequested = MAKEWORD(2, 2);
548
549         err = WSAStartup(wVersionRequested, &wsaData);
550         if (err != 0) {
551                 /* Tell the user that we could not find a usable Winsock DLL. */
552                 cc_log("WSAStartup failed with error: %d", err);
553                 return hostname;
554         }
555
556         if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
557                 /* Tell the user that we could not find a usable WinSock DLL. */
558                 cc_log("Could not find a usable version of Winsock.dll");
559                 WSACleanup();
560                 return hostname;
561         }
562
563         int result = gethostname(hostname, sizeof(hostname) - 1);
564         if (result != 0) {
565                 int last_error = WSAGetLastError();
566                 LPVOID lpMsgBuf;
567                 LPVOID lpDisplayBuf;
568                 DWORD dw = last_error;
569
570                 FormatMessage(
571                   FORMAT_MESSAGE_ALLOCATE_BUFFER |
572                   FORMAT_MESSAGE_FROM_SYSTEM |
573                   FORMAT_MESSAGE_IGNORE_INSERTS,
574                   NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
575                   (LPTSTR) &lpMsgBuf, 0, NULL);
576
577                 lpDisplayBuf = (LPVOID) LocalAlloc(
578                   LMEM_ZEROINIT,
579                   (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) __FILE__) + 200)
580                   * sizeof(TCHAR));
581                 _snprintf((LPTSTR) lpDisplayBuf,
582                           LocalSize(lpDisplayBuf) / sizeof(TCHAR),
583                           TEXT("%s failed with error %d: %s"), __FILE__, dw,
584                           lpMsgBuf);
585
586                 cc_log("can't get hostname OS returned error: %s", (char *)lpDisplayBuf);
587
588                 LocalFree(lpMsgBuf);
589                 LocalFree(lpDisplayBuf);
590         }
591         WSACleanup();
592 #endif
593
594         hostname[sizeof(hostname) - 1] = 0;
595         return hostname;
596 }
597
598 /*
599  * Return a string to be passed to mkstemp to create a temporary file. Also
600  * tries to cope with NFS by adding the local hostname.
601  */
602 const char *
603 tmp_string(void)
604 {
605         static char *ret;
606
607         if (!ret) {
608                 ret = format("%s.%u.XXXXXX", get_hostname(), (unsigned)getpid());
609         }
610
611         return ret;
612 }
613
614 /*
615  * Return the hash result as a hex string. Size -1 means don't include size
616  * suffix. Caller frees.
617  */
618 char *
619 format_hash_as_string(const unsigned char *hash, int size)
620 {
621         char *ret;
622         int i;
623
624         ret = x_malloc(53);
625         for (i = 0; i < 16; i++) {
626                 sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
627         }
628         if (size >= 0) {
629                 sprintf(&ret[i*2], "-%d", size);
630         }
631
632         return ret;
633 }
634
635 char const CACHEDIR_TAG[] =
636   "Signature: 8a477f597d28d172789f06886806bc55\n"
637   "# This file is a cache directory tag created by ccache.\n"
638   "# For information about cache directory tags, see:\n"
639   "#    http://www.brynosaurus.com/cachedir/\n";
640
641 int
642 create_cachedirtag(const char *dir)
643 {
644         struct stat st;
645         FILE *f;
646         char *filename = format("%s/CACHEDIR.TAG", dir);
647         if (stat(filename, &st) == 0) {
648                 if (S_ISREG(st.st_mode)) {
649                         goto success;
650                 }
651                 errno = EEXIST;
652                 goto error;
653         }
654         f = fopen(filename, "w");
655         if (!f) {
656                 goto error;
657         }
658         if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
659                 fclose(f);
660                 goto error;
661         }
662         if (fclose(f)) {
663                 goto error;
664         }
665 success:
666         free(filename);
667         return 0;
668 error:
669         free(filename);
670         return 1;
671 }
672
673 /* Construct a string according to a format. Caller frees. */
674 char *
675 format(const char *format, ...)
676 {
677         va_list ap;
678         char *ptr = NULL;
679
680         va_start(ap, format);
681         if (vasprintf(&ptr, format, ap) == -1) {
682                 fatal("Out of memory in format");
683         }
684         va_end(ap);
685
686         if (!*ptr) {
687                 fatal("Internal error in format");
688         }
689         return ptr;
690 }
691
692 /* This is like strdup() but dies if the malloc fails. */
693 char *
694 x_strdup(const char *s)
695 {
696         char *ret;
697         ret = strdup(s);
698         if (!ret) {
699                 fatal("Out of memory in x_strdup");
700         }
701         return ret;
702 }
703
704 /* This is like strndup() but dies if the malloc fails. */
705 char *
706 x_strndup(const char *s, size_t n)
707 {
708         char *ret;
709 #ifndef HAVE_STRNDUP
710         size_t m;
711
712         if (!s)
713                 return NULL;
714         m = 0;
715         while (m < n && s[m]) {
716                 m++;
717         }
718         ret = malloc(m + 1);
719         if (ret) {
720                 memcpy(ret, s, m);
721                 ret[m] = '\0';
722         }
723 #else
724         ret = strndup(s, n);
725 #endif
726         if (!ret) {
727                 fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
728         }
729         return ret;
730 }
731
732 /* This is like malloc() but dies if the malloc fails. */
733 void *
734 x_malloc(size_t size)
735 {
736         void *ret;
737         if (size == 0) {
738                 /*
739                  * malloc() may return NULL if size is zero, so always do this to make sure
740                  * that the code handles it regardless of platform.
741                  */
742                 return NULL;
743         }
744         ret = malloc(size);
745         if (!ret) {
746                 fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
747         }
748         return ret;
749 }
750
751 /* This is like calloc() but dies if the allocation fails. */
752 void *
753 x_calloc(size_t nmemb, size_t size)
754 {
755         void *ret;
756         if (nmemb * size == 0) {
757                 /*
758                  * calloc() may return NULL if nmemb or size is 0, so always do this to
759                  * make sure that the code handles it regardless of platform.
760                  */
761                 return NULL;
762         }
763         ret = calloc(nmemb, size);
764         if (!ret) {
765                 fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
766         }
767         return ret;
768 }
769
770 /* This is like realloc() but dies if the malloc fails. */
771 void *
772 x_realloc(void *ptr, size_t size)
773 {
774         void *p2;
775         if (!ptr) {
776                 return x_malloc(size);
777         }
778         p2 = realloc(ptr, size);
779         if (!p2) {
780                 fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
781         }
782         return p2;
783 }
784
785 /* This is like unsetenv. */
786 void x_unsetenv(const char *name)
787 {
788 #ifdef HAVE_UNSETENV
789         unsetenv(name);
790 #else
791         putenv(x_strdup(name)); /* Leak to environment. */
792 #endif
793 }
794
795 /* Like fstat() but also call cc_log on failure. */
796 int
797 x_fstat(int fd, struct stat *buf)
798 {
799         int result = fstat(fd, buf);
800         if (result != 0) {
801                 cc_log("Failed to fstat fd %d: %s", fd, strerror(errno));
802         }
803         return result;
804 }
805
806 /* Like lstat() but also call cc_log on failure. */
807 int
808 x_lstat(const char *pathname, struct stat *buf)
809 {
810         int result = lstat(pathname, buf);
811         if (result != 0) {
812                 cc_log("Failed to lstat %s: %s", pathname, strerror(errno));
813         }
814         return result;
815 }
816
817 /* Like stat() but also call cc_log on failure. */
818 int
819 x_stat(const char *pathname, struct stat *buf)
820 {
821         int result = stat(pathname, buf);
822         if (result != 0) {
823                 cc_log("Failed to stat %s: %s", pathname, strerror(errno));
824         }
825         return result;
826 }
827
828 /*
829  * Construct a string according to the format and store it in *ptr. The
830  * original *ptr is then freed.
831  */
832 void
833 reformat(char **ptr, const char *format, ...)
834 {
835         char *saved = *ptr;
836         va_list ap;
837
838         *ptr = NULL;
839         va_start(ap, format);
840         if (vasprintf(ptr, format, ap) == -1) {
841                 fatal("Out of memory in reformat");
842         }
843         va_end(ap);
844
845         if (!ptr) {
846                 fatal("Out of memory in reformat");
847         }
848         if (saved) {
849                 free(saved);
850         }
851 }
852
853 /*
854  * Recursive directory traversal. fn() is called on all entries in the tree.
855  */
856 void
857 traverse(const char *dir, void (*fn)(const char *, struct stat *))
858 {
859         DIR *d;
860         struct dirent *de;
861
862         d = opendir(dir);
863         if (!d) {
864                 return;
865         }
866
867         while ((de = readdir(d))) {
868                 char *fname;
869                 struct stat st;
870
871                 if (str_eq(de->d_name, ".")) {
872                         continue;
873                 }
874                 if (str_eq(de->d_name, "..")) {
875                         continue;
876                 }
877
878                 if (strlen(de->d_name) == 0) {
879                         continue;
880                 }
881
882                 fname = format("%s/%s", dir, de->d_name);
883                 if (lstat(fname, &st)) {
884                         if (errno != ENOENT && errno != ESTALE) {
885                                 fatal("lstat %s failed: %s", fname, strerror(errno));
886                         }
887                         free(fname);
888                         continue;
889                 }
890
891                 if (S_ISDIR(st.st_mode)) {
892                         traverse(fname, fn);
893                 }
894
895                 fn(fname, &st);
896                 free(fname);
897         }
898
899         closedir(d);
900 }
901
902
903 /* return the base name of a file - caller frees */
904 char *
905 basename(const char *path)
906 {
907         char *p;
908         p = strrchr(path, '/');
909         if (p) {
910                 path = p + 1;
911         }
912 #ifdef _WIN32
913         p = strrchr(path, '\\');
914         if (p) {
915                 path = p + 1;
916         }
917 #endif
918
919         return x_strdup(path);
920 }
921
922 /* return the dir name of a file - caller frees */
923 char *
924 dirname(const char *path)
925 {
926         char *p;
927 #ifdef _WIN32
928         char *p2;
929 #endif
930         char *s;
931         s = x_strdup(path);
932         p = strrchr(s, '/');
933 #ifdef _WIN32
934         p2 = strrchr(s, '\\');
935         if (!p || (p2 && p < p2)) {
936                 p = p2;
937         }
938 #endif
939         if (!p) {
940                 free(s);
941                 s = x_strdup(".");
942         } else if (p == s) {
943                 *(p + 1) = 0;
944         } else {
945                 *p = 0;
946         }
947         return s;
948 }
949
950 /*
951  * Return the file extension (including the dot) of a path as a pointer into
952  * path. If path has no file extension, the empty string and the end of path is
953  * returned.
954  */
955 const char *
956 get_extension(const char *path)
957 {
958         size_t len = strlen(path);
959         const char *p;
960
961         for (p = &path[len - 1]; p >= path; --p) {
962                 if (*p == '.') {
963                         return p;
964                 }
965                 if (*p == '/') {
966                         break;
967                 }
968         }
969         return &path[len];
970 }
971
972 /*
973  * Return a string containing the given path without the filename extension.
974  * Caller frees.
975  */
976 char *
977 remove_extension(const char *path)
978 {
979         return x_strndup(path, strlen(path) - strlen(get_extension(path)));
980 }
981
982 /* return size on disk of a file */
983 size_t
984 file_size(struct stat *st)
985 {
986 #ifdef _WIN32
987         return (st->st_size + 1023) & ~1023;
988 #else
989         size_t size = st->st_blocks * 512;
990         if ((size_t)st->st_size > size) {
991                 /* probably a broken stat() call ... */
992                 size = (st->st_size + 1023) & ~1023;
993         }
994         return size;
995 #endif
996 }
997
998 /* Format a size as a human-readable string. Caller frees. */
999 char *
1000 format_human_readable_size(uint64_t v)
1001 {
1002         char *s;
1003         if (v >= 1000*1000*1000) {
1004                 s = format("%.1f GB", v/((double)(1000*1000*1000)));
1005         } else if (v >= 1000*1000) {
1006                 s = format("%.1f MB", v/((double)(1000*1000)));
1007         } else {
1008                 s = format("%.1f kB", v/((double)(1000)));
1009         }
1010         return s;
1011 }
1012
1013 /* Format a size as a parsable string. Caller frees. */
1014 char *
1015 format_parsable_size_with_suffix(uint64_t size)
1016 {
1017         char *s;
1018         if (size >= 1000*1000*1000) {
1019                 s = format("%.1fG", size / ((double)(1000*1000*1000)));
1020         } else if (size >= 1000*1000) {
1021                 s = format("%.1fM", size / ((double)(1000*1000)));
1022         } else if (size >= 1000) {
1023                 s = format("%.1fk", size / ((double)(1000)));
1024         } else {
1025                 s = format("%u", (unsigned)size);
1026         }
1027         return s;
1028 }
1029
1030 /*
1031  * Parse a "size value", i.e. a string that can end in k, M, G, T (10-based
1032  * suffixes) or Ki, Mi, Gi, Ti (2-based suffixes). For backward compatibility,
1033  * K is also recognized as a synonym of k.
1034  */
1035 bool
1036 parse_size_with_suffix(const char *str, uint64_t *size)
1037 {
1038         char *p;
1039         double x;
1040
1041         errno = 0;
1042         x = strtod(str, &p);
1043         if (errno != 0 || x < 0 || p == str || *str == '\0') {
1044                 return false;
1045         }
1046
1047         while (isspace(*p)) {
1048                 ++p;
1049         }
1050
1051         if (*p != '\0') {
1052                 unsigned multiplier;
1053                 if (*(p+1) == 'i') {
1054                         multiplier = 1024;
1055                 } else {
1056                         multiplier = 1000;
1057                 }
1058                 switch (*p) {
1059                 case 'T':
1060                         x *= multiplier;
1061                 case 'G':
1062                         x *= multiplier;
1063                 case 'M':
1064                         x *= multiplier;
1065                 case 'K':
1066                 case 'k':
1067                         x *= multiplier;
1068                         break;
1069                 default:
1070                         return false;
1071                 }
1072         } else {
1073                 /* Default suffix: G. */
1074                 x *= 1000 * 1000 * 1000;
1075         }
1076         *size = x;
1077         return true;
1078 }
1079
1080
1081 /* A sane realpath() function, trying to cope with stupid path limits and a
1082  * broken API. */
1083 char *
1084 x_realpath(const char *path)
1085 {
1086         long maxlen = path_max(path);
1087         char *ret, *p;
1088 #if !defined(HAVE_REALPATH) && defined(_WIN32)
1089         HANDLE path_handle;
1090 #endif
1091
1092         ret = x_malloc(maxlen);
1093
1094 #if HAVE_REALPATH
1095         p = realpath(path, ret);
1096 #elif defined(_WIN32)
1097         path_handle = CreateFile(
1098           path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1099           FILE_ATTRIBUTE_NORMAL, NULL);
1100         if (INVALID_HANDLE_VALUE != path_handle) {
1101                 GetFinalPathNameByHandle(path_handle, ret, maxlen, FILE_NAME_NORMALIZED);
1102                 CloseHandle(path_handle);
1103                 p = ret + 4; /* strip \\?\ from the file name */
1104         } else {
1105                 snprintf(ret, maxlen, "%s", path);
1106                 p = ret;
1107         }
1108 #else
1109         /* yes, there are such systems. This replacement relies on
1110            the fact that when we call x_realpath we only care about symlinks */
1111         {
1112                 int len = readlink(path, ret, maxlen-1);
1113                 if (len == -1) {
1114                         free(ret);
1115                         return NULL;
1116                 }
1117                 ret[len] = 0;
1118                 p = ret;
1119         }
1120 #endif
1121         if (p) {
1122                 p = x_strdup(p);
1123                 free(ret);
1124                 return p;
1125         }
1126         free(ret);
1127         return NULL;
1128 }
1129
1130 /* a getcwd that will returns an allocated buffer */
1131 char *
1132 gnu_getcwd(void)
1133 {
1134         unsigned size = 128;
1135
1136         while (true) {
1137                 char *buffer = (char *)x_malloc(size);
1138                 if (getcwd(buffer, size) == buffer) {
1139                         return buffer;
1140                 }
1141                 free(buffer);
1142                 if (errno != ERANGE) {
1143                         cc_log("getcwd error: %d (%s)", errno, strerror(errno));
1144                         return NULL;
1145                 }
1146                 size *= 2;
1147         }
1148 }
1149
1150 #ifndef HAVE_STRTOK_R
1151 /* strtok_r replacement */
1152 char *
1153 strtok_r(char *str, const char *delim, char **saveptr)
1154 {
1155         int len;
1156         char *ret;
1157         if (!str)
1158                 str = *saveptr;
1159         len = strlen(str);
1160         ret = strtok(str, delim);
1161         if (ret) {
1162                 char *save = ret;
1163                 while (*save++) ;
1164                 if ((len + 1) == (intptr_t) (save - str))
1165                         save--;
1166                 *saveptr = save;
1167         }
1168         return ret;
1169 }
1170 #endif
1171
1172 /*
1173  * Create an empty temporary file. *fname will be reallocated and set to the
1174  * resulting filename. Returns an open file descriptor to the file.
1175  */
1176 int
1177 create_tmp_fd(char **fname)
1178 {
1179         char *template = format("%s.%s", *fname, tmp_string());
1180         int fd = mkstemp(template);
1181         if (fd == -1 && errno == ENOENT) {
1182                 if (create_parent_dirs(*fname) != 0) {
1183                         fatal("Failed to create directory %s: %s",
1184                               dirname(*fname), strerror(errno));
1185                 }
1186                 reformat(&template, "%s.%s", *fname, tmp_string());
1187                 fd = mkstemp(template);
1188         }
1189         if (fd == -1) {
1190                 fatal("Failed to create temporary file for %s: %s",
1191                       *fname, strerror(errno));
1192         }
1193
1194 #ifndef _WIN32
1195         fchmod(fd, 0666 & ~get_umask());
1196 #endif
1197
1198         free(*fname);
1199         *fname = template;
1200         return fd;
1201 }
1202
1203 /*
1204  * Create an empty temporary file. *fname will be reallocated and set to the
1205  * resulting filename. Returns an open FILE*.
1206  */
1207 FILE *
1208 create_tmp_file(char **fname, const char *mode)
1209 {
1210         FILE *file = fdopen(create_tmp_fd(fname), mode);
1211         if (!file) {
1212                 fatal("Failed to create file %s: %s", *fname, strerror(errno));
1213         }
1214         return file;
1215 }
1216
1217 /*
1218  * Return current user's home directory, or NULL if it can't be determined.
1219  */
1220 const char *
1221 get_home_directory(void)
1222 {
1223         const char *p = getenv("HOME");
1224         if (p) {
1225                 return p;
1226         }
1227 #ifdef _WIN32
1228         p = getenv("APPDATA");
1229         if (p) {
1230                 return p;
1231         }
1232 #endif
1233 #ifdef HAVE_GETPWUID
1234         {
1235                 struct passwd *pwd = getpwuid(getuid());
1236                 if (pwd) {
1237                         return pwd->pw_dir;
1238                 }
1239         }
1240 #endif
1241         return NULL;
1242 }
1243
1244 /*
1245  * Get the current directory by reading $PWD. If $PWD isn't sane, gnu_getcwd()
1246  * is used. Caller frees.
1247  */
1248 char *
1249 get_cwd(void)
1250 {
1251         char *pwd;
1252         char *cwd;
1253         struct stat st_pwd;
1254         struct stat st_cwd;
1255
1256         cwd = gnu_getcwd();
1257         if (!cwd) {
1258                 return NULL;
1259         }
1260         pwd = getenv("PWD");
1261         if (!pwd) {
1262                 return cwd;
1263         }
1264         if (stat(pwd, &st_pwd) != 0) {
1265                 return cwd;
1266         }
1267         if (stat(cwd, &st_cwd) != 0) {
1268                 return cwd;
1269         }
1270         if (st_pwd.st_dev == st_cwd.st_dev && st_pwd.st_ino == st_cwd.st_ino) {
1271                 free(cwd);
1272                 return x_strdup(pwd);
1273         } else {
1274                 return cwd;
1275         }
1276 }
1277
1278 /*
1279  * Check whether s1 and s2 have the same executable name.
1280  */
1281 bool
1282 same_executable_name(const char *s1, const char *s2)
1283 {
1284 #ifdef _WIN32
1285         bool eq = strcasecmp(s1, s2) == 0;
1286         if (!eq) {
1287                 char *tmp = format("%s.exe", s2);
1288                 eq = strcasecmp(s1, tmp) == 0;
1289                 free(tmp);
1290         }
1291         return eq;
1292 #else
1293         return str_eq(s1, s2);
1294 #endif
1295 }
1296
1297 /*
1298  * Compute the length of the longest directory path that is common to two
1299  * paths. s1 is assumed to be the path to a directory.
1300  */
1301 size_t
1302 common_dir_prefix_length(const char *s1, const char *s2)
1303 {
1304         const char *p1 = s1;
1305         const char *p2 = s2;
1306
1307         while (*p1 && *p2 && *p1 == *p2) {
1308                 ++p1;
1309                 ++p2;
1310         }
1311         while ((*p1 && *p1 != '/') || (*p2 && *p2 != '/')) {
1312                 p1--;
1313                 p2--;
1314         }
1315         if (!*p1 && !*p2 && p2 == s2 + 1) {
1316                 /* Special case for s1 and s2 both being "/". */
1317                 return 0;
1318         }
1319         return p1 - s1;
1320 }
1321
1322 /*
1323  * Compute a relative path from from (an absolute path to a directory) to to (a
1324  * path). Assumes that both from and to are well-formed and canonical. Caller
1325  * frees.
1326  */
1327 char *
1328 get_relative_path(const char *from, const char *to)
1329 {
1330         size_t common_prefix_len;
1331         int i;
1332         char *result;
1333
1334         assert(from && is_absolute_path(from));
1335         assert(to);
1336
1337         if (!*to || !is_absolute_path(to)) {
1338                 return x_strdup(to);
1339         }
1340
1341 #ifdef _WIN32
1342         // Both paths are absolute, drop the drive letters
1343         assert(from[0] == to[0]); // Assume the same drive letter
1344         from += 2;
1345         to += 2;
1346 #endif
1347
1348         result = x_strdup("");
1349         common_prefix_len = common_dir_prefix_length(from, to);
1350         if (common_prefix_len > 0 || !str_eq(from, "/")) {
1351                 const char *p;
1352                 for (p = from + common_prefix_len; *p; p++) {
1353                         if (*p == '/') {
1354                                 reformat(&result, "../%s", result);
1355                         }
1356                 }
1357         }
1358         if (strlen(to) > common_prefix_len) {
1359                 reformat(&result, "%s%s", result, to + common_prefix_len + 1);
1360         }
1361         i = strlen(result) - 1;
1362         while (i >= 0 && result[i] == '/') {
1363                 result[i] = '\0';
1364                 i--;
1365         }
1366         if (str_eq(result, "")) {
1367                 free(result);
1368                 result = x_strdup(".");
1369         }
1370         return result;
1371 }
1372
1373 /*
1374  * Return whether path is absolute.
1375  */
1376 bool
1377 is_absolute_path(const char *path)
1378 {
1379 #ifdef _WIN32
1380         return path[0] && path[1] == ':';
1381 #else
1382         return path[0] == '/';
1383 #endif
1384 }
1385
1386 /*
1387  * Return whether the argument is a full path.
1388  */
1389 bool
1390 is_full_path(const char *path)
1391 {
1392         if (strchr(path, '/'))
1393                 return true;
1394 #ifdef _WIN32
1395         if (strchr(path, '\\'))
1396                 return true;
1397 #endif
1398         return false;
1399 }
1400
1401 /*
1402  * Update the modification time of a file in the cache to save it from LRU
1403  * cleanup.
1404  */
1405 void
1406 update_mtime(const char *path)
1407 {
1408 #ifdef HAVE_UTIMES
1409         utimes(path, NULL);
1410 #else
1411         utime(path, NULL);
1412 #endif
1413 }
1414
1415 /*
1416  * If exit() already has been called, call _exit(), otherwise exit(). This is
1417  * used to avoid calling exit() inside an atexit handler.
1418  */
1419 void
1420 x_exit(int status)
1421 {
1422         static bool first_time = true;
1423         if (first_time) {
1424                 first_time = false;
1425                 exit(status);
1426         } else {
1427                 _exit(status);
1428         }
1429 }
1430
1431 /*
1432  * Rename oldpath to newpath (deleting newpath).
1433  */
1434 int
1435 x_rename(const char *oldpath, const char *newpath)
1436 {
1437 #ifndef _WIN32
1438         return rename(oldpath, newpath);
1439 #else
1440         /* Windows' rename() refuses to overwrite an existing file. */
1441         unlink(newpath);  /* not x_unlink, as x_unlink calls x_rename */
1442         /* If the function succeeds, the return value is nonzero. */
1443         if (MoveFileA(oldpath, newpath) == 0) {
1444                 LPVOID lpMsgBuf;
1445                 LPVOID lpDisplayBuf;
1446                 DWORD dw = GetLastError();
1447
1448                 FormatMessage(
1449                   FORMAT_MESSAGE_ALLOCATE_BUFFER |
1450                   FORMAT_MESSAGE_FROM_SYSTEM |
1451                   FORMAT_MESSAGE_IGNORE_INSERTS,
1452                   NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf,
1453                   0, NULL);
1454
1455                 lpDisplayBuf = (LPVOID) LocalAlloc(
1456                   LMEM_ZEROINIT,
1457                   (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) __FILE__) + 40)
1458                   * sizeof(TCHAR));
1459                 _snprintf((LPTSTR) lpDisplayBuf,
1460                           LocalSize(lpDisplayBuf) / sizeof(TCHAR),
1461                           TEXT("%s failed with error %d: %s"), __FILE__, dw, lpMsgBuf);
1462
1463                 cc_log("can't rename file %s to %s OS returned error: %s",
1464                        oldpath, newpath, (char *) lpDisplayBuf);
1465
1466                 LocalFree(lpMsgBuf);
1467                 LocalFree(lpDisplayBuf);
1468                 return -1;
1469         } else {
1470                 return 0;
1471         }
1472 #endif
1473 }
1474
1475 /*
1476  * Remove path, NFS hazardous. Use only for temporary files that will not exist
1477  * on other systems. That is, the path should include tmp_string().
1478  */
1479 int
1480 tmp_unlink(const char *path)
1481 {
1482         int rc;
1483         cc_log("Unlink %s", path);
1484         rc = unlink(path);
1485         if (rc) {
1486                 cc_log("Unlink failed: %s", strerror(errno));
1487         }
1488         return rc;
1489 }
1490
1491 /*
1492  * Remove path, NFS safe.
1493  */
1494 int
1495 x_unlink(const char *path)
1496 {
1497         /*
1498          * If path is on an NFS share, unlink isn't atomic, so we rename to a temp
1499          * file. We don't care if the temp file is trashed, so it's always safe to
1500          * unlink it first.
1501          */
1502         char *tmp_name = format("%s.rm.%s", path, tmp_string());
1503         int result = 0;
1504         int saved_errno = 0;
1505         cc_log("Unlink %s via %s", path, tmp_name);
1506         if (x_rename(path, tmp_name) == -1) {
1507                 result = -1;
1508                 saved_errno = errno;
1509                 goto out;
1510         }
1511         if (unlink(tmp_name) == -1) {
1512                 /* If it was released in a race, that's OK. */
1513                 if (errno != ENOENT && errno != ESTALE) {
1514                         result = -1;
1515                         saved_errno = errno;
1516                 }
1517         }
1518 out:
1519         free(tmp_name);
1520         if (result) {
1521                 cc_log("x_unlink failed: %s", strerror(saved_errno));
1522         }
1523         errno = saved_errno;
1524         return result;
1525 }
1526
1527 #ifndef _WIN32
1528 /* Like readlink() but returns the string or NULL on failure. Caller frees. */
1529 char *
1530 x_readlink(const char *path)
1531 {
1532         long maxlen = path_max(path);
1533         ssize_t len;
1534         char *buf;
1535
1536         buf = x_malloc(maxlen);
1537         len = readlink(path, buf, maxlen-1);
1538         if (len == -1) {
1539                 free(buf);
1540                 return NULL;
1541         }
1542         buf[len] = 0;
1543         return buf;
1544 }
1545 #endif
1546
1547 /*
1548  * Reads the content of a file. Size hint 0 means no hint. Returns true on
1549  * success, otherwise false.
1550  */
1551 bool
1552 read_file(const char *path, size_t size_hint, char **data, size_t *size)
1553 {
1554         int fd, ret;
1555         size_t pos = 0, allocated;
1556
1557         if (size_hint == 0) {
1558                 struct stat st;
1559                 if (x_stat(path, &st) == 0) {
1560                         size_hint = st.st_size;
1561                 }
1562         }
1563         size_hint = (size_hint < 1024) ? 1024 : size_hint;
1564
1565         fd = open(path, O_RDONLY | O_BINARY);
1566         if (fd == -1) {
1567                 return false;
1568         }
1569         allocated = size_hint;
1570         *data = x_malloc(allocated);
1571         while (true) {
1572                 if (pos > allocated / 2) {
1573                         allocated *= 2;
1574                         *data = x_realloc(*data, allocated);
1575                 }
1576                 ret = read(fd, *data + pos, allocated - pos);
1577                 if (ret == 0 || (ret == -1 && errno != EINTR)) {
1578                         break;
1579                 }
1580                 if (ret > 0) {
1581                         pos += ret;
1582                 }
1583         }
1584         close(fd);
1585         if (ret == -1) {
1586                 cc_log("Failed reading %s", path);
1587                 free(*data);
1588                 *data = NULL;
1589                 return false;
1590         }
1591
1592         *size = pos;
1593         return true;
1594 }
1595
1596 /*
1597  * Return the content (with NUL termination) of a text file, or NULL on error.
1598  * Caller frees. Size hint 0 means no hint.
1599  */
1600 char *
1601 read_text_file(const char *path, size_t size_hint)
1602 {
1603         size_t size;
1604         char *data;
1605
1606         if (read_file(path, size_hint, &data, &size)) {
1607                 data = x_realloc(data, size + 1);
1608                 data[size] = '\0';
1609                 return data;
1610         } else {
1611                 return NULL;
1612         }
1613 }
1614
1615 static bool
1616 expand_variable(const char **str, char **result, char **errmsg)
1617 {
1618         bool curly;
1619         const char *p, *q;
1620         char *name;
1621         const char *value;
1622
1623         assert(**str == '$');
1624         p = *str + 1;
1625         if (*p == '{') {
1626                 curly = true;
1627                 ++p;
1628         } else {
1629                 curly = false;
1630         }
1631         q = p;
1632         while (isalnum(*q) || *q == '_') {
1633                 ++q;
1634         }
1635         if (curly) {
1636                 if (*q != '}') {
1637                         *errmsg = format("syntax error: missing '}' after \"%s\"", p);
1638                         return false;
1639                 }
1640         }
1641
1642         if (q == p) {
1643                 /* Special case: don't consider a single $ the start of a variable. */
1644                 reformat(result, "%s$", *result);
1645                 return true;
1646         }
1647
1648         name = x_strndup(p, q - p);
1649         value = getenv(name);
1650         if (!value) {
1651                 *errmsg = format("environment variable \"%s\" not set", name);
1652                 free(name);
1653                 return false;
1654         }
1655         reformat(result, "%s%s", *result, value);
1656         if (!curly) {
1657                 --q;
1658         }
1659         *str = q;
1660         free(name);
1661         return true;
1662 }
1663
1664 /*
1665  * Substitute all instances of $VAR or ${VAR}, where VAR is an environment
1666  * variable, in a string. Caller frees. If one of the environment variables
1667  * doesn't exist, NULL will be returned and *errmsg will be an appropriate
1668  * error message (caller frees).
1669  */
1670 char *
1671 subst_env_in_string(const char *str, char **errmsg)
1672 {
1673         const char *p; /* Interval start. */
1674         const char *q; /* Interval end. */
1675         char *result;
1676
1677         assert(errmsg);
1678         *errmsg = NULL;
1679
1680         result = x_strdup("");
1681         p = str;
1682         q = str;
1683         for (q = str; *q; ++q) {
1684                 if (*q == '$') {
1685                         reformat(&result, "%s%.*s", result, (int)(q - p), p);
1686                         if (!expand_variable(&q, &result, errmsg)) {
1687                                 free(result);
1688                                 return NULL;
1689                         }
1690                         p = q + 1;
1691                 }
1692         }
1693         reformat(&result, "%s%.*s", result, (int)(q - p), p);
1694         return result;
1695 }