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