Caching.cpp 6.4 KB

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