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