2 * Copyright (C) 2002 Andrew Tridgell
3 * Copyright (C) 2009-2014 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
72 static char prefix[200];
74 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 vlog(const char *format, va_list ap, bool log_updated_time)
117 log_prefix(log_updated_time);
118 vfprintf(logfile, format, ap);
119 fprintf(logfile, "\n");
123 * Write a message to the log file (adding a newline) and flush.
126 cc_log(const char *format, ...)
129 va_start(ap, format);
130 vlog(format, ap, true);
138 * Write a message to the log file (adding a newline) without flushing and with
139 * a reused timestamp.
142 cc_bulklog(const char *format, ...)
145 va_start(ap, format);
146 vlog(format, ap, false);
151 * Log an executed command to the CCACHE_LOGFILE location.
154 cc_log_argv(const char *prefix, char **argv)
161 fputs(prefix, logfile);
162 print_command(logfile, argv);
166 /* something went badly wrong! */
168 fatal(const char *format, ...)
173 va_start(ap, format);
174 vsnprintf(msg, sizeof(msg), format, ap);
177 cc_log("FATAL: %s", msg);
178 fprintf(stderr, "ccache: error: %s\n", msg);
184 * Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
187 copy_fd(int fd_in, int fd_out)
193 gz_in = gzdopen(dup(fd_in), "rb");
196 fatal("Failed to copy fd");
199 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
200 ssize_t count, written = 0;
202 count = write(fd_out, buf + written, n - written);
204 if (errno != EAGAIN && errno != EINTR) {
205 fatal("Failed to copy fd");
210 } while (written < n);
217 /* cheap and nasty mkstemp replacement */
219 mkstemp(char *template)
222 return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
227 * Copy src to dest, decompressing src if needed. compress_level > 0 decides
228 * whether dest will be compressed, and with which compression level.
231 copy_file(const char *src, const char *dest, int compress_level)
234 gzFile gz_in = NULL, gz_out = NULL;
244 /* open destination file */
245 tmp_name = x_strdup(dest);
246 fd_out = create_tmp_fd(&tmp_name);
247 cc_log("Copying %s to %s via %s (%scompressed)",
248 src, dest, tmp_name, compress_level > 0 ? "" : "un");
250 /* open source file */
251 fd_in = open(src, O_RDONLY | O_BINARY);
253 cc_log("open error: %s", strerror(errno));
257 gz_in = gzdopen(fd_in, "rb");
259 cc_log("gzdopen(src) error: %s", strerror(errno));
264 if (compress_level > 0) {
266 * A gzip file occupies at least 20 bytes, so it will always
267 * occupy an entire filesystem block, even for empty files.
268 * Turn off compression for empty files to save some space.
270 if (fstat(fd_in, &st) != 0) {
271 cc_log("fstat error: %s", strerror(errno));
274 if (file_size(&st) == 0) {
279 if (compress_level > 0) {
280 gz_out = gzdopen(dup(fd_out), "wb");
282 cc_log("gzdopen(dest) error: %s", strerror(errno));
285 gzsetparams(gz_out, compress_level, Z_DEFAULT_STRATEGY);
288 while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
289 if (compress_level > 0) {
290 written = gzwrite(gz_out, buf, n);
295 count = write(fd_out, buf + written, n - written);
296 if (count == -1 && errno != EINTR) {
300 } while (written < n);
303 if (compress_level > 0) {
304 cc_log("gzwrite error: %s (errno: %s)",
305 gzerror(gz_in, &errnum),
308 cc_log("write error: %s", strerror(errno));
315 * gzeof won't tell if there's an error in the trailing CRC, so we must check
316 * gzerror before considering everything OK.
318 gzerror(gz_in, &errnum);
319 if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
320 cc_log("gzread error: %s (errno: %s)",
321 gzerror(gz_in, &errnum), strerror(errno));
327 tmp_unlink(tmp_name);
340 /* get perms right on the tmp file */
342 fchmod(fd_out, 0666 & ~mask);
346 /* the close can fail on NFS if out of space */
347 if (close(fd_out) == -1) {
348 cc_log("close error: %s", strerror(errno));
352 if (x_rename(tmp_name, dest) == -1) {
353 cc_log("rename error: %s", strerror(errno));
371 tmp_unlink(tmp_name);
376 /* Run copy_file() and, if successful, delete the source file. */
378 move_file(const char *src, const char *dest, int compress_level)
382 ret = copy_file(src, dest, compress_level);
390 * Like move_file(), but assumes that src is uncompressed and that src and dest
391 * are on the same file system.
394 move_uncompressed_file(const char *src, const char *dest, int compress_level)
396 if (compress_level > 0) {
397 return move_file(src, dest, compress_level);
399 return x_rename(src, dest);
403 /* test if a file is zlib compressed */
405 file_is_compressed(const char *filename)
409 f = fopen(filename, "rb");
414 /* test if file starts with 1F8B, which is zlib's
416 if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
425 /* make sure a directory exists */
427 create_dir(const char *dir)
430 if (stat(dir, &st) == 0) {
431 if (S_ISDIR(st.st_mode)) {
437 if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
443 /* Create directories leading to path. Returns 0 on success, otherwise -1. */
445 create_parent_dirs(const char *path)
449 char *parent = dirname(path);
451 if (stat(parent, &st) == 0) {
452 if (S_ISDIR(st.st_mode)) {
459 res = create_parent_dirs(parent);
461 res = mkdir(parent, 0777);
462 /* Have to handle the condition of the directory already existing because
463 * the file system could have changed in between calling stat and
464 * actually creating the directory. This can happen when there are
465 * multiple instances of ccache running and trying to create the same
466 * directory chain, which usually is the case when the cache root does
467 * not initially exist. As long as one of the processes creates the
468 * directories then our condition is satisfied and we avoid a race
471 if (res != 0 && errno == EEXIST) {
483 * Return a static string with the current hostname.
488 static char hostname[200] = "";
491 strcpy(hostname, "unknown");
493 gethostname(hostname, sizeof(hostname)-1);
495 hostname[sizeof(hostname)-1] = 0;
502 * Return a string to be passed to mkstemp to create a temporary file. Also
503 * tries to cope with NFS by adding the local hostname.
511 ret = format("%s.%u.XXXXXX", get_hostname(), (unsigned)getpid());
518 * Return the hash result as a hex string. Size -1 means don't include size
519 * suffix. Caller frees.
522 format_hash_as_string(const unsigned char *hash, int size)
528 for (i = 0; i < 16; i++) {
529 sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
532 sprintf(&ret[i*2], "-%u", size);
538 char const CACHEDIR_TAG[] =
539 "Signature: 8a477f597d28d172789f06886806bc55\n"
540 "# This file is a cache directory tag created by ccache.\n"
541 "# For information about cache directory tags, see:\n"
542 "# http://www.brynosaurus.com/cachedir/\n";
545 create_cachedirtag(const char *dir)
549 char *filename = format("%s/CACHEDIR.TAG", dir);
550 if (stat(filename, &st) == 0) {
551 if (S_ISREG(st.st_mode)) {
557 f = fopen(filename, "w");
561 if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
576 /* Construct a string according to a format. Caller frees. */
578 format(const char *format, ...)
583 va_start(ap, format);
584 if (vasprintf(&ptr, format, ap) == -1) {
585 fatal("Out of memory in format");
590 fatal("Internal error in format");
596 this is like strdup() but dies if the malloc fails
599 x_strdup(const char *s)
604 fatal("Out of memory in x_strdup");
610 this is like strndup() but dies if the malloc fails
613 x_strndup(const char *s, size_t n)
622 while (m < n && s[m]) {
634 fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
640 this is like malloc() but dies if the malloc fails
643 x_malloc(size_t size)
648 * malloc() may return NULL if size is zero, so always do this to make sure
649 * that the code handles it regardless of platform.
655 fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
660 /* This is like calloc() but dies if the allocation fails. */
662 x_calloc(size_t nmemb, size_t size)
665 if (nmemb * size == 0) {
667 * calloc() may return NULL if nmemb or size is 0, so always do this to
668 * make sure that the code handles it regardless of platform.
672 ret = calloc(nmemb, size);
674 fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
680 this is like realloc() but dies if the malloc fails
683 x_realloc(void *ptr, size_t size)
687 return x_malloc(size);
689 p2 = realloc(ptr, size);
691 fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
696 /* This is like unsetenv. */
697 void x_unsetenv(const char *name)
702 putenv(x_strdup(name)); /* Leak to environment. */
707 * Construct a string according to the format and store it in *ptr. The
708 * original *ptr is then freed.
711 reformat(char **ptr, const char *format, ...)
717 va_start(ap, format);
718 if (vasprintf(ptr, format, ap) == -1) {
719 fatal("Out of memory in reformat");
724 fatal("Out of memory in reformat");
732 * Recursive directory traversal. fn() is called on all entries in the tree.
735 traverse(const char *dir, void (*fn)(const char *, struct stat *))
745 while ((de = readdir(d))) {
749 if (str_eq(de->d_name, ".")) {
752 if (str_eq(de->d_name, "..")) {
756 if (strlen(de->d_name) == 0) {
760 fname = format("%s/%s", dir, de->d_name);
761 if (lstat(fname, &st)) {
762 if (errno != ENOENT) {
769 if (S_ISDIR(st.st_mode)) {
781 /* return the base name of a file - caller frees */
783 basename(const char *path)
786 p = strrchr(path, '/');
791 p = strrchr(path, '\\');
797 return x_strdup(path);
800 /* return the dir name of a file - caller frees */
802 dirname(const char *path)
812 p2 = strrchr(s, '\\');
813 if (!p || (p2 && p < p2)) {
829 * Return the file extension (including the dot) of a path as a pointer into
830 * path. If path has no file extension, the empty string and the end of path is
834 get_extension(const char *path)
836 size_t len = strlen(path);
839 for (p = &path[len - 1]; p >= path; --p) {
851 * Return a string containing the given path without the filename extension.
855 remove_extension(const char *path)
857 return x_strndup(path, strlen(path) - strlen(get_extension(path)));
860 /* return size on disk of a file */
862 file_size(struct stat *st)
865 return (st->st_size + 1023) & ~1023;
867 size_t size = st->st_blocks * 512;
868 if ((size_t)st->st_size > size) {
869 /* probably a broken stat() call ... */
870 size = (st->st_size + 1023) & ~1023;
876 /* Format a size as a human-readable string. Caller frees. */
878 format_human_readable_size(uint64_t v)
881 if (v >= 1000*1000*1000) {
882 s = format("%.1f GB", v/((double)(1000*1000*1000)));
883 } else if (v >= 1000*1000) {
884 s = format("%.1f MB", v/((double)(1000*1000)));
886 s = format("%.1f kB", v/((double)(1000)));
891 /* Format a size as a parsable string. Caller frees. */
893 format_parsable_size_with_suffix(uint64_t size)
896 if (size >= 1000*1000*1000) {
897 s = format("%.1fG", size / ((double)(1000*1000*1000)));
898 } else if (size >= 1000*1000) {
899 s = format("%.1fM", size / ((double)(1000*1000)));
900 } else if (size >= 1000) {
901 s = format("%.1fk", size / ((double)(1000)));
903 s = format("%u", (unsigned)size);
909 * Parse a "size value", i.e. a string that can end in k, M, G, T (10-based
910 * suffixes) or Ki, Mi, Gi, Ti (2-based suffixes). For backward compatibility,
911 * K is also recognized as a synonym of k.
914 parse_size_with_suffix(const char *str, uint64_t *size)
921 if (errno != 0 || x < 0 || p == str || *str == '\0') {
925 while (isspace(*p)) {
957 a sane realpath() function, trying to cope with stupid path limits and
961 x_realpath(const char *path)
963 long maxlen = path_max(path);
969 ret = x_malloc(maxlen);
972 p = realpath(path, ret);
973 #elif defined(_WIN32)
974 path_handle = CreateFile(
975 path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
976 FILE_ATTRIBUTE_NORMAL, NULL);
977 GetFinalPathNameByHandle(path_handle, ret, maxlen, FILE_NAME_NORMALIZED);
978 CloseHandle(path_handle);
979 p = ret+4;// strip the \\?\ from the file name
981 /* yes, there are such systems. This replacement relies on
982 the fact that when we call x_realpath we only care about symlinks */
984 int len = readlink(path, ret, maxlen-1);
1002 /* a getcwd that will returns an allocated buffer */
1006 unsigned size = 128;
1009 char *buffer = (char *)x_malloc(size);
1010 if (getcwd(buffer, size) == buffer) {
1014 if (errno != ERANGE) {
1015 cc_log("getcwd error: %d (%s)", errno, strerror(errno));
1022 #ifndef HAVE_STRTOK_R
1023 /* strtok_r replacement */
1025 strtok_r(char *str, const char *delim, char **saveptr)
1032 ret = strtok(str, delim);
1036 if ((len + 1) == (intptr_t) (save - str))
1045 * Create an empty temporary file. *fname will be reallocated and set to the
1046 * resulting filename. Returns an open file descriptor to the file.
1049 create_tmp_fd(char **fname)
1051 char *template = format("%s.%s", *fname, tmp_string());
1052 int fd = mkstemp(template);
1053 if (fd == -1 && errno == ENOENT) {
1054 if (create_parent_dirs(template) != 0) {
1055 fatal("Failed to create directory %s: %s",
1056 dirname(template), strerror(errno));
1058 reformat(&template, "%s.%s", *fname, tmp_string());
1059 fd = mkstemp(template);
1062 fatal("Failed to create file %s: %s", template, strerror(errno));
1070 * Create an empty temporary file. *fname will be reallocated and set to the
1071 * resulting filename. Returns an open FILE*.
1074 create_tmp_file(char **fname, const char *mode)
1076 FILE *file = fdopen(create_tmp_fd(fname), mode);
1078 fatal("Failed to create file %s: %s", *fname, strerror(errno));
1084 * Create an empty temporary file. *fname will be reallocated and set to the
1085 * resulting filename.
1088 create_empty_tmp_file(char **fname)
1090 close(create_tmp_fd(fname));
1094 * Return current user's home directory, or NULL if it can't be determined.
1097 get_home_directory(void)
1099 const char *p = getenv("HOME");
1104 p = getenv("APPDATA");
1109 #ifdef HAVE_GETPWUID
1111 struct passwd *pwd = getpwuid(getuid());
1121 * Get the current directory by reading $PWD. If $PWD isn't sane, gnu_getcwd()
1122 * is used. Caller frees.
1136 pwd = getenv("PWD");
1140 if (stat(pwd, &st_pwd) != 0) {
1143 if (stat(cwd, &st_cwd) != 0) {
1146 if (st_pwd.st_dev == st_cwd.st_dev && st_pwd.st_ino == st_cwd.st_ino) {
1148 return x_strdup(pwd);
1155 * Check whether s1 and s2 have the same executable name.
1158 same_executable_name(const char *s1, const char *s2)
1161 bool eq = strcasecmp(s1, s2) == 0;
1163 char *tmp = format("%s.exe", s2);
1164 eq = strcasecmp(s1, tmp) == 0;
1169 return str_eq(s1, s2);
1174 * Compute the length of the longest directory path that is common to two
1175 * paths. s1 is assumed to be the path to a directory.
1178 common_dir_prefix_length(const char *s1, const char *s2)
1180 const char *p1 = s1;
1181 const char *p2 = s2;
1183 while (*p1 && *p2 && *p1 == *p2) {
1187 while ((*p1 && *p1 != '/') || (*p2 && *p2 != '/')) {
1191 if (!*p1 && !*p2 && p2 == s2 + 1) {
1192 /* Special case for s1 and s2 both being "/". */
1199 * Compute a relative path from from (an absolute path to a directory) to to (a
1200 * path). Assumes that both from and to are well-formed and canonical. Caller
1204 get_relative_path(const char *from, const char *to)
1206 size_t common_prefix_len;
1211 assert(from && from[0] == '/');
1214 if (!*to || *to != '/') {
1215 return x_strdup(to);
1218 result = x_strdup("");
1219 common_prefix_len = common_dir_prefix_length(from, to);
1220 if (common_prefix_len > 0 || !str_eq(from, "/")) {
1221 for (p = from + common_prefix_len; *p; p++) {
1223 reformat(&result, "../%s", result);
1227 if (strlen(to) > common_prefix_len) {
1228 reformat(&result, "%s%s", result, to + common_prefix_len + 1);
1230 i = strlen(result) - 1;
1231 while (i >= 0 && result[i] == '/') {
1235 if (str_eq(result, "")) {
1237 result = x_strdup(".");
1243 * Return whether path is absolute.
1246 is_absolute_path(const char *path)
1249 return path[0] && path[1] == ':';
1251 return path[0] == '/';
1256 * Return whether the argument is a full path.
1259 is_full_path(const char *path)
1261 if (strchr(path, '/'))
1264 if (strchr(path, '\\'))
1271 * Update the modification time of a file in the cache to save it from LRU
1275 update_mtime(const char *path)
1285 * Rename oldpath to newpath (deleting newpath).
1288 x_rename(const char *oldpath, const char *newpath)
1291 /* Windows' rename() refuses to overwrite an existing file. */
1292 unlink(newpath); /* not x_unlink, as x_unlink calls x_rename */
1294 return rename(oldpath, newpath);
1298 * Remove path, NFS hazardous. Use only for temporary files that will not exist
1299 * on other systems. That is, the path should include tmp_string().
1302 tmp_unlink(const char *path)
1304 cc_log("Unlink %s", path);
1305 return unlink(path);
1309 * Remove path, NFS safe.
1312 x_unlink(const char *path)
1315 * If path is on an NFS share, unlink isn't atomic, so we rename to a temp
1316 * file. We don't care if the temp file is trashed, so it's always safe to
1319 char *tmp_name = format("%s.rm.%s", path, tmp_string());
1321 cc_log("Unlink %s via %s", path, tmp_name);
1322 if (x_rename(path, tmp_name) == -1) {
1326 if (unlink(tmp_name) == -1) {
1327 /* If it was released in a race, that's OK. */
1328 if (errno != ENOENT) {
1338 /* Like readlink() but returns the string or NULL on failure. Caller frees. */
1340 x_readlink(const char *path)
1342 long maxlen = path_max(path);
1346 buf = x_malloc(maxlen);
1347 len = readlink(path, buf, maxlen-1);
1358 * Reads the content of a file. Size hint 0 means no hint. Returns true on
1359 * success, otherwise false.
1362 read_file(const char *path, size_t size_hint, char **data, size_t *size)
1365 size_t pos = 0, allocated;
1367 if (size_hint == 0) {
1369 if (stat(path, &st) == 0) {
1370 size_hint = st.st_size;
1373 size_hint = (size_hint < 1024) ? 1024 : size_hint;
1375 fd = open(path, O_RDONLY | O_BINARY);
1379 allocated = size_hint;
1380 *data = x_malloc(allocated);
1382 if (pos > allocated / 2) {
1384 *data = x_realloc(*data, allocated);
1386 ret = read(fd, *data + pos, allocated - pos);
1387 if (ret == 0 || (ret == -1 && errno != EINTR)) {
1396 cc_log("Failed reading %s", path);
1407 * Return the content (with NUL termination) of a text file, or NULL on error.
1408 * Caller frees. Size hint 0 means no hint.
1411 read_text_file(const char *path, size_t size_hint)
1416 if (read_file(path, size_hint, &data, &size)) {
1417 data = x_realloc(data, size + 1);
1426 expand_variable(const char **str, char **result, char **errmsg)
1433 assert(**str == '$');
1442 while (isalnum(*q) || *q == '_') {
1447 *errmsg = format("syntax error: missing '}' after \"%s\"", p);
1453 /* Special case: don't consider a single $ the start of a variable. */
1454 reformat(result, "%s$", *result);
1458 name = x_strndup(p, q - p);
1459 value = getenv(name);
1461 *errmsg = format("environment variable \"%s\" not set", name);
1465 reformat(result, "%s%s", *result, value);
1475 * Substitute all instances of $VAR or ${VAR}, where VAR is an environment
1476 * variable, in a string. Caller frees. If one of the environment variables
1477 * doesn't exist, NULL will be returned and *errmsg will be an appropriate
1478 * error message (caller frees).
1481 subst_env_in_string(const char *str, char **errmsg)
1483 const char *p; /* Interval start. */
1484 const char *q; /* Interval end. */
1490 result = x_strdup("");
1493 for (q = str; *q; ++q) {
1495 reformat(&result, "%s%.*s", result, (int)(q - p), p);
1496 if (!expand_variable(&q, &result, errmsg)) {
1503 reformat(&result, "%s%.*s", result, (int)(q - p), p);