2 * Copyright (C) 2002 Andrew Tridgell
3 * Copyright (C) 2009-2016 Joel Rosdahl
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the Free
7 * Software Foundation; either version 3 of the License, or (at your option)
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #ifdef HAVE_SYS_TIME_H
33 #include <sys/locking.h>
41 extern struct conf *conf;
47 if (str_eq(conf->log_file, "")) {
50 logfile = fopen(conf->log_file, "a");
53 int fd = fileno(logfile);
54 int flags = fcntl(fd, F_GETFD, 0);
56 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
66 log_prefix(bool log_updated_time)
68 #ifdef HAVE_GETTIMEOFDAY
69 static char prefix[200];
71 if (log_updated_time) {
75 gettimeofday(&tv, NULL);
76 #ifdef __MINGW64_VERSION_MAJOR
77 tm = localtime((time_t *)&tv.tv_sec);
79 tm = localtime(&tv.tv_sec);
81 strftime(timestamp, sizeof(timestamp), "%Y-%m-%dT%H:%M:%S", tm);
82 snprintf(prefix, sizeof(prefix),
83 "[%s.%06d %-5d] ", timestamp, (int)tv.tv_usec, (int)getpid());
85 fputs(prefix, logfile);
87 fprintf(logfile, "[%-5d] ", (int)getpid());
92 path_max(const char *path)
97 #elif defined(MAXPATHLEN)
100 #elif defined(_PC_PATH_MAX)
101 long maxlen = pathconf(path, _PC_PATH_MAX);
102 if (maxlen >= 4096) {
111 * Warn about failure writing to the log file and then exit.
116 extern struct conf *conf;
118 /* Note: Can't call fatal() since that would lead to recursion. */
119 fprintf(stderr, "ccache: error: Failed to write to %s: %s\n",
120 conf->log_file, strerror(errno));
121 x_exit(EXIT_FAILURE);
125 vlog(const char *format, va_list ap, bool log_updated_time)
132 log_prefix(log_updated_time);
133 rc1 = vfprintf(logfile, format, ap);
134 rc2 = fprintf(logfile, "\n");
135 if (rc1 < 0 || rc2 < 0) {
141 * Write a message to the log file (adding a newline) and flush.
144 cc_log(const char *format, ...)
147 va_start(ap, format);
148 vlog(format, ap, true);
156 * Write a message to the log file (adding a newline) without flushing and with
157 * a reused timestamp.
160 cc_bulklog(const char *format, ...)
163 va_start(ap, format);
164 vlog(format, ap, false);
169 * Log an executed command to the CCACHE_LOGFILE location.
172 cc_log_argv(const char *prefix, char **argv)
180 fputs(prefix, logfile);
181 print_command(logfile, argv);
182 rc = fflush(logfile);
188 /* something went badly wrong! */
190 fatal(const char *format, ...)
195 va_start(ap, format);
196 vsnprintf(msg, sizeof(msg), format, ap);
199 cc_log("FATAL: %s", msg);
200 fprintf(stderr, "ccache: error: %s\n", msg);
206 * Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
209 copy_fd(int fd_in, int fd_out)
215 gz_in = gzdopen(dup(fd_in), "rb");
218 fatal("Failed to copy fd");
221 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
224 ssize_t count = write(fd_out, buf + written, n - written);
226 if (errno != EAGAIN && errno != EINTR) {
227 fatal("Failed to copy fd");
232 } while (written < n);
239 /* cheap and nasty mkstemp replacement */
241 mkstemp(char *template)
244 return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
252 static bool mask_retrieved = false;
254 if (!mask_retrieved) {
257 mask_retrieved = true;
264 * Copy src to dest, decompressing src if needed. compress_level > 0 decides
265 * whether dest will be compressed, and with which compression level. Returns 0
266 * on success and -1 on failure. On failure, errno represents the error.
269 copy_file(const char *src, const char *dest, int compress_level)
272 gzFile gz_in = NULL, gz_out = NULL;
280 /* open destination file */
281 tmp_name = x_strdup(dest);
282 fd_out = create_tmp_fd(&tmp_name);
283 cc_log("Copying %s to %s via %s (%scompressed)",
284 src, dest, tmp_name, compress_level > 0 ? "" : "un");
286 /* open source file */
287 fd_in = open(src, O_RDONLY | O_BINARY);
290 cc_log("open error: %s", strerror(saved_errno));
294 gz_in = gzdopen(fd_in, "rb");
297 cc_log("gzdopen(src) error: %s", strerror(saved_errno));
302 if (compress_level > 0) {
304 * A gzip file occupies at least 20 bytes, so it will always
305 * occupy an entire filesystem block, even for empty files.
306 * Turn off compression for empty files to save some space.
308 if (x_fstat(fd_in, &st) != 0) {
311 if (file_size(&st) == 0) {
316 if (compress_level > 0) {
317 gz_out = gzdopen(dup(fd_out), "wb");
320 cc_log("gzdopen(dest) error: %s", strerror(saved_errno));
323 gzsetparams(gz_out, compress_level, Z_DEFAULT_STRATEGY);
326 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
327 if (compress_level > 0) {
328 written = gzwrite(gz_out, buf, n);
332 ssize_t count = write(fd_out, buf + written, n - written);
333 if (count == -1 && errno != EINTR) {
338 } while (written < n);
341 if (compress_level > 0) {
342 cc_log("gzwrite error: %s (errno: %s)",
343 gzerror(gz_in, &errnum),
344 strerror(saved_errno));
346 cc_log("write error: %s", strerror(saved_errno));
353 * gzeof won't tell if there's an error in the trailing CRC, so we must check
354 * gzerror before considering everything OK.
356 gzerror(gz_in, &errnum);
357 if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
359 cc_log("gzread error: %s (errno: %s)",
360 gzerror(gz_in, &errnum), strerror(saved_errno));
366 tmp_unlink(tmp_name);
379 fchmod(fd_out, 0666 & ~get_umask());
382 /* the close can fail on NFS if out of space */
383 if (close(fd_out) == -1) {
385 cc_log("close error: %s", strerror(saved_errno));
389 if (x_rename(tmp_name, dest) == -1) {
391 cc_log("rename error: %s", strerror(saved_errno));
409 tmp_unlink(tmp_name);
415 /* Run copy_file() and, if successful, delete the source file. */
417 move_file(const char *src, const char *dest, int compress_level)
421 ret = copy_file(src, dest, compress_level);
429 * Like move_file(), but assumes that src is uncompressed and that src and dest
430 * are on the same file system.
433 move_uncompressed_file(const char *src, const char *dest, int compress_level)
435 if (compress_level > 0) {
436 return move_file(src, dest, compress_level);
438 return x_rename(src, dest);
442 /* test if a file is zlib compressed */
444 file_is_compressed(const char *filename)
448 f = fopen(filename, "rb");
453 /* test if file starts with 1F8B, which is zlib's
455 if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
464 /* make sure a directory exists */
466 create_dir(const char *dir)
469 if (stat(dir, &st) == 0) {
470 if (S_ISDIR(st.st_mode)) {
476 if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
482 /* Create directories leading to path. Returns 0 on success, otherwise -1. */
484 create_parent_dirs(const char *path)
488 char *parent = dirname(path);
490 if (stat(parent, &st) == 0) {
491 if (S_ISDIR(st.st_mode)) {
498 res = create_parent_dirs(parent);
500 res = mkdir(parent, 0777);
501 /* Have to handle the condition of the directory already existing because
502 * the file system could have changed in between calling stat and
503 * actually creating the directory. This can happen when there are
504 * multiple instances of ccache running and trying to create the same
505 * directory chain, which usually is the case when the cache root does
506 * not initially exist. As long as one of the processes creates the
507 * directories then our condition is satisfied and we avoid a race
510 if (res != 0 && errno == EEXIST) {
522 * Return a static string with the current hostname.
527 static char hostname[260] = "";
533 strcpy(hostname, "unknown");
535 gethostname(hostname, sizeof(hostname) - 1);
536 #elif defined(_WIN32)
537 const char *computer_name = getenv("COMPUTERNAME");
539 snprintf(hostname, sizeof(hostname), "%s", computer_name);
543 WORD wVersionRequested;
547 wVersionRequested = MAKEWORD(2, 2);
549 err = WSAStartup(wVersionRequested, &wsaData);
551 /* Tell the user that we could not find a usable Winsock DLL. */
552 cc_log("WSAStartup failed with error: %d", err);
556 if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
557 /* Tell the user that we could not find a usable WinSock DLL. */
558 cc_log("Could not find a usable version of Winsock.dll");
563 int result = gethostname(hostname, sizeof(hostname) - 1);
565 int last_error = WSAGetLastError();
568 DWORD dw = last_error;
571 FORMAT_MESSAGE_ALLOCATE_BUFFER |
572 FORMAT_MESSAGE_FROM_SYSTEM |
573 FORMAT_MESSAGE_IGNORE_INSERTS,
574 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
575 (LPTSTR) &lpMsgBuf, 0, NULL);
577 lpDisplayBuf = (LPVOID) LocalAlloc(
579 (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) __FILE__) + 200)
581 _snprintf((LPTSTR) lpDisplayBuf,
582 LocalSize(lpDisplayBuf) / sizeof(TCHAR),
583 TEXT("%s failed with error %d: %s"), __FILE__, dw,
586 cc_log("can't get hostname OS returned error: %s", (char *)lpDisplayBuf);
589 LocalFree(lpDisplayBuf);
594 hostname[sizeof(hostname) - 1] = 0;
599 * Return a string to be passed to mkstemp to create a temporary file. Also
600 * tries to cope with NFS by adding the local hostname.
608 ret = format("%s.%u.XXXXXX", get_hostname(), (unsigned)getpid());
615 * Return the hash result as a hex string. Size -1 means don't include size
616 * suffix. Caller frees.
619 format_hash_as_string(const unsigned char *hash, int size)
625 for (i = 0; i < 16; i++) {
626 sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
629 sprintf(&ret[i*2], "-%d", size);
635 char const CACHEDIR_TAG[] =
636 "Signature: 8a477f597d28d172789f06886806bc55\n"
637 "# This file is a cache directory tag created by ccache.\n"
638 "# For information about cache directory tags, see:\n"
639 "# http://www.brynosaurus.com/cachedir/\n";
642 create_cachedirtag(const char *dir)
646 char *filename = format("%s/CACHEDIR.TAG", dir);
647 if (stat(filename, &st) == 0) {
648 if (S_ISREG(st.st_mode)) {
654 f = fopen(filename, "w");
658 if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
673 /* Construct a string according to a format. Caller frees. */
675 format(const char *format, ...)
680 va_start(ap, format);
681 if (vasprintf(&ptr, format, ap) == -1) {
682 fatal("Out of memory in format");
687 fatal("Internal error in format");
692 /* This is like strdup() but dies if the malloc fails. */
694 x_strdup(const char *s)
699 fatal("Out of memory in x_strdup");
704 /* This is like strndup() but dies if the malloc fails. */
706 x_strndup(const char *s, size_t n)
715 while (m < n && s[m]) {
727 fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
732 /* This is like malloc() but dies if the malloc fails. */
734 x_malloc(size_t size)
739 * malloc() may return NULL if size is zero, so always do this to make sure
740 * that the code handles it regardless of platform.
746 fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
751 /* This is like calloc() but dies if the allocation fails. */
753 x_calloc(size_t nmemb, size_t size)
756 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.
763 ret = calloc(nmemb, size);
765 fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
770 /* This is like realloc() but dies if the malloc fails. */
772 x_realloc(void *ptr, size_t size)
776 return x_malloc(size);
778 p2 = realloc(ptr, size);
780 fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
785 /* This is like unsetenv. */
786 void x_unsetenv(const char *name)
791 putenv(x_strdup(name)); /* Leak to environment. */
795 /* Like fstat() but also call cc_log on failure. */
797 x_fstat(int fd, struct stat *buf)
799 int result = fstat(fd, buf);
801 cc_log("Failed to fstat fd %d: %s", fd, strerror(errno));
806 /* Like lstat() but also call cc_log on failure. */
808 x_lstat(const char *pathname, struct stat *buf)
810 int result = lstat(pathname, buf);
812 cc_log("Failed to lstat %s: %s", pathname, strerror(errno));
817 /* Like stat() but also call cc_log on failure. */
819 x_stat(const char *pathname, struct stat *buf)
821 int result = stat(pathname, buf);
823 cc_log("Failed to stat %s: %s", pathname, strerror(errno));
829 * Construct a string according to the format and store it in *ptr. The
830 * original *ptr is then freed.
833 reformat(char **ptr, const char *format, ...)
839 va_start(ap, format);
840 if (vasprintf(ptr, format, ap) == -1) {
841 fatal("Out of memory in reformat");
846 fatal("Out of memory in reformat");
854 * Recursive directory traversal. fn() is called on all entries in the tree.
857 traverse(const char *dir, void (*fn)(const char *, struct stat *))
867 while ((de = readdir(d))) {
871 if (str_eq(de->d_name, ".")) {
874 if (str_eq(de->d_name, "..")) {
878 if (strlen(de->d_name) == 0) {
882 fname = format("%s/%s", dir, de->d_name);
883 if (lstat(fname, &st)) {
884 if (errno != ENOENT && errno != ESTALE) {
885 fatal("lstat %s failed: %s", fname, strerror(errno));
891 if (S_ISDIR(st.st_mode)) {
903 /* return the base name of a file - caller frees */
905 basename(const char *path)
908 p = strrchr(path, '/');
913 p = strrchr(path, '\\');
919 return x_strdup(path);
922 /* return the dir name of a file - caller frees */
924 dirname(const char *path)
934 p2 = strrchr(s, '\\');
935 if (!p || (p2 && p < p2)) {
951 * Return the file extension (including the dot) of a path as a pointer into
952 * path. If path has no file extension, the empty string and the end of path is
956 get_extension(const char *path)
958 size_t len = strlen(path);
961 for (p = &path[len - 1]; p >= path; --p) {
973 * Return a string containing the given path without the filename extension.
977 remove_extension(const char *path)
979 return x_strndup(path, strlen(path) - strlen(get_extension(path)));
982 /* return size on disk of a file */
984 file_size(struct stat *st)
987 return (st->st_size + 1023) & ~1023;
989 size_t size = st->st_blocks * 512;
990 if ((size_t)st->st_size > size) {
991 /* probably a broken stat() call ... */
992 size = (st->st_size + 1023) & ~1023;
998 /* Format a size as a human-readable string. Caller frees. */
1000 format_human_readable_size(uint64_t v)
1003 if (v >= 1000*1000*1000) {
1004 s = format("%.1f GB", v/((double)(1000*1000*1000)));
1005 } else if (v >= 1000*1000) {
1006 s = format("%.1f MB", v/((double)(1000*1000)));
1008 s = format("%.1f kB", v/((double)(1000)));
1013 /* Format a size as a parsable string. Caller frees. */
1015 format_parsable_size_with_suffix(uint64_t size)
1018 if (size >= 1000*1000*1000) {
1019 s = format("%.1fG", size / ((double)(1000*1000*1000)));
1020 } else if (size >= 1000*1000) {
1021 s = format("%.1fM", size / ((double)(1000*1000)));
1022 } else if (size >= 1000) {
1023 s = format("%.1fk", size / ((double)(1000)));
1025 s = format("%u", (unsigned)size);
1031 * Parse a "size value", i.e. a string that can end in k, M, G, T (10-based
1032 * suffixes) or Ki, Mi, Gi, Ti (2-based suffixes). For backward compatibility,
1033 * K is also recognized as a synonym of k.
1036 parse_size_with_suffix(const char *str, uint64_t *size)
1042 x = strtod(str, &p);
1043 if (errno != 0 || x < 0 || p == str || *str == '\0') {
1047 while (isspace(*p)) {
1052 unsigned multiplier;
1053 if (*(p+1) == 'i') {
1073 /* Default suffix: G. */
1074 x *= 1000 * 1000 * 1000;
1081 /* A sane realpath() function, trying to cope with stupid path limits and a
1084 x_realpath(const char *path)
1086 long maxlen = path_max(path);
1088 #if !defined(HAVE_REALPATH) && defined(_WIN32)
1092 ret = x_malloc(maxlen);
1095 p = realpath(path, ret);
1096 #elif defined(_WIN32)
1097 path_handle = CreateFile(
1098 path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1099 FILE_ATTRIBUTE_NORMAL, NULL);
1100 if (INVALID_HANDLE_VALUE != path_handle) {
1101 GetFinalPathNameByHandle(path_handle, ret, maxlen, FILE_NAME_NORMALIZED);
1102 CloseHandle(path_handle);
1103 p = ret + 4; /* strip \\?\ from the file name */
1105 snprintf(ret, maxlen, "%s", path);
1109 /* yes, there are such systems. This replacement relies on
1110 the fact that when we call x_realpath we only care about symlinks */
1112 int len = readlink(path, ret, maxlen-1);
1130 /* a getcwd that will returns an allocated buffer */
1134 unsigned size = 128;
1137 char *buffer = (char *)x_malloc(size);
1138 if (getcwd(buffer, size) == buffer) {
1142 if (errno != ERANGE) {
1143 cc_log("getcwd error: %d (%s)", errno, strerror(errno));
1150 #ifndef HAVE_STRTOK_R
1151 /* strtok_r replacement */
1153 strtok_r(char *str, const char *delim, char **saveptr)
1160 ret = strtok(str, delim);
1164 if ((len + 1) == (intptr_t) (save - str))
1173 * Create an empty temporary file. *fname will be reallocated and set to the
1174 * resulting filename. Returns an open file descriptor to the file.
1177 create_tmp_fd(char **fname)
1179 char *template = format("%s.%s", *fname, tmp_string());
1180 int fd = mkstemp(template);
1181 if (fd == -1 && errno == ENOENT) {
1182 if (create_parent_dirs(*fname) != 0) {
1183 fatal("Failed to create directory %s: %s",
1184 dirname(*fname), strerror(errno));
1186 reformat(&template, "%s.%s", *fname, tmp_string());
1187 fd = mkstemp(template);
1190 fatal("Failed to create temporary file for %s: %s",
1191 *fname, strerror(errno));
1195 fchmod(fd, 0666 & ~get_umask());
1204 * Create an empty temporary file. *fname will be reallocated and set to the
1205 * resulting filename. Returns an open FILE*.
1208 create_tmp_file(char **fname, const char *mode)
1210 FILE *file = fdopen(create_tmp_fd(fname), mode);
1212 fatal("Failed to create file %s: %s", *fname, strerror(errno));
1218 * Return current user's home directory, or NULL if it can't be determined.
1221 get_home_directory(void)
1223 const char *p = getenv("HOME");
1228 p = getenv("APPDATA");
1233 #ifdef HAVE_GETPWUID
1235 struct passwd *pwd = getpwuid(getuid());
1245 * Get the current directory by reading $PWD. If $PWD isn't sane, gnu_getcwd()
1246 * is used. Caller frees.
1260 pwd = getenv("PWD");
1264 if (stat(pwd, &st_pwd) != 0) {
1267 if (stat(cwd, &st_cwd) != 0) {
1270 if (st_pwd.st_dev == st_cwd.st_dev && st_pwd.st_ino == st_cwd.st_ino) {
1272 return x_strdup(pwd);
1279 * Check whether s1 and s2 have the same executable name.
1282 same_executable_name(const char *s1, const char *s2)
1285 bool eq = strcasecmp(s1, s2) == 0;
1287 char *tmp = format("%s.exe", s2);
1288 eq = strcasecmp(s1, tmp) == 0;
1293 return str_eq(s1, s2);
1298 * Compute the length of the longest directory path that is common to two
1299 * paths. s1 is assumed to be the path to a directory.
1302 common_dir_prefix_length(const char *s1, const char *s2)
1304 const char *p1 = s1;
1305 const char *p2 = s2;
1307 while (*p1 && *p2 && *p1 == *p2) {
1311 while ((*p1 && *p1 != '/') || (*p2 && *p2 != '/')) {
1315 if (!*p1 && !*p2 && p2 == s2 + 1) {
1316 /* Special case for s1 and s2 both being "/". */
1323 * Compute a relative path from from (an absolute path to a directory) to to (a
1324 * path). Assumes that both from and to are well-formed and canonical. Caller
1328 get_relative_path(const char *from, const char *to)
1330 size_t common_prefix_len;
1334 assert(from && is_absolute_path(from));
1337 if (!*to || !is_absolute_path(to)) {
1338 return x_strdup(to);
1342 // Both paths are absolute, drop the drive letters
1343 assert(from[0] == to[0]); // Assume the same drive letter
1348 result = x_strdup("");
1349 common_prefix_len = common_dir_prefix_length(from, to);
1350 if (common_prefix_len > 0 || !str_eq(from, "/")) {
1352 for (p = from + common_prefix_len; *p; p++) {
1354 reformat(&result, "../%s", result);
1358 if (strlen(to) > common_prefix_len) {
1359 reformat(&result, "%s%s", result, to + common_prefix_len + 1);
1361 i = strlen(result) - 1;
1362 while (i >= 0 && result[i] == '/') {
1366 if (str_eq(result, "")) {
1368 result = x_strdup(".");
1374 * Return whether path is absolute.
1377 is_absolute_path(const char *path)
1380 return path[0] && path[1] == ':';
1382 return path[0] == '/';
1387 * Return whether the argument is a full path.
1390 is_full_path(const char *path)
1392 if (strchr(path, '/'))
1395 if (strchr(path, '\\'))
1402 * Update the modification time of a file in the cache to save it from LRU
1406 update_mtime(const char *path)
1416 * If exit() already has been called, call _exit(), otherwise exit(). This is
1417 * used to avoid calling exit() inside an atexit handler.
1422 static bool first_time = true;
1432 * Rename oldpath to newpath (deleting newpath).
1435 x_rename(const char *oldpath, const char *newpath)
1438 return rename(oldpath, newpath);
1440 /* Windows' rename() refuses to overwrite an existing file. */
1441 unlink(newpath); /* not x_unlink, as x_unlink calls x_rename */
1442 /* If the function succeeds, the return value is nonzero. */
1443 if (MoveFileA(oldpath, newpath) == 0) {
1445 LPVOID lpDisplayBuf;
1446 DWORD dw = GetLastError();
1449 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1450 FORMAT_MESSAGE_FROM_SYSTEM |
1451 FORMAT_MESSAGE_IGNORE_INSERTS,
1452 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf,
1455 lpDisplayBuf = (LPVOID) LocalAlloc(
1457 (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) __FILE__) + 40)
1459 _snprintf((LPTSTR) lpDisplayBuf,
1460 LocalSize(lpDisplayBuf) / sizeof(TCHAR),
1461 TEXT("%s failed with error %d: %s"), __FILE__, dw, lpMsgBuf);
1463 cc_log("can't rename file %s to %s OS returned error: %s",
1464 oldpath, newpath, (char *) lpDisplayBuf);
1466 LocalFree(lpMsgBuf);
1467 LocalFree(lpDisplayBuf);
1476 * Remove path, NFS hazardous. Use only for temporary files that will not exist
1477 * on other systems. That is, the path should include tmp_string().
1480 tmp_unlink(const char *path)
1483 cc_log("Unlink %s", path);
1486 cc_log("Unlink failed: %s", strerror(errno));
1492 * Remove path, NFS safe.
1495 x_unlink(const char *path)
1498 * If path is on an NFS share, unlink isn't atomic, so we rename to a temp
1499 * file. We don't care if the temp file is trashed, so it's always safe to
1502 char *tmp_name = format("%s.rm.%s", path, tmp_string());
1504 int saved_errno = 0;
1505 cc_log("Unlink %s via %s", path, tmp_name);
1506 if (x_rename(path, tmp_name) == -1) {
1508 saved_errno = errno;
1511 if (unlink(tmp_name) == -1) {
1512 /* If it was released in a race, that's OK. */
1513 if (errno != ENOENT && errno != ESTALE) {
1515 saved_errno = errno;
1521 cc_log("x_unlink failed: %s", strerror(saved_errno));
1523 errno = saved_errno;
1528 /* Like readlink() but returns the string or NULL on failure. Caller frees. */
1530 x_readlink(const char *path)
1532 long maxlen = path_max(path);
1536 buf = x_malloc(maxlen);
1537 len = readlink(path, buf, maxlen-1);
1548 * Reads the content of a file. Size hint 0 means no hint. Returns true on
1549 * success, otherwise false.
1552 read_file(const char *path, size_t size_hint, char **data, size_t *size)
1555 size_t pos = 0, allocated;
1557 if (size_hint == 0) {
1559 if (x_stat(path, &st) == 0) {
1560 size_hint = st.st_size;
1563 size_hint = (size_hint < 1024) ? 1024 : size_hint;
1565 fd = open(path, O_RDONLY | O_BINARY);
1569 allocated = size_hint;
1570 *data = x_malloc(allocated);
1572 if (pos > allocated / 2) {
1574 *data = x_realloc(*data, allocated);
1576 ret = read(fd, *data + pos, allocated - pos);
1577 if (ret == 0 || (ret == -1 && errno != EINTR)) {
1586 cc_log("Failed reading %s", path);
1597 * Return the content (with NUL termination) of a text file, or NULL on error.
1598 * Caller frees. Size hint 0 means no hint.
1601 read_text_file(const char *path, size_t size_hint)
1606 if (read_file(path, size_hint, &data, &size)) {
1607 data = x_realloc(data, size + 1);
1616 expand_variable(const char **str, char **result, char **errmsg)
1623 assert(**str == '$');
1632 while (isalnum(*q) || *q == '_') {
1637 *errmsg = format("syntax error: missing '}' after \"%s\"", p);
1643 /* Special case: don't consider a single $ the start of a variable. */
1644 reformat(result, "%s$", *result);
1648 name = x_strndup(p, q - p);
1649 value = getenv(name);
1651 *errmsg = format("environment variable \"%s\" not set", name);
1655 reformat(result, "%s%s", *result, value);
1665 * Substitute all instances of $VAR or ${VAR}, where VAR is an environment
1666 * variable, in a string. Caller frees. If one of the environment variables
1667 * doesn't exist, NULL will be returned and *errmsg will be an appropriate
1668 * error message (caller frees).
1671 subst_env_in_string(const char *str, char **errmsg)
1673 const char *p; /* Interval start. */
1674 const char *q; /* Interval end. */
1680 result = x_strdup("");
1683 for (q = str; *q; ++q) {
1685 reformat(&result, "%s%.*s", result, (int)(q - p), p);
1686 if (!expand_variable(&q, &result, errmsg)) {
1693 reformat(&result, "%s%.*s", result, (int)(q - p), p);