Caching.cpp 7.5 KB

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