Path: blob/main/contrib/llvm-project/llvm/lib/Support/Caching.cpp
35233 views
//===-Caching.cpp - LLVM Local File Cache ---------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the localCache function, which simplifies creating,9// adding to, and querying a local file system cache. localCache takes care of10// periodically pruning older files from the cache using a CachePruningPolicy.11//12//===----------------------------------------------------------------------===//1314#include "llvm/Support/Caching.h"15#include "llvm/Support/Errc.h"16#include "llvm/Support/FileSystem.h"17#include "llvm/Support/MemoryBuffer.h"18#include "llvm/Support/Path.h"1920#if !defined(_MSC_VER) && !defined(__MINGW32__)21#include <unistd.h>22#else23#include <io.h>24#endif2526using namespace llvm;2728Expected<FileCache> llvm::localCache(const Twine &CacheNameRef,29const Twine &TempFilePrefixRef,30const Twine &CacheDirectoryPathRef,31AddBufferFn AddBuffer) {3233// Create local copies which are safely captured-by-copy in lambdas34SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath;35CacheNameRef.toVector(CacheName);36TempFilePrefixRef.toVector(TempFilePrefix);37CacheDirectoryPathRef.toVector(CacheDirectoryPath);3839return [=](unsigned Task, StringRef Key,40const Twine &ModuleName) -> Expected<AddStreamFn> {41// This choice of file name allows the cache to be pruned (see pruneCache()42// in include/llvm/Support/CachePruning.h).43SmallString<64> EntryPath;44sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);45// First, see if we have a cache hit.46SmallString<64> ResultPath;47Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(48Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);49std::error_code EC;50if (FDOrErr) {51ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =52MemoryBuffer::getOpenFile(*FDOrErr, EntryPath,53/*FileSize=*/-1,54/*RequiresNullTerminator=*/false);55sys::fs::closeFile(*FDOrErr);56if (MBOrErr) {57AddBuffer(Task, ModuleName, std::move(*MBOrErr));58return AddStreamFn();59}60EC = MBOrErr.getError();61} else {62EC = errorToErrorCode(FDOrErr.takeError());63}6465// On Windows we can fail to open a cache file with a permission denied66// error. This generally means that another process has requested to delete67// the file while it is still open, but it could also mean that another68// process has opened the file without the sharing permissions we need.69// Since the file is probably being deleted we handle it in the same way as70// if the file did not exist at all.71if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied)72return createStringError(EC, Twine("Failed to open cache file ") +73EntryPath + ": " + EC.message() + "\n");7475// This file stream is responsible for commiting the resulting file to the76// cache and calling AddBuffer to add it to the link.77struct CacheStream : CachedFileStream {78AddBufferFn AddBuffer;79sys::fs::TempFile TempFile;80std::string ModuleName;81unsigned Task;8283CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,84sys::fs::TempFile TempFile, std::string EntryPath,85std::string ModuleName, unsigned Task)86: CachedFileStream(std::move(OS), std::move(EntryPath)),87AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)),88ModuleName(ModuleName), Task(Task) {}8990~CacheStream() {91// TODO: Manually commit rather than using non-trivial destructor,92// allowing to replace report_fatal_errors with a return Error.9394// Make sure the stream is closed before committing it.95OS.reset();9697// Open the file first to avoid racing with a cache pruner.98ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =99MemoryBuffer::getOpenFile(100sys::fs::convertFDToNativeFile(TempFile.FD), ObjectPathName,101/*FileSize=*/-1, /*RequiresNullTerminator=*/false);102if (!MBOrErr)103report_fatal_error(Twine("Failed to open new cache file ") +104TempFile.TmpName + ": " +105MBOrErr.getError().message() + "\n");106107// On POSIX systems, this will atomically replace the destination if108// it already exists. We try to emulate this on Windows, but this may109// fail with a permission denied error (for example, if the destination110// is currently opened by another process that does not give us the111// sharing permissions we need). Since the existing file should be112// semantically equivalent to the one we are trying to write, we give113// AddBuffer a copy of the bytes we wrote in that case. We do this114// instead of just using the existing file, because the pruner might115// delete the file before we get a chance to use it.116Error E = TempFile.keep(ObjectPathName);117E = handleErrors(std::move(E), [&](const ECError &E) -> Error {118std::error_code EC = E.convertToErrorCode();119if (EC != errc::permission_denied)120return errorCodeToError(EC);121122auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),123ObjectPathName);124MBOrErr = std::move(MBCopy);125126// FIXME: should we consume the discard error?127consumeError(TempFile.discard());128129return Error::success();130});131132if (E)133report_fatal_error(Twine("Failed to rename temporary file ") +134TempFile.TmpName + " to " + ObjectPathName + ": " +135toString(std::move(E)) + "\n");136137AddBuffer(Task, ModuleName, std::move(*MBOrErr));138}139};140141return [=](size_t Task, const Twine &ModuleName)142-> Expected<std::unique_ptr<CachedFileStream>> {143// Create the cache directory if not already done. Doing this lazily144// ensures the filesystem isn't mutated until the cache is.145if (std::error_code EC = sys::fs::create_directories(146CacheDirectoryPath, /*IgnoreExisting=*/true))147return createStringError(EC, Twine("can't create cache directory ") +148CacheDirectoryPath + ": " +149EC.message());150151// Write to a temporary to avoid race condition152SmallString<64> TempFilenameModel;153sys::path::append(TempFilenameModel, CacheDirectoryPath,154TempFilePrefix + "-%%%%%%.tmp.o");155Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create(156TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);157if (!Temp)158return createStringError(errc::io_error,159toString(Temp.takeError()) + ": " + CacheName +160": Can't get a temporary file");161162// This CacheStream will move the temporary file into the cache when done.163return std::make_unique<CacheStream>(164std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),165AddBuffer, std::move(*Temp), std::string(EntryPath), ModuleName.str(),166Task);167};168};169}170171172