Caching.cpp 7.2 KB

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