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