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(const Twine &CacheNameRef, 30 const Twine &TempFilePrefixRef, 31 const Twine &CacheDirectoryPathRef, 32 AddBufferFn AddBuffer) { 33 34 // Create local copies which are safely captured-by-copy in lambdas 35 SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath; 36 CacheNameRef.toVector(CacheName); 37 TempFilePrefixRef.toVector(TempFilePrefix); 38 CacheDirectoryPathRef.toVector(CacheDirectoryPath); 39 40 auto Func = [=](unsigned Task, StringRef Key, 41 const Twine &ModuleName) -> Expected<AddStreamFn> { 42 // This choice of file name allows the cache to be pruned (see pruneCache() 43 // in include/llvm/Support/CachePruning.h). 44 SmallString<64> EntryPath; 45 sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key); 46 // First, see if we have a cache hit. 47 SmallString<64> ResultPath; 48 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead( 49 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath); 50 std::error_code EC; 51 if (FDOrErr) { 52 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 53 MemoryBuffer::getOpenFile(*FDOrErr, EntryPath, 54 /*FileSize=*/-1, 55 /*RequiresNullTerminator=*/false); 56 sys::fs::closeFile(*FDOrErr); 57 if (MBOrErr) { 58 AddBuffer(Task, ModuleName, std::move(*MBOrErr)); 59 return AddStreamFn(); 60 } 61 EC = MBOrErr.getError(); 62 } else { 63 EC = errorToErrorCode(FDOrErr.takeError()); 64 } 65 66 // On Windows we can fail to open a cache file with a permission denied 67 // error. This generally means that another process has requested to delete 68 // the file while it is still open, but it could also mean that another 69 // process has opened the file without the sharing permissions we need. 70 // Since the file is probably being deleted we handle it in the same way as 71 // if the file did not exist at all. 72 if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied) 73 return createStringError(EC, Twine("Failed to open cache file ") + 74 EntryPath + ": " + EC.message() + "\n"); 75 76 // This file stream is responsible for commiting the resulting file to the 77 // cache and calling AddBuffer to add it to the link. 78 struct CacheStream : CachedFileStream { 79 AddBufferFn AddBuffer; 80 sys::fs::TempFile TempFile; 81 std::string ModuleName; 82 unsigned Task; 83 84 CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer, 85 sys::fs::TempFile TempFile, std::string EntryPath, 86 std::string ModuleName, unsigned Task) 87 : CachedFileStream(std::move(OS), std::move(EntryPath)), 88 AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)), 89 ModuleName(ModuleName), Task(Task) {} 90 91 Error commit() override { 92 Error E = CachedFileStream::commit(); 93 if (E) 94 return E; 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), ObjectPathName, 103 /*FileSize=*/-1, /*RequiresNullTerminator=*/false); 104 if (!MBOrErr) { 105 std::error_code EC = MBOrErr.getError(); 106 return createStringError(EC, Twine("Failed to open new cache file ") + 107 TempFile.TmpName + ": " + 108 EC.message() + "\n"); 109 } 110 111 // On POSIX systems, this will atomically replace the destination if 112 // it already exists. We try to emulate this on Windows, but this may 113 // fail with a permission denied error (for example, if the destination 114 // is currently opened by another process that does not give us the 115 // sharing permissions we need). Since the existing file should be 116 // semantically equivalent to the one we are trying to write, we give 117 // AddBuffer a copy of the bytes we wrote in that case. We do this 118 // instead of just using the existing file, because the pruner might 119 // delete the file before we get a chance to use it. 120 E = TempFile.keep(ObjectPathName); 121 E = handleErrors(std::move(E), [&](const ECError &E) -> Error { 122 std::error_code EC = E.convertToErrorCode(); 123 if (EC != errc::permission_denied) 124 return createStringError( 125 EC, Twine("Failed to rename temporary file ") + 126 TempFile.TmpName + " to " + ObjectPathName + ": " + 127 EC.message() + "\n"); 128 129 auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(), 130 ObjectPathName); 131 MBOrErr = std::move(MBCopy); 132 133 // FIXME: should we consume the discard error? 134 consumeError(TempFile.discard()); 135 136 return Error::success(); 137 }); 138 139 if (E) 140 return E; 141 142 AddBuffer(Task, ModuleName, std::move(*MBOrErr)); 143 return Error::success(); 144 } 145 }; 146 147 return [=](size_t Task, const Twine &ModuleName) 148 -> Expected<std::unique_ptr<CachedFileStream>> { 149 // Create the cache directory if not already done. Doing this lazily 150 // ensures the filesystem isn't mutated until the cache is. 151 if (std::error_code EC = sys::fs::create_directories( 152 CacheDirectoryPath, /*IgnoreExisting=*/true)) 153 return createStringError(EC, Twine("can't create cache directory ") + 154 CacheDirectoryPath + ": " + 155 EC.message()); 156 157 // Write to a temporary to avoid race condition 158 SmallString<64> TempFilenameModel; 159 sys::path::append(TempFilenameModel, CacheDirectoryPath, 160 TempFilePrefix + "-%%%%%%.tmp.o"); 161 Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create( 162 TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write); 163 if (!Temp) 164 return createStringError(errc::io_error, 165 toString(Temp.takeError()) + ": " + CacheName + 166 ": Can't get a temporary file"); 167 168 // This CacheStream will move the temporary file into the cache when done. 169 return std::make_unique<CacheStream>( 170 std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false), 171 AddBuffer, std::move(*Temp), std::string(EntryPath), ModuleName.str(), 172 Task); 173 }; 174 }; 175 return FileCache(Func, CacheDirectoryPathRef.str()); 176 } 177