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