1 //===-Caching.cpp - LLVM Local File Cache ---------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the localCache function, which simplifies creating, 10 // adding to, and querying a local file system cache. localCache takes care of 11 // periodically pruning older files from the cache using a CachePruningPolicy. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Support/Caching.h" 16 #include "llvm/Support/Errc.h" 17 #include "llvm/Support/FileSystem.h" 18 #include "llvm/Support/MemoryBuffer.h" 19 #include "llvm/Support/Path.h" 20 21 #if !defined(_MSC_VER) && !defined(__MINGW32__) 22 #include <unistd.h> 23 #else 24 #include <io.h> 25 #endif 26 27 using namespace llvm; 28 29 Expected<FileCache> llvm::localCache(Twine CacheNameRef, 30 Twine TempFilePrefixRef, 31 Twine CacheDirectoryPathRef, 32 AddBufferFn AddBuffer) { 33 if (std::error_code EC = sys::fs::create_directories(CacheDirectoryPathRef)) 34 return errorCodeToError(EC); 35 36 // Create local copies which are safely captured-by-copy in lambdas 37 SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath; 38 CacheNameRef.toVector(CacheName); 39 TempFilePrefixRef.toVector(TempFilePrefix); 40 CacheDirectoryPathRef.toVector(CacheDirectoryPath); 41 42 return [=](unsigned Task, StringRef Key) -> Expected<AddStreamFn> { 43 // This choice of file name allows the cache to be pruned (see pruneCache() 44 // in include/llvm/Support/CachePruning.h). 45 SmallString<64> EntryPath; 46 sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key); 47 // First, see if we have a cache hit. 48 SmallString<64> ResultPath; 49 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead( 50 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath); 51 std::error_code EC; 52 if (FDOrErr) { 53 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 54 MemoryBuffer::getOpenFile(*FDOrErr, EntryPath, 55 /*FileSize=*/-1, 56 /*RequiresNullTerminator=*/false); 57 sys::fs::closeFile(*FDOrErr); 58 if (MBOrErr) { 59 AddBuffer(Task, std::move(*MBOrErr)); 60 return AddStreamFn(); 61 } 62 EC = MBOrErr.getError(); 63 } else { 64 EC = errorToErrorCode(FDOrErr.takeError()); 65 } 66 67 // On Windows we can fail to open a cache file with a permission denied 68 // error. This generally means that another process has requested to delete 69 // the file while it is still open, but it could also mean that another 70 // process has opened the file without the sharing permissions we need. 71 // Since the file is probably being deleted we handle it in the same way as 72 // if the file did not exist at all. 73 if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied) 74 return createStringError(EC, Twine("Failed to open cache file ") + 75 EntryPath + ": " + EC.message() + "\n"); 76 77 // This file stream is responsible for commiting the resulting file to the 78 // cache and calling AddBuffer to add it to the link. 79 struct CacheStream : CachedFileStream { 80 AddBufferFn AddBuffer; 81 sys::fs::TempFile TempFile; 82 std::string EntryPath; 83 unsigned Task; 84 85 CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer, 86 sys::fs::TempFile TempFile, std::string EntryPath, 87 unsigned Task) 88 : CachedFileStream(std::move(OS)), AddBuffer(std::move(AddBuffer)), 89 TempFile(std::move(TempFile)), EntryPath(std::move(EntryPath)), 90 Task(Task) {} 91 92 ~CacheStream() { 93 // TODO: Manually commit rather than using non-trivial destructor, 94 // allowing to replace report_fatal_errors with a return Error. 95 96 // Make sure the stream is closed before committing it. 97 OS.reset(); 98 99 // Open the file first to avoid racing with a cache pruner. 100 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 101 MemoryBuffer::getOpenFile( 102 sys::fs::convertFDToNativeFile(TempFile.FD), TempFile.TmpName, 103 /*FileSize=*/-1, /*RequiresNullTerminator=*/false); 104 if (!MBOrErr) 105 report_fatal_error(Twine("Failed to open new cache file ") + 106 TempFile.TmpName + ": " + 107 MBOrErr.getError().message() + "\n"); 108 109 // On POSIX systems, this will atomically replace the destination if 110 // it already exists. We try to emulate this on Windows, but this may 111 // fail with a permission denied error (for example, if the destination 112 // is currently opened by another process that does not give us the 113 // sharing permissions we need). Since the existing file should be 114 // semantically equivalent to the one we are trying to write, we give 115 // AddBuffer a copy of the bytes we wrote in that case. We do this 116 // instead of just using the existing file, because the pruner might 117 // delete the file before we get a chance to use it. 118 Error E = TempFile.keep(EntryPath); 119 E = handleErrors(std::move(E), [&](const ECError &E) -> Error { 120 std::error_code EC = E.convertToErrorCode(); 121 if (EC != errc::permission_denied) 122 return errorCodeToError(EC); 123 124 auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(), 125 EntryPath); 126 MBOrErr = std::move(MBCopy); 127 128 // FIXME: should we consume the discard error? 129 consumeError(TempFile.discard()); 130 131 return Error::success(); 132 }); 133 134 if (E) 135 report_fatal_error(Twine("Failed to rename temporary file ") + 136 TempFile.TmpName + " to " + EntryPath + ": " + 137 toString(std::move(E)) + "\n"); 138 139 AddBuffer(Task, std::move(*MBOrErr)); 140 } 141 }; 142 143 return [=](size_t Task) -> Expected<std::unique_ptr<CachedFileStream>> { 144 // Write to a temporary to avoid race condition 145 SmallString<64> TempFilenameModel; 146 sys::path::append(TempFilenameModel, CacheDirectoryPath, 147 TempFilePrefix + "-%%%%%%.tmp.o"); 148 Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create( 149 TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write); 150 if (!Temp) 151 return createStringError(errc::io_error, 152 toString(Temp.takeError()) + ": " + CacheName + 153 ": Can't get a temporary file"); 154 155 // This CacheStream will move the temporary file into the cache when done. 156 return std::make_unique<CacheStream>( 157 std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false), 158 AddBuffer, std::move(*Temp), std::string(EntryPath.str()), Task); 159 }; 160 }; 161 } 162