| 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 "llvm/Support/Windows/WindowsSupport.h" |
| 25 | #include <io.h> |
| 26 | #endif |
| 27 | |
| 28 | using namespace llvm; |
| 29 | |
| 30 | Expected<FileCache> llvm::localCache(const Twine &CacheNameRef, |
| 31 | const Twine &TempFilePrefixRef, |
| 32 | const Twine &CacheDirectoryPathRef, |
| 33 | AddBufferFn AddBuffer, bool CacheRename) { |
| 34 | |
| 35 | // Create local copies which are safely captured-by-copy in lambdas |
| 36 | SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath; |
| 37 | CacheNameRef.toVector(Out&: CacheName); |
| 38 | TempFilePrefixRef.toVector(Out&: TempFilePrefix); |
| 39 | CacheDirectoryPathRef.toVector(Out&: CacheDirectoryPath); |
| 40 | |
| 41 | auto Func = [=](unsigned Task, StringRef Key, |
| 42 | const Twine &ModuleName) -> 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(path&: EntryPath, a: CacheDirectoryPath, b: "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 | Name: Twine(EntryPath), Flags: sys::fs::OF_UpdateAtime, RealPath: &ResultPath); |
| 51 | std::error_code EC; |
| 52 | if (FDOrErr) { |
| 53 | ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = |
| 54 | MemoryBuffer::getOpenFile(FD: *FDOrErr, Filename: EntryPath, |
| 55 | /*FileSize=*/-1, |
| 56 | /*RequiresNullTerminator=*/false); |
| 57 | sys::fs::closeFile(F&: *FDOrErr); |
| 58 | if (MBOrErr) { |
| 59 | AddBuffer(Task, ModuleName, std::move(*MBOrErr)); |
| 60 | return AddStreamFn(); |
| 61 | } |
| 62 | EC = MBOrErr.getError(); |
| 63 | } else { |
| 64 | EC = errorToErrorCode(Err: 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, S: 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 ModuleName; |
| 83 | unsigned Task; |
| 84 | |
| 85 | CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer, |
| 86 | sys::fs::TempFile TempFile, std::string EntryPath, |
| 87 | std::string ModuleName, unsigned Task) |
| 88 | : CachedFileStream(std::move(OS), std::move(EntryPath)), |
| 89 | AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)), |
| 90 | ModuleName(ModuleName), Task(Task) {} |
| 91 | |
| 92 | Error commit() override { |
| 93 | Error E = CachedFileStream::commit(); |
| 94 | if (E) |
| 95 | return E; |
| 96 | |
| 97 | // Make sure the stream is closed before committing it. |
| 98 | OS.reset(); |
| 99 | |
| 100 | // Open the file first to avoid racing with a cache pruner. |
| 101 | ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = |
| 102 | MemoryBuffer::getOpenFile( |
| 103 | FD: sys::fs::convertFDToNativeFile(FD: TempFile.FD), Filename: ObjectPathName, |
| 104 | /*FileSize=*/-1, /*RequiresNullTerminator=*/false); |
| 105 | if (!MBOrErr) { |
| 106 | std::error_code EC = MBOrErr.getError(); |
| 107 | return createStringError(EC, S: Twine("Failed to open new cache file " ) + |
| 108 | TempFile.TmpName + ": " + |
| 109 | EC.message() + "\n" ); |
| 110 | } |
| 111 | |
| 112 | // On POSIX systems, this will atomically replace the destination if |
| 113 | // it already exists. We try to emulate this on Windows, but this may |
| 114 | // fail with a permission denied error (for example, if the destination |
| 115 | // is currently opened by another process that does not give us the |
| 116 | // sharing permissions we need). Since the existing file should be |
| 117 | // semantically equivalent to the one we are trying to write, we give |
| 118 | // AddBuffer a copy of the bytes we wrote in that case. We do this |
| 119 | // instead of just using the existing file, because the pruner might |
| 120 | // delete the file before we get a chance to use it. |
| 121 | E = TempFile.keep(Name: ObjectPathName); |
| 122 | E = handleErrors(E: std::move(E), Hs: [&](const ECError &E) -> Error { |
| 123 | std::error_code EC = E.convertToErrorCode(); |
| 124 | if (EC != errc::permission_denied) |
| 125 | return createStringError( |
| 126 | EC, S: Twine("Failed to rename temporary file " ) + |
| 127 | TempFile.TmpName + " to " + ObjectPathName + ": " + |
| 128 | EC.message() + "\n" ); |
| 129 | |
| 130 | auto MBCopy = MemoryBuffer::getMemBufferCopy(InputData: (*MBOrErr)->getBuffer(), |
| 131 | BufferName: ObjectPathName); |
| 132 | MBOrErr = std::move(MBCopy); |
| 133 | |
| 134 | // FIXME: should we consume the discard error? |
| 135 | consumeError(Err: TempFile.discard()); |
| 136 | |
| 137 | return Error::success(); |
| 138 | }); |
| 139 | |
| 140 | if (E) |
| 141 | return E; |
| 142 | |
| 143 | AddBuffer(Task, ModuleName, std::move(*MBOrErr)); |
| 144 | return Error::success(); |
| 145 | } |
| 146 | }; |
| 147 | |
| 148 | // This class is responsible for renaming/moving existing file into a |
| 149 | // cache directory. The path for an input file is passed through a string |
| 150 | // stream. |
| 151 | struct MoveFileToCache : CachedFileStream { |
| 152 | AddBufferFn AddBuffer; |
| 153 | std::string ModuleName; |
| 154 | size_t Task; |
| 155 | StringRef FilePath; |
| 156 | |
| 157 | MoveFileToCache(AddBufferFn AddBuffer, std::string EntryPath, |
| 158 | std::string ModuleID, size_t Task) |
| 159 | : CachedFileStream({}, std::move(EntryPath)), |
| 160 | AddBuffer(std::move(AddBuffer)), ModuleName(ModuleID), Task(Task) {} |
| 161 | virtual ~MoveFileToCache() = default; |
| 162 | |
| 163 | virtual Error commit(std::unique_ptr<MemoryBuffer> MemBuf) override { |
| 164 | Error E = CachedFileStream::commit(); |
| 165 | if (E) |
| 166 | return E; |
| 167 | |
| 168 | FilePath = MemBuf->getBufferIdentifier(); |
| 169 | assert(!FilePath.empty() && "File path is empty." ); |
| 170 | |
| 171 | // Rename/move native object file into cache directory, if they are |
| 172 | // located the same device/logical drive, otherwise we use a copy. |
| 173 | std::error_code EC = sys::fs::rename(from: FilePath, to: ObjectPathName); |
| 174 | #ifdef _WIN32 |
| 175 | if (EC == |
| 176 | std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) |
| 177 | #else |
| 178 | if (EC == std::make_error_code(e: std::errc::cross_device_link)) |
| 179 | #endif |
| 180 | EC = sys::fs::copy_file(From: FilePath, To: ObjectPathName); |
| 181 | if (EC) |
| 182 | return createStringError(EC, S: Twine("Failed to rename or copy file " ) + |
| 183 | FilePath + " to " + ObjectPathName + |
| 184 | ": " + EC.message() + "\n" ); |
| 185 | |
| 186 | AddBuffer(Task, ModuleName, std::move(MemBuf)); |
| 187 | |
| 188 | return Error::success(); |
| 189 | } |
| 190 | }; |
| 191 | |
| 192 | return [=](size_t Task, const Twine &ModuleName) |
| 193 | -> Expected<std::unique_ptr<CachedFileStream>> { |
| 194 | // Create the cache directory if not already done. Doing this lazily |
| 195 | // ensures the filesystem isn't mutated until the cache is. |
| 196 | if (std::error_code EC = sys::fs::create_directories( |
| 197 | path: CacheDirectoryPath, /*IgnoreExisting=*/true)) |
| 198 | return createStringError(EC, S: Twine("can't create cache directory " ) + |
| 199 | CacheDirectoryPath + ": " + |
| 200 | EC.message()); |
| 201 | // MoveFileToChache class will rename/move the file into the cache on |
| 202 | // destruction. |
| 203 | if (CacheRename) { |
| 204 | return std::make_unique<MoveFileToCache>( |
| 205 | args: AddBuffer, args: std::string(EntryPath.str()), args: ModuleName.str(), args&: Task); |
| 206 | } |
| 207 | |
| 208 | // Write to a temporary to avoid race condition |
| 209 | SmallString<64> TempFilenameModel; |
| 210 | sys::path::append(path&: TempFilenameModel, a: CacheDirectoryPath, |
| 211 | b: TempFilePrefix + "-%%%%%%.tmp.o" ); |
| 212 | Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create( |
| 213 | Model: TempFilenameModel, Mode: sys::fs::owner_read | sys::fs::owner_write); |
| 214 | if (!Temp) |
| 215 | return createStringError(EC: errc::io_error, |
| 216 | S: toString(E: Temp.takeError()) + ": " + CacheName + |
| 217 | ": Can't get a temporary file" ); |
| 218 | |
| 219 | // This CacheStream will move the temporary file into the cache when done. |
| 220 | return std::make_unique<CacheStream>( |
| 221 | args: std::make_unique<raw_fd_ostream>(args&: Temp->FD, /* ShouldClose */ args: false), |
| 222 | args: AddBuffer, args: std::move(*Temp), args: std::string(EntryPath), args: ModuleName.str(), |
| 223 | args&: Task); |
| 224 | }; |
| 225 | }; |
| 226 | return FileCache(Func, CacheDirectoryPathRef.str()); |
| 227 | } |
| 228 | |