1 // Copyright (C) 2002 Andrew Tridgell
2 // Copyright (C) 2009-2019 Joel Rosdahl
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)
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
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
25 #ifdef HAVE_SYS_TIME_H
31 #include <sys/locking.h>
36 // Destination for conf->log_file.
39 // Buffer used for logs in conf->debug mode.
40 static char *debug_log_buffer;
42 // Allocated debug_log_buffer size.
43 static size_t debug_log_buffer_capacity;
45 // The amount of log data stored in debug_log_buffer.
46 static size_t debug_log_size;
48 #define DEBUG_LOG_BUFFER_MARGIN 1024
53 extern struct conf *conf;
55 if (debug_log_buffer || logfile) {
60 debug_log_buffer_capacity = DEBUG_LOG_BUFFER_MARGIN;
61 debug_log_buffer = x_malloc(debug_log_buffer_capacity);
64 if (str_eq(conf->log_file, "")) {
67 logfile = fopen(conf->log_file, "a");
70 set_cloexec_flag(fileno(logfile));
79 append_to_debug_log(const char *s, size_t len)
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);
86 memcpy(debug_log_buffer + debug_log_size, s, len);
87 debug_log_size += len;
91 log_prefix(bool log_updated_time)
93 static char prefix[200];
94 #ifdef HAVE_GETTIMEOFDAY
95 if (log_updated_time) {
99 gettimeofday(&tv, NULL);
100 #ifdef __MINGW64_VERSION_MAJOR
101 localtime_r((time_t *)&tv.tv_sec, &tm);
103 localtime_r(&tv.tv_sec, &tm);
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());
110 snprintf(prefix, sizeof(prefix), "[%-5d] ", (int)getpid());
113 fputs(prefix, logfile);
115 if (debug_log_buffer) {
116 append_to_debug_log(prefix, strlen(prefix));
121 path_max(const char *path)
126 #elif defined(MAXPATHLEN)
129 #elif defined(_PC_PATH_MAX)
130 long maxlen = pathconf(path, _PC_PATH_MAX);
131 return maxlen >= 4096 ? maxlen : 4096;
135 static void warn_log_fail(void) ATTR_NORETURN;
137 // Warn about failure writing to the log file and then exit.
141 extern struct conf *conf;
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);
150 vlog(const char *format, va_list ap, bool log_updated_time)
158 log_prefix(log_updated_time);
160 int rc1 = vfprintf(logfile, format, ap);
161 int rc2 = fprintf(logfile, "\n");
162 if (rc1 < 0 || rc2 < 0) {
166 if (debug_log_buffer) {
168 int len = vsnprintf(buf, sizeof(buf), format, aq);
170 append_to_debug_log(buf, MIN((size_t)len, sizeof(buf) - 1));
171 append_to_debug_log("\n", 1);
177 // Write a message to the log file (adding a newline) and flush.
179 cc_log(const char *format, ...)
182 va_start(ap, format);
183 vlog(format, ap, true);
190 // Write a message to the log file (adding a newline) without flushing and with
191 // a reused timestamp.
193 cc_bulklog(const char *format, ...)
196 va_start(ap, format);
197 vlog(format, ap, false);
201 // Log an executed command to the CCACHE_LOGFILE location.
203 cc_log_argv(const char *prefix, char **argv)
211 fputs(prefix, logfile);
212 print_command(logfile, argv);
213 int rc = fflush(logfile);
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));
226 // Copy the current log memory buffer to an output file.
228 cc_dump_debug_log_buffer(const char *path)
230 FILE *file = fopen(path, "w");
232 (void) fwrite(debug_log_buffer, 1, debug_log_size, file);
235 cc_log("Failed to open %s: %s", path, strerror(errno));
239 // Something went badly wrong!
241 fatal(const char *format, ...)
244 va_start(ap, format);
246 vsnprintf(msg, sizeof(msg), format, ap);
249 cc_log("FATAL: %s", msg);
250 fprintf(stderr, "ccache: error: %s\n", msg);
255 // Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
257 copy_fd(int fd_in, int fd_out)
259 gzFile gz_in = gzdopen(dup(fd_in), "rb");
261 fatal("Failed to copy fd");
265 char buf[READ_BUFFER_SIZE];
266 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
269 ssize_t count = write(fd_out, buf + written, n - written);
271 if (errno != EAGAIN && errno != EINTR) {
272 fatal("Failed to copy fd");
277 } while (written < n);
284 // Cheap and nasty mkstemp replacement.
286 mkstemp(char *template)
289 #pragma GCC diagnostic push
290 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
294 #pragma GCC diagnostic pop
296 return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
304 static bool mask_retrieved = false;
306 if (!mask_retrieved) {
309 mask_retrieved = true;
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.
319 copy_file(const char *src, const char *dest, int compress_level)
323 gzFile gz_out = NULL;
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");
333 int fd_in = open(src, O_RDONLY | O_BINARY);
336 cc_log("open error: %s", strerror(saved_errno));
340 gz_in = gzdopen(fd_in, "rb");
343 cc_log("gzdopen(src) error: %s", strerror(saved_errno));
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.
353 if (x_fstat(fd_in, &st) != 0) {
356 if (file_size(&st) == 0) {
361 if (compress_level > 0) {
362 gz_out = gzdopen(dup(fd_out), "wb");
365 cc_log("gzdopen(dest) error: %s", strerror(saved_errno));
368 gzsetparams(gz_out, compress_level, Z_DEFAULT_STRATEGY);
372 char buf[READ_BUFFER_SIZE];
373 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
375 if (compress_level > 0) {
376 written = gzwrite(gz_out, buf, n);
380 ssize_t count = write(fd_out, buf + written, n - written);
381 if (count == -1 && errno != EINTR) {
386 } while (written < n);
389 if (compress_level > 0) {
391 cc_log("gzwrite error: %s (errno: %s)",
392 gzerror(gz_in, &errnum),
393 strerror(saved_errno));
395 cc_log("write error: %s", strerror(saved_errno));
401 // gzeof won't tell if there's an error in the trailing CRC, so we must check
402 // gzerror before considering everything OK.
404 gzerror(gz_in, &errnum);
405 if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
407 cc_log("gzread error: %s (errno: %s)",
408 gzerror(gz_in, &errnum), strerror(saved_errno));
414 tmp_unlink(tmp_name);
427 fchmod(fd_out, 0666 & ~get_umask());
430 // The close can fail on NFS if out of space.
431 if (close(fd_out) == -1) {
433 cc_log("close error: %s", strerror(saved_errno));
437 if (x_rename(tmp_name, dest) == -1) {
439 cc_log("rename error: %s", strerror(saved_errno));
457 tmp_unlink(tmp_name);
463 // Run copy_file() and, if successful, delete the source file.
465 move_file(const char *src, const char *dest, int compress_level)
467 int ret = copy_file(src, dest, compress_level);
474 // Like move_file(), but assumes that src is uncompressed and that src and dest
475 // are on the same file system.
477 move_uncompressed_file(const char *src, const char *dest, int compress_level)
479 if (compress_level > 0) {
480 return move_file(src, dest, compress_level);
482 return x_rename(src, dest);
486 // Test if a file is zlib compressed.
488 file_is_compressed(const char *filename)
490 FILE *f = fopen(filename, "rb");
495 // Test if file starts with 1F8B, which is zlib's magic number.
496 if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
505 // Make sure a directory exists.
507 create_dir(const char *dir)
510 if (stat(dir, &st) == 0) {
511 if (S_ISDIR(st.st_mode)) {
517 if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
523 // Create directories leading to path. Returns 0 on success, otherwise -1.
525 create_parent_dirs(const char *path)
528 char *parent = dirname(path);
530 if (stat(parent, &st) == 0) {
531 if (S_ISDIR(st.st_mode)) {
538 res = create_parent_dirs(parent);
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
549 if (res != 0 && errno == EEXIST) {
560 // Return a static string with the current hostname.
564 static char hostname[260] = "";
570 strcpy(hostname, "unknown");
572 gethostname(hostname, sizeof(hostname) - 1);
573 #elif defined(_WIN32)
574 const char *computer_name = getenv("COMPUTERNAME");
576 snprintf(hostname, sizeof(hostname), "%s", computer_name);
580 WORD w_version_requested = MAKEWORD(2, 2);
582 int err = WSAStartup(w_version_requested, &wsa_data);
584 // Tell the user that we could not find a usable Winsock DLL.
585 cc_log("WSAStartup failed with error: %d", err);
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");
596 int result = gethostname(hostname, sizeof(hostname) - 1);
599 DWORD dw = WSAGetLastError();
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);
608 LPVOID lp_display_buf = (LPVOID) LocalAlloc(
610 (lstrlen((LPCTSTR) lp_msg_buf) + lstrlen((LPCTSTR) __FILE__) + 200)
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);
617 cc_log("can't get hostname OS returned error: %s", (char *)lp_display_buf);
619 LocalFree(lp_msg_buf);
620 LocalFree(lp_display_buf);
625 hostname[sizeof(hostname) - 1] = 0;
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.
636 ret = format("%s.%u.XXXXXX", get_hostname(), (unsigned)getpid());
641 // Return the hash result as a hex string. Size -1 means don't include size
642 // suffix. Caller frees.
644 format_hash_as_string(const unsigned char *hash, int size)
647 char *ret = x_malloc(53);
648 for (i = 0; i < 16; i++) {
649 sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
652 sprintf(&ret[i*2], "-%d", size);
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";
664 create_cachedirtag(const char *dir)
666 char *filename = format("%s/CACHEDIR.TAG", dir);
668 if (stat(filename, &st) == 0) {
669 if (S_ISREG(st.st_mode)) {
675 FILE *f = fopen(filename, "w");
679 if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
694 // Construct a string according to a format. Caller frees.
696 format(const char *format, ...)
699 va_start(ap, format);
702 if (vasprintf(&ptr, format, ap) == -1) {
703 fatal("Out of memory in format");
708 fatal("Internal error in format");
713 // This is like strdup() but dies if the malloc fails.
715 x_strdup(const char *s)
717 char *ret = strdup(s);
719 fatal("Out of memory in x_strdup");
724 // This is like strndup() but dies if the malloc fails.
726 x_strndup(const char *s, size_t n)
733 while (m < n && s[m]) {
736 char *ret = malloc(m + 1);
742 char *ret = strndup(s, n);
745 fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
750 // This is like malloc() but dies if the malloc fails.
752 x_malloc(size_t size)
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.
759 void *ret = malloc(size);
761 fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
766 // This is like calloc() but dies if the allocation fails.
768 x_calloc(size_t nmemb, size_t size)
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.
775 void *ret = calloc(nmemb, size);
777 fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
782 // This is like realloc() but dies if the malloc fails.
784 x_realloc(void *ptr, size_t size)
787 return x_malloc(size);
789 void *p2 = realloc(ptr, size);
791 fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
796 // This is like setenv.
797 void x_setenv(const char *name, const char *value)
800 setenv(name, value, true);
802 putenv(format("%s=%s", name, value)); // Leak to environment.
806 // This is like unsetenv.
807 void x_unsetenv(const char *name)
812 putenv(x_strdup(name)); // Leak to environment.
816 // Like fstat() but also call cc_log on failure.
818 x_fstat(int fd, struct stat *buf)
820 int result = fstat(fd, buf);
822 cc_log("Failed to fstat fd %d: %s", fd, strerror(errno));
827 // Like lstat() but also call cc_log on failure.
829 x_lstat(const char *pathname, struct stat *buf)
831 int result = lstat(pathname, buf);
833 cc_log("Failed to lstat %s: %s", pathname, strerror(errno));
838 // Like stat() but also call cc_log on failure.
840 x_stat(const char *pathname, struct stat *buf)
842 int result = stat(pathname, buf);
844 cc_log("Failed to stat %s: %s", pathname, strerror(errno));
849 // Construct a string according to the format and store it in *ptr. The
850 // original *ptr is then freed.
852 reformat(char **ptr, const char *format, ...)
858 va_start(ap, format);
859 if (vasprintf(ptr, format, ap) == -1) {
860 fatal("Out of memory in reformat");
869 // Recursive directory traversal. fn() is called on all entries in the tree.
871 traverse(const char *dir, void (*fn)(const char *, struct stat *))
873 DIR *d = opendir(dir);
879 while ((de = readdir(d))) {
880 if (str_eq(de->d_name, ".")) {
883 if (str_eq(de->d_name, "..")) {
887 if (strlen(de->d_name) == 0) {
891 char *fname = format("%s/%s", dir, de->d_name);
893 if (lstat(fname, &st)) {
894 if (errno != ENOENT && errno != ESTALE) {
895 fatal("lstat %s failed: %s", fname, strerror(errno));
901 if (S_ISDIR(st.st_mode)) {
913 // Return the base name of a file - caller frees.
915 basename(const char *path)
917 char *p = strrchr(path, '/');
922 p = strrchr(path, '\\');
928 return x_strdup(path);
931 // Return the dir name of a file - caller frees.
933 dirname(const char *path)
935 char *s = x_strdup(path);
936 char *p = strrchr(s, '/');
938 char *p2 = strrchr(s, '\\');
939 if (!p || (p2 && p < p2)) {
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
958 get_extension(const char *path)
960 size_t len = strlen(path);
961 for (const char *p = &path[len - 1]; p >= path; --p) {
972 // Return a string containing the given path without the filename extension.
975 remove_extension(const char *path)
977 return x_strndup(path, strlen(path) - strlen(get_extension(path)));
980 // Return size on disk of a file.
982 file_size(struct stat *st)
985 return (st->st_size + 1023) & ~1023;
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;
996 // Format a size as a human-readable string. Caller frees.
998 format_human_readable_size(uint64_t v)
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)));
1006 s = format("%.1f kB", v/((double)(1000)));
1011 // Format a size as a parsable string. Caller frees.
1013 format_parsable_size_with_suffix(uint64_t size)
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)));
1023 s = format("%u", (unsigned)size);
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.
1032 parse_size_with_suffix(const char *str, uint64_t *size)
1037 double x = strtod(str, &p);
1038 if (errno != 0 || x < 0 || p == str || *str == '\0') {
1042 while (isspace(*p)) {
1047 unsigned multiplier = *(p+1) == 'i' ? 1024 : 1000;
1066 // Default suffix: G.
1067 x *= 1000 * 1000 * 1000;
1069 *size = (uint64_t)x;
1074 #if !defined(HAVE_REALPATH) && \
1075 defined(_WIN32) && \
1076 !defined(HAVE_GETFINALPATHNAMEBYHANDLEW)
1077 static BOOL GetFileNameFromHandle(HANDLE file_handle, TCHAR *filename,
1080 BOOL success = FALSE;
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.
1090 // Create a file mapping object.
1092 CreateFileMapping(file_handle, NULL, PAGE_READONLY, 0, 1, NULL);
1097 // Create a file mapping to get the file name.
1098 void *mem = MapViewOfFile(file_map, FILE_MAP_READ, 0, 0, 1);
1100 if (GetMappedFileName(GetCurrentProcess(),
1104 // Translate path with device name to drive letters.
1108 if (GetLogicalDriveStrings(512-1, temp)) {
1109 TCHAR name[MAX_PATH];
1110 TCHAR drive[3] = TEXT(" :");
1115 // Copy the drive letter to the template string.
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('\\');
1125 // Reconstruct filename using temp_file and replace device path
1127 TCHAR temp_file[MAX_PATH];
1128 _sntprintf(temp_file,
1133 _tcsncpy(filename, temp_file, _tcslen(temp_file));
1138 // Go to the next NULL character.
1142 } while (!found && *p); // End of string.
1146 UnmapViewOfFile(mem);
1149 CloseHandle(file_map);
1154 // A sane realpath() function, trying to cope with stupid path limits and a
1155 // broken API. Caller frees.
1157 x_realpath(const char *path)
1159 long maxlen = path_max(path);
1160 char *ret = x_malloc(maxlen);
1164 p = realpath(path, ret);
1165 #elif defined(_WIN32)
1166 if (path[0] == '/') {
1167 path++; // Skip leading slash.
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);
1176 GetFileNameFromHandle(path_handle, ret, maxlen);
1178 CloseHandle(path_handle);
1179 p = ret + 4; // Strip \\?\ from the file name.
1181 snprintf(ret, maxlen, "%s", path);
1185 // Yes, there are such systems. This replacement relies on the fact that when
1186 // we call x_realpath we only care about symlinks.
1188 int len = readlink(path, ret, maxlen-1);
1206 // A getcwd that will returns an allocated buffer.
1210 unsigned size = 128;
1213 char *buffer = (char *)x_malloc(size);
1214 if (getcwd(buffer, size) == buffer) {
1218 if (errno != ERANGE) {
1219 cc_log("getcwd error: %d (%s)", errno, strerror(errno));
1226 #ifndef HAVE_LOCALTIME_R
1227 // localtime_r replacement.
1229 localtime_r(const time_t *timep, struct tm *result)
1231 struct tm *tm = localtime(timep);
1237 #ifndef HAVE_STRTOK_R
1238 // strtok_r replacement.
1240 strtok_r(char *str, const char *delim, char **saveptr)
1245 int len = strlen(str);
1246 char *ret = strtok(str, delim);
1252 if ((len + 1) == (intptr_t) (save - str)) {
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.
1264 create_tmp_fd(char **fname)
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));
1273 reformat(&template, "%s.%s", *fname, tmp_string());
1274 fd = mkstemp(template);
1277 fatal("Failed to create temporary file for %s: %s",
1278 *fname, strerror(errno));
1280 set_cloexec_flag(fd);
1283 fchmod(fd, 0666 & ~get_umask());
1291 // Create an empty temporary file. *fname will be reallocated and set to the
1292 // resulting filename. Returns an open FILE*.
1294 create_tmp_file(char **fname, const char *mode)
1296 FILE *file = fdopen(create_tmp_fd(fname), mode);
1298 fatal("Failed to create file %s: %s", *fname, strerror(errno));
1303 // Return current user's home directory, or NULL if it can't be determined.
1305 get_home_directory(void)
1307 const char *p = getenv("HOME");
1312 p = getenv("APPDATA");
1317 #ifdef HAVE_GETPWUID
1319 struct passwd *pwd = getpwuid(getuid());
1328 // Get the current directory by reading $PWD. If $PWD isn't sane, gnu_getcwd()
1329 // is used. Caller frees.
1336 char *cwd = gnu_getcwd();
1340 char *pwd = getenv("PWD");
1344 if (stat(pwd, &st_pwd) != 0) {
1347 if (stat(cwd, &st_cwd) != 0) {
1350 if (st_pwd.st_dev == st_cwd.st_dev && st_pwd.st_ino == st_cwd.st_ino) {
1352 return x_strdup(pwd);
1358 // Check whether s1 and s2 have the same executable name.
1360 same_executable_name(const char *s1, const char *s2)
1363 bool eq = strcasecmp(s1, s2) == 0;
1365 char *tmp = format("%s.exe", s2);
1366 eq = strcasecmp(s1, tmp) == 0;
1371 return str_eq(s1, s2);
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.
1378 common_dir_prefix_length(const char *s1, const char *s2)
1380 const char *p1 = s1;
1381 const char *p2 = s2;
1383 while (*p1 && *p2 && *p1 == *p2) {
1387 while ((*p1 && *p1 != '/') || (*p2 && *p2 != '/')) {
1391 if (!*p1 && !*p2 && p2 == s2 + 1) {
1392 // Special case for s1 and s2 both being "/".
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
1402 get_relative_path(const char *from, const char *to)
1404 size_t common_prefix_len;
1407 assert(from && is_absolute_path(from));
1410 if (!*to || !is_absolute_path(to)) {
1411 return x_strdup(to);
1415 // Paths can be escaped by a slash for use with -isystem.
1416 if (from[0] == '/') {
1422 // Both paths are absolute, drop the drive letters.
1423 assert(from[0] == to[0]); // Assume the same drive letter.
1428 result = x_strdup("");
1429 common_prefix_len = common_dir_prefix_length(from, to);
1430 if (common_prefix_len > 0 || !str_eq(from, "/")) {
1432 for (p = from + common_prefix_len; *p; p++) {
1434 reformat(&result, "../%s", result);
1438 if (strlen(to) > common_prefix_len) {
1439 reformat(&result, "%s%s", result, to + common_prefix_len + 1);
1441 for (int i = strlen(result) - 1; i >= 0 && result[i] == '/'; i--) {
1444 if (str_eq(result, "")) {
1446 result = x_strdup(".");
1451 // Return whether path is absolute.
1453 is_absolute_path(const char *path)
1456 return path[0] && path[1] == ':';
1458 return path[0] == '/';
1462 // Return whether the argument is a full path.
1464 is_full_path(const char *path)
1466 if (strchr(path, '/')) {
1470 if (strchr(path, '\\')) {
1477 bool is_symlink(const char *path)
1484 return x_lstat(path, &st) == 0 && ((st.st_mode & S_IFMT) == S_IFLNK);
1488 // Update the modification time of a file in the cache to save it from LRU
1491 update_mtime(const char *path)
1500 // If exit() already has been called, call _exit(), otherwise exit(). This is
1501 // used to avoid calling exit() inside an atexit handler.
1505 static bool first_time = true;
1514 // Rename oldpath to newpath (deleting newpath).
1516 x_rename(const char *oldpath, const char *newpath)
1519 return rename(oldpath, newpath);
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) {
1526 DWORD dw = GetLastError();
1528 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1529 FORMAT_MESSAGE_FROM_SYSTEM |
1530 FORMAT_MESSAGE_IGNORE_INSERTS,
1532 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lp_msg_buf,
1536 LPVOID lp_display_buf = (LPVOID) LocalAlloc(
1538 (lstrlen((LPCTSTR) lp_msg_buf) + lstrlen((LPCTSTR) __FILE__) + 40)
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);
1545 cc_log("can't rename file %s to %s OS returned error: %s",
1546 oldpath, newpath, (char *) lp_display_buf);
1548 LocalFree(lp_msg_buf);
1549 LocalFree(lp_display_buf);
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().
1560 tmp_unlink(const char *path)
1562 cc_log("Unlink %s", path);
1563 int rc = unlink(path);
1565 cc_log("Unlink failed: %s", strerror(errno));
1571 do_x_unlink(const char *path, bool log_failure)
1573 int saved_errno = 0;
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
1578 char *tmp_name = format("%s.rm.%s", path, tmp_string());
1581 if (x_rename(path, tmp_name) == -1) {
1583 saved_errno = errno;
1586 if (unlink(tmp_name) == -1) {
1587 // If it was released in a race, that's OK.
1588 if (errno != ENOENT && errno != ESTALE) {
1590 saved_errno = errno;
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));
1602 errno = saved_errno;
1606 // Remove path, NFS safe, log both successes and failures.
1608 x_unlink(const char *path)
1610 return do_x_unlink(path, true);
1613 // Remove path, NFS safe, only log successes.
1615 x_try_unlink(const char *path)
1617 return do_x_unlink(path, false);
1621 // Like readlink() but returns the string or NULL on failure. Caller frees.
1623 x_readlink(const char *path)
1625 long maxlen = path_max(path);
1626 char *buf = x_malloc(maxlen);
1627 ssize_t len = readlink(path, buf, maxlen-1);
1637 // Reads the content of a file. Size hint 0 means no hint. Returns true on
1638 // success, otherwise false.
1640 read_file(const char *path, size_t size_hint, char **data, size_t *size)
1642 if (size_hint == 0) {
1644 if (x_stat(path, &st) == 0) {
1645 size_hint = st.st_size;
1648 size_hint = (size_hint < 1024) ? 1024 : size_hint;
1650 int fd = open(path, O_RDONLY | O_BINARY);
1654 size_t allocated = size_hint;
1655 *data = x_malloc(allocated);
1659 if (pos > allocated / 2) {
1661 *data = x_realloc(*data, allocated);
1663 ret = read(fd, *data + pos, allocated - pos);
1664 if (ret == 0 || (ret == -1 && errno != EINTR)) {
1673 cc_log("Failed reading %s", path);
1683 // Return the content (with NUL termination) of a text file, or NULL on error.
1684 // Caller frees. Size hint 0 means no hint.
1686 read_text_file(const char *path, size_t size_hint)
1690 if (read_file(path, size_hint, &data, &size)) {
1691 data = x_realloc(data, size + 1);
1700 expand_variable(const char **str, char **result, char **errmsg)
1702 assert(**str == '$');
1705 const char *p = *str + 1;
1714 while (isalnum(*q) || *q == '_') {
1719 *errmsg = format("syntax error: missing '}' after \"%s\"", p);
1725 // Special case: don't consider a single $ the start of a variable.
1726 reformat(result, "%s$", *result);
1730 char *name = x_strndup(p, q - p);
1731 const char *value = getenv(name);
1733 *errmsg = format("environment variable \"%s\" not set", name);
1737 reformat(result, "%s%s", *result, value);
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).
1751 subst_env_in_string(const char *str, char **errmsg)
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) {
1761 reformat(&result, "%s%.*s", result, (int)(q - p), p);
1762 if (!expand_variable(&q, &result, errmsg)) {
1769 reformat(&result, "%s%.*s", result, (int)(q - p), p);
1774 set_cloexec_flag(int fd)
1777 int flags = fcntl(fd, F_GETFD, 0);
1779 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
1786 double time_seconds(void)
1788 #ifdef HAVE_GETTIMEOFDAY
1790 gettimeofday(&tv, NULL);
1791 return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
1793 return (double)time(NULL);