1 // Copyright (C) 2002 Andrew Tridgell
2 // Copyright (C) 2009-2018 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>
37 static char *logbuffer;
38 static size_t logbufsize;
39 static size_t logsize;
41 #define LOGBUFSIZ 1024
46 extern struct conf *conf;
48 if (logbuffer || logfile) {
53 logbufsize = LOGBUFSIZ;
54 logbuffer = x_malloc(logbufsize);
57 if (str_eq(conf->log_file, "")) {
60 logfile = fopen(conf->log_file, "a");
63 set_cloexec_flag(fileno(logfile));
72 append_log(const char *s, size_t len)
75 if (logsize + len + 1 > logbufsize) {
76 logbufsize = logbufsize + len + 1 + LOGBUFSIZ;
77 logbuffer = x_realloc(logbuffer, logbufsize);
79 memcpy(logbuffer + logsize, s, len);
84 log_prefix(bool log_updated_time)
86 static char prefix[200];
87 #ifdef HAVE_GETTIMEOFDAY
88 if (log_updated_time) {
92 gettimeofday(&tv, NULL);
93 #ifdef __MINGW64_VERSION_MAJOR
94 tm = localtime((time_t *)&tv.tv_sec);
96 tm = localtime(&tv.tv_sec);
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());
103 snprintf(prefix, sizeof(prefix), "[%-5d] ", (int)getpid());
106 fputs(prefix, logfile);
109 append_log(prefix, strlen(prefix));
114 path_max(const char *path)
119 #elif defined(MAXPATHLEN)
122 #elif defined(_PC_PATH_MAX)
123 long maxlen = pathconf(path, _PC_PATH_MAX);
124 return maxlen >= 4096 ? maxlen : 4096;
128 static void warn_log_fail(void) ATTR_NORETURN;
130 // Warn about failure writing to the log file and then exit.
134 extern struct conf *conf;
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);
143 vlog(const char *format, va_list ap, bool log_updated_time)
151 log_prefix(log_updated_time);
153 int rc1 = vfprintf(logfile, format, ap);
154 int rc2 = fprintf(logfile, "\n");
155 if (rc1 < 0 || rc2 < 0) {
161 size_t len = vsnprintf(buf, sizeof(buf), format, aq);
162 append_log(buf, len);
168 // Write a message to the log file (adding a newline) and flush.
170 cc_log(const char *format, ...)
173 va_start(ap, format);
174 vlog(format, ap, true);
181 // Write a message to the log file (adding a newline) without flushing and with
182 // a reused timestamp.
184 cc_bulklog(const char *format, ...)
187 va_start(ap, format);
188 vlog(format, ap, false);
192 // Log an executed command to the CCACHE_LOGFILE location.
194 cc_log_argv(const char *prefix, char **argv)
202 fputs(prefix, logfile);
203 print_command(logfile, argv);
204 int rc = fflush(logfile);
210 append_log(prefix, strlen(prefix));
211 char *s = format_command(argv);
212 append_log(s, strlen(s));
217 // Copy the current log memory buffer to an output file.
219 cc_dump_log_buffer(const char *path)
221 FILE *file = fopen(path, "w");
222 (void) fwrite(logbuffer, 1, logsize, file);
226 // Something went badly wrong!
228 fatal(const char *format, ...)
231 va_start(ap, format);
233 vsnprintf(msg, sizeof(msg), format, ap);
236 cc_log("FATAL: %s", msg);
237 fprintf(stderr, "ccache: error: %s\n", msg);
242 // Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
244 copy_fd(int fd_in, int fd_out)
246 gzFile gz_in = gzdopen(dup(fd_in), "rb");
248 fatal("Failed to copy fd");
252 char buf[READ_BUFFER_SIZE];
253 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
256 ssize_t count = write(fd_out, buf + written, n - written);
258 if (errno != EAGAIN && errno != EINTR) {
259 fatal("Failed to copy fd");
264 } while (written < n);
271 // Cheap and nasty mkstemp replacement.
273 mkstemp(char *template)
276 #pragma GCC diagnostic push
277 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
281 #pragma GCC diagnostic pop
283 return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
291 static bool mask_retrieved = false;
293 if (!mask_retrieved) {
296 mask_retrieved = true;
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.
306 copy_file(const char *src, const char *dest, int compress_level)
310 gzFile gz_out = NULL;
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");
320 int fd_in = open(src, O_RDONLY | O_BINARY);
323 cc_log("open error: %s", strerror(saved_errno));
327 gz_in = gzdopen(fd_in, "rb");
330 cc_log("gzdopen(src) error: %s", strerror(saved_errno));
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.
340 if (x_fstat(fd_in, &st) != 0) {
343 if (file_size(&st) == 0) {
348 if (compress_level > 0) {
349 gz_out = gzdopen(dup(fd_out), "wb");
352 cc_log("gzdopen(dest) error: %s", strerror(saved_errno));
355 gzsetparams(gz_out, compress_level, Z_DEFAULT_STRATEGY);
359 char buf[READ_BUFFER_SIZE];
360 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
362 if (compress_level > 0) {
363 written = gzwrite(gz_out, buf, n);
367 ssize_t count = write(fd_out, buf + written, n - written);
368 if (count == -1 && errno != EINTR) {
373 } while (written < n);
376 if (compress_level > 0) {
378 cc_log("gzwrite error: %s (errno: %s)",
379 gzerror(gz_in, &errnum),
380 strerror(saved_errno));
382 cc_log("write error: %s", strerror(saved_errno));
388 // gzeof won't tell if there's an error in the trailing CRC, so we must check
389 // gzerror before considering everything OK.
391 gzerror(gz_in, &errnum);
392 if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
394 cc_log("gzread error: %s (errno: %s)",
395 gzerror(gz_in, &errnum), strerror(saved_errno));
401 tmp_unlink(tmp_name);
414 fchmod(fd_out, 0666 & ~get_umask());
417 // The close can fail on NFS if out of space.
418 if (close(fd_out) == -1) {
420 cc_log("close error: %s", strerror(saved_errno));
424 if (x_rename(tmp_name, dest) == -1) {
426 cc_log("rename error: %s", strerror(saved_errno));
444 tmp_unlink(tmp_name);
450 // Run copy_file() and, if successful, delete the source file.
452 move_file(const char *src, const char *dest, int compress_level)
454 int ret = copy_file(src, dest, compress_level);
461 // Like move_file(), but assumes that src is uncompressed and that src and dest
462 // are on the same file system.
464 move_uncompressed_file(const char *src, const char *dest, int compress_level)
466 if (compress_level > 0) {
467 return move_file(src, dest, compress_level);
469 return x_rename(src, dest);
473 // Test if a file is zlib compressed.
475 file_is_compressed(const char *filename)
477 FILE *f = fopen(filename, "rb");
482 // Test if file starts with 1F8B, which is zlib's magic number.
483 if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
492 // Make sure a directory exists.
494 create_dir(const char *dir)
497 if (stat(dir, &st) == 0) {
498 if (S_ISDIR(st.st_mode)) {
504 if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
510 // Create directories leading to path. Returns 0 on success, otherwise -1.
512 create_parent_dirs(const char *path)
515 char *parent = dirname(path);
517 if (stat(parent, &st) == 0) {
518 if (S_ISDIR(st.st_mode)) {
525 res = create_parent_dirs(parent);
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
536 if (res != 0 && errno == EEXIST) {
547 // Return a static string with the current hostname.
551 static char hostname[260] = "";
557 strcpy(hostname, "unknown");
559 gethostname(hostname, sizeof(hostname) - 1);
560 #elif defined(_WIN32)
561 const char *computer_name = getenv("COMPUTERNAME");
563 snprintf(hostname, sizeof(hostname), "%s", computer_name);
567 WORD w_version_requested = MAKEWORD(2, 2);
569 int err = WSAStartup(w_version_requested, &wsa_data);
571 // Tell the user that we could not find a usable Winsock DLL.
572 cc_log("WSAStartup failed with error: %d", err);
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");
583 int result = gethostname(hostname, sizeof(hostname) - 1);
586 DWORD dw = WSAGetLastError();
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);
595 LPVOID lp_display_buf = (LPVOID) LocalAlloc(
597 (lstrlen((LPCTSTR) lp_msg_buf) + lstrlen((LPCTSTR) __FILE__) + 200)
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);
604 cc_log("can't get hostname OS returned error: %s", (char *)lp_display_buf);
606 LocalFree(lp_msg_buf);
607 LocalFree(lp_display_buf);
612 hostname[sizeof(hostname) - 1] = 0;
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.
623 ret = format("%s.%u.XXXXXX", get_hostname(), (unsigned)getpid());
628 // Return the hash result as a hex string. Size -1 means don't include size
629 // suffix. Caller frees.
631 format_hash_as_string(const unsigned char *hash, int size)
634 char *ret = x_malloc(53);
635 for (i = 0; i < 16; i++) {
636 sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
639 sprintf(&ret[i*2], "-%d", size);
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";
651 create_cachedirtag(const char *dir)
653 char *filename = format("%s/CACHEDIR.TAG", dir);
655 if (stat(filename, &st) == 0) {
656 if (S_ISREG(st.st_mode)) {
662 FILE *f = fopen(filename, "w");
666 if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
681 // Construct a string according to a format. Caller frees.
683 format(const char *format, ...)
686 va_start(ap, format);
689 if (vasprintf(&ptr, format, ap) == -1) {
690 fatal("Out of memory in format");
695 fatal("Internal error in format");
700 // This is like strdup() but dies if the malloc fails.
702 x_strdup(const char *s)
704 char *ret = strdup(s);
706 fatal("Out of memory in x_strdup");
711 // This is like strndup() but dies if the malloc fails.
713 x_strndup(const char *s, size_t n)
720 while (m < n && s[m]) {
723 char *ret = malloc(m + 1);
729 char *ret = strndup(s, n);
732 fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
737 // This is like malloc() but dies if the malloc fails.
739 x_malloc(size_t size)
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.
746 void *ret = malloc(size);
748 fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
753 // This is like calloc() but dies if the allocation fails.
755 x_calloc(size_t nmemb, size_t size)
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.
762 void *ret = calloc(nmemb, size);
764 fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
769 // This is like realloc() but dies if the malloc fails.
771 x_realloc(void *ptr, size_t size)
774 return x_malloc(size);
776 void *p2 = realloc(ptr, size);
778 fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
783 // This is like unsetenv.
784 void x_unsetenv(const char *name)
789 putenv(x_strdup(name)); // Leak to environment.
793 // Like fstat() but also call cc_log on failure.
795 x_fstat(int fd, struct stat *buf)
797 int result = fstat(fd, buf);
799 cc_log("Failed to fstat fd %d: %s", fd, strerror(errno));
804 // Like lstat() but also call cc_log on failure.
806 x_lstat(const char *pathname, struct stat *buf)
808 int result = lstat(pathname, buf);
810 cc_log("Failed to lstat %s: %s", pathname, strerror(errno));
815 // Like stat() but also call cc_log on failure.
817 x_stat(const char *pathname, struct stat *buf)
819 int result = stat(pathname, buf);
821 cc_log("Failed to stat %s: %s", pathname, strerror(errno));
826 // Construct a string according to the format and store it in *ptr. The
827 // original *ptr is then freed.
829 reformat(char **ptr, const char *format, ...)
835 va_start(ap, format);
836 if (vasprintf(ptr, format, ap) == -1) {
837 fatal("Out of memory in reformat");
846 // Recursive directory traversal. fn() is called on all entries in the tree.
848 traverse(const char *dir, void (*fn)(const char *, struct stat *))
850 DIR *d = opendir(dir);
856 while ((de = readdir(d))) {
857 if (str_eq(de->d_name, ".")) {
860 if (str_eq(de->d_name, "..")) {
864 if (strlen(de->d_name) == 0) {
868 char *fname = format("%s/%s", dir, de->d_name);
870 if (lstat(fname, &st)) {
871 if (errno != ENOENT && errno != ESTALE) {
872 fatal("lstat %s failed: %s", fname, strerror(errno));
878 if (S_ISDIR(st.st_mode)) {
890 // Return the base name of a file - caller frees.
892 basename(const char *path)
894 char *p = strrchr(path, '/');
899 p = strrchr(path, '\\');
905 return x_strdup(path);
908 // Return the dir name of a file - caller frees.
910 dirname(const char *path)
912 char *s = x_strdup(path);
913 char *p = strrchr(s, '/');
915 char *p2 = strrchr(s, '\\');
916 if (!p || (p2 && p < p2)) {
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
935 get_extension(const char *path)
937 size_t len = strlen(path);
938 for (const char *p = &path[len - 1]; p >= path; --p) {
949 // Return a string containing the given path without the filename extension.
952 remove_extension(const char *path)
954 return x_strndup(path, strlen(path) - strlen(get_extension(path)));
957 // Return size on disk of a file.
959 file_size(struct stat *st)
962 return (st->st_size + 1023) & ~1023;
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;
973 // Format a size as a human-readable string. Caller frees.
975 format_human_readable_size(uint64_t v)
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)));
983 s = format("%.1f kB", v/((double)(1000)));
988 // Format a size as a parsable string. Caller frees.
990 format_parsable_size_with_suffix(uint64_t size)
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)));
1000 s = format("%u", (unsigned)size);
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.
1009 parse_size_with_suffix(const char *str, uint64_t *size)
1014 double x = strtod(str, &p);
1015 if (errno != 0 || x < 0 || p == str || *str == '\0') {
1019 while (isspace(*p)) {
1024 unsigned multiplier = *(p+1) == 'i' ? 1024 : 1000;
1043 // Default suffix: G.
1044 x *= 1000 * 1000 * 1000;
1046 *size = (uint64_t)x;
1051 #if !defined(HAVE_REALPATH) && \
1052 defined(_WIN32) && \
1053 !defined(HAVE_GETFINALPATHNAMEBYHANDLEW)
1054 static BOOL GetFileNameFromHandle(HANDLE file_handle, TCHAR *filename,
1057 BOOL success = FALSE;
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.
1067 // Create a file mapping object.
1069 CreateFileMapping(file_handle, NULL, PAGE_READONLY, 0, 1, NULL);
1074 // Create a file mapping to get the file name.
1075 void *mem = MapViewOfFile(file_map, FILE_MAP_READ, 0, 0, 1);
1077 if (GetMappedFileName(GetCurrentProcess(),
1081 // Translate path with device name to drive letters.
1085 if (GetLogicalDriveStrings(512-1, temp)) {
1086 TCHAR name[MAX_PATH];
1087 TCHAR drive[3] = TEXT(" :");
1092 // Copy the drive letter to the template string.
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('\\');
1102 // Reconstruct filename using temp_file and replace device path
1104 TCHAR temp_file[MAX_PATH];
1105 _sntprintf(temp_file,
1110 _tcsncpy(filename, temp_file, _tcslen(temp_file));
1115 // Go to the next NULL character.
1119 } while (!found && *p); // End of string.
1123 UnmapViewOfFile(mem);
1126 CloseHandle(file_map);
1131 // A sane realpath() function, trying to cope with stupid path limits and a
1132 // broken API. Caller frees.
1134 x_realpath(const char *path)
1136 long maxlen = path_max(path);
1137 char *ret = x_malloc(maxlen);
1141 p = realpath(path, ret);
1142 #elif defined(_WIN32)
1143 if (path[0] == '/') {
1144 path++; // Skip leading slash.
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);
1153 GetFileNameFromHandle(path_handle, ret, maxlen);
1155 CloseHandle(path_handle);
1156 p = ret + 4; // Strip \\?\ from the file name.
1158 snprintf(ret, maxlen, "%s", path);
1162 // Yes, there are such systems. This replacement relies on the fact that when
1163 // we call x_realpath we only care about symlinks.
1165 int len = readlink(path, ret, maxlen-1);
1183 // A getcwd that will returns an allocated buffer.
1187 unsigned size = 128;
1190 char *buffer = (char *)x_malloc(size);
1191 if (getcwd(buffer, size) == buffer) {
1195 if (errno != ERANGE) {
1196 cc_log("getcwd error: %d (%s)", errno, strerror(errno));
1203 #ifndef HAVE_STRTOK_R
1204 // strtok_r replacement.
1206 strtok_r(char *str, const char *delim, char **saveptr)
1211 int len = strlen(str);
1212 char *ret = strtok(str, delim);
1218 if ((len + 1) == (intptr_t) (save - str)) {
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.
1230 create_tmp_fd(char **fname)
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));
1239 reformat(&template, "%s.%s", *fname, tmp_string());
1240 fd = mkstemp(template);
1243 fatal("Failed to create temporary file for %s: %s",
1244 *fname, strerror(errno));
1246 set_cloexec_flag(fd);
1249 fchmod(fd, 0666 & ~get_umask());
1257 // Create an empty temporary file. *fname will be reallocated and set to the
1258 // resulting filename. Returns an open FILE*.
1260 create_tmp_file(char **fname, const char *mode)
1262 FILE *file = fdopen(create_tmp_fd(fname), mode);
1264 fatal("Failed to create file %s: %s", *fname, strerror(errno));
1269 // Return current user's home directory, or NULL if it can't be determined.
1271 get_home_directory(void)
1273 const char *p = getenv("HOME");
1278 p = getenv("APPDATA");
1283 #ifdef HAVE_GETPWUID
1285 struct passwd *pwd = getpwuid(getuid());
1294 // Get the current directory by reading $PWD. If $PWD isn't sane, gnu_getcwd()
1295 // is used. Caller frees.
1302 char *cwd = gnu_getcwd();
1306 char *pwd = getenv("PWD");
1310 if (stat(pwd, &st_pwd) != 0) {
1313 if (stat(cwd, &st_cwd) != 0) {
1316 if (st_pwd.st_dev == st_cwd.st_dev && st_pwd.st_ino == st_cwd.st_ino) {
1318 return x_strdup(pwd);
1324 // Check whether s1 and s2 have the same executable name.
1326 same_executable_name(const char *s1, const char *s2)
1329 bool eq = strcasecmp(s1, s2) == 0;
1331 char *tmp = format("%s.exe", s2);
1332 eq = strcasecmp(s1, tmp) == 0;
1337 return str_eq(s1, s2);
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.
1344 common_dir_prefix_length(const char *s1, const char *s2)
1346 const char *p1 = s1;
1347 const char *p2 = s2;
1349 while (*p1 && *p2 && *p1 == *p2) {
1353 while ((*p1 && *p1 != '/') || (*p2 && *p2 != '/')) {
1357 if (!*p1 && !*p2 && p2 == s2 + 1) {
1358 // Special case for s1 and s2 both being "/".
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
1368 get_relative_path(const char *from, const char *to)
1370 size_t common_prefix_len;
1373 assert(from && is_absolute_path(from));
1376 if (!*to || !is_absolute_path(to)) {
1377 return x_strdup(to);
1381 // Paths can be escaped by a slash for use with -isystem.
1382 if (from[0] == '/') {
1388 // Both paths are absolute, drop the drive letters.
1389 assert(from[0] == to[0]); // Assume the same drive letter.
1394 result = x_strdup("");
1395 common_prefix_len = common_dir_prefix_length(from, to);
1396 if (common_prefix_len > 0 || !str_eq(from, "/")) {
1398 for (p = from + common_prefix_len; *p; p++) {
1400 reformat(&result, "../%s", result);
1404 if (strlen(to) > common_prefix_len) {
1405 reformat(&result, "%s%s", result, to + common_prefix_len + 1);
1407 for (int i = strlen(result) - 1; i >= 0 && result[i] == '/'; i--) {
1410 if (str_eq(result, "")) {
1412 result = x_strdup(".");
1417 // Return whether path is absolute.
1419 is_absolute_path(const char *path)
1422 return path[0] && path[1] == ':';
1424 return path[0] == '/';
1428 // Return whether the argument is a full path.
1430 is_full_path(const char *path)
1432 if (strchr(path, '/')) {
1436 if (strchr(path, '\\')) {
1443 bool is_symlink(const char *path)
1450 return x_lstat(path, &st) == 0 && ((st.st_mode & S_IFMT) == S_IFLNK);
1454 // Update the modification time of a file in the cache to save it from LRU
1457 update_mtime(const char *path)
1466 // If exit() already has been called, call _exit(), otherwise exit(). This is
1467 // used to avoid calling exit() inside an atexit handler.
1471 static bool first_time = true;
1480 // Rename oldpath to newpath (deleting newpath).
1482 x_rename(const char *oldpath, const char *newpath)
1485 return rename(oldpath, newpath);
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) {
1492 DWORD dw = GetLastError();
1494 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1495 FORMAT_MESSAGE_FROM_SYSTEM |
1496 FORMAT_MESSAGE_IGNORE_INSERTS,
1498 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lp_msg_buf,
1502 LPVOID lp_display_buf = (LPVOID) LocalAlloc(
1504 (lstrlen((LPCTSTR) lp_msg_buf) + lstrlen((LPCTSTR) __FILE__) + 40)
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);
1511 cc_log("can't rename file %s to %s OS returned error: %s",
1512 oldpath, newpath, (char *) lp_display_buf);
1514 LocalFree(lp_msg_buf);
1515 LocalFree(lp_display_buf);
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().
1526 tmp_unlink(const char *path)
1528 cc_log("Unlink %s", path);
1529 int rc = unlink(path);
1531 cc_log("Unlink failed: %s", strerror(errno));
1537 do_x_unlink(const char *path, bool log_failure)
1539 int saved_errno = 0;
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
1544 char *tmp_name = format("%s.rm.%s", path, tmp_string());
1547 if (x_rename(path, tmp_name) == -1) {
1549 saved_errno = errno;
1552 if (unlink(tmp_name) == -1) {
1553 // If it was released in a race, that's OK.
1554 if (errno != ENOENT && errno != ESTALE) {
1556 saved_errno = errno;
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));
1568 errno = saved_errno;
1572 // Remove path, NFS safe, log both successes and failures.
1574 x_unlink(const char *path)
1576 return do_x_unlink(path, true);
1579 // Remove path, NFS safe, only log successes.
1581 x_try_unlink(const char *path)
1583 return do_x_unlink(path, false);
1587 // Like readlink() but returns the string or NULL on failure. Caller frees.
1589 x_readlink(const char *path)
1591 long maxlen = path_max(path);
1592 char *buf = x_malloc(maxlen);
1593 ssize_t len = readlink(path, buf, maxlen-1);
1603 // Reads the content of a file. Size hint 0 means no hint. Returns true on
1604 // success, otherwise false.
1606 read_file(const char *path, size_t size_hint, char **data, size_t *size)
1608 if (size_hint == 0) {
1610 if (x_stat(path, &st) == 0) {
1611 size_hint = st.st_size;
1614 size_hint = (size_hint < 1024) ? 1024 : size_hint;
1616 int fd = open(path, O_RDONLY | O_BINARY);
1620 size_t allocated = size_hint;
1621 *data = x_malloc(allocated);
1625 if (pos > allocated / 2) {
1627 *data = x_realloc(*data, allocated);
1629 ret = read(fd, *data + pos, allocated - pos);
1630 if (ret == 0 || (ret == -1 && errno != EINTR)) {
1639 cc_log("Failed reading %s", path);
1649 // Return the content (with NUL termination) of a text file, or NULL on error.
1650 // Caller frees. Size hint 0 means no hint.
1652 read_text_file(const char *path, size_t size_hint)
1656 if (read_file(path, size_hint, &data, &size)) {
1657 data = x_realloc(data, size + 1);
1666 expand_variable(const char **str, char **result, char **errmsg)
1668 assert(**str == '$');
1671 const char *p = *str + 1;
1680 while (isalnum(*q) || *q == '_') {
1685 *errmsg = format("syntax error: missing '}' after \"%s\"", p);
1691 // Special case: don't consider a single $ the start of a variable.
1692 reformat(result, "%s$", *result);
1696 char *name = x_strndup(p, q - p);
1697 const char *value = getenv(name);
1699 *errmsg = format("environment variable \"%s\" not set", name);
1703 reformat(result, "%s%s", *result, value);
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).
1717 subst_env_in_string(const char *str, char **errmsg)
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) {
1727 reformat(&result, "%s%.*s", result, (int)(q - p), p);
1728 if (!expand_variable(&q, &result, errmsg)) {
1735 reformat(&result, "%s%.*s", result, (int)(q - p), p);
1740 set_cloexec_flag(int fd)
1743 int flags = fcntl(fd, F_GETFD, 0);
1745 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);