FileOutputBuffer.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
  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. // Utility for creating a in-memory buffer that will be written to a file.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/FileOutputBuffer.h"
  13. #include "llvm/Support/Errc.h"
  14. #include "llvm/Support/FileSystem.h"
  15. #include "llvm/Support/Memory.h"
  16. #include <system_error>
  17. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  18. #include <unistd.h>
  19. #else
  20. #include <io.h>
  21. #endif
  22. using namespace llvm;
  23. using namespace llvm::sys;
  24. namespace {
  25. // A FileOutputBuffer which creates a temporary file in the same directory
  26. // as the final output file. The final output file is atomically replaced
  27. // with the temporary file on commit().
  28. class OnDiskBuffer : public FileOutputBuffer {
  29. public:
  30. OnDiskBuffer(StringRef Path, fs::TempFile Temp, fs::mapped_file_region Buf)
  31. : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {}
  32. uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.data(); }
  33. uint8_t *getBufferEnd() const override {
  34. return (uint8_t *)Buffer.data() + Buffer.size();
  35. }
  36. size_t getBufferSize() const override { return Buffer.size(); }
  37. Error commit() override {
  38. // Unmap buffer, letting OS flush dirty pages to file on disk.
  39. Buffer.unmap();
  40. // Atomically replace the existing file with the new one.
  41. return Temp.keep(FinalPath);
  42. }
  43. ~OnDiskBuffer() override {
  44. // Close the mapping before deleting the temp file, so that the removal
  45. // succeeds.
  46. Buffer.unmap();
  47. consumeError(Temp.discard());
  48. }
  49. void discard() override {
  50. // Delete the temp file if it still was open, but keeping the mapping
  51. // active.
  52. consumeError(Temp.discard());
  53. }
  54. private:
  55. fs::mapped_file_region Buffer;
  56. fs::TempFile Temp;
  57. };
  58. // A FileOutputBuffer which keeps data in memory and writes to the final
  59. // output file on commit(). This is used only when we cannot use OnDiskBuffer.
  60. class InMemoryBuffer : public FileOutputBuffer {
  61. public:
  62. InMemoryBuffer(StringRef Path, MemoryBlock Buf, std::size_t BufSize,
  63. unsigned Mode)
  64. : FileOutputBuffer(Path), Buffer(Buf), BufferSize(BufSize),
  65. Mode(Mode) {}
  66. uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }
  67. uint8_t *getBufferEnd() const override {
  68. return (uint8_t *)Buffer.base() + BufferSize;
  69. }
  70. size_t getBufferSize() const override { return BufferSize; }
  71. Error commit() override {
  72. if (FinalPath == "-") {
  73. llvm::outs() << StringRef((const char *)Buffer.base(), BufferSize);
  74. llvm::outs().flush();
  75. return Error::success();
  76. }
  77. using namespace sys::fs;
  78. int FD;
  79. std::error_code EC;
  80. if (auto EC =
  81. openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode))
  82. return errorCodeToError(EC);
  83. raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true);
  84. OS << StringRef((const char *)Buffer.base(), BufferSize);
  85. return Error::success();
  86. }
  87. private:
  88. // Buffer may actually contain a larger memory block than BufferSize
  89. OwningMemoryBlock Buffer;
  90. size_t BufferSize;
  91. unsigned Mode;
  92. };
  93. } // namespace
  94. static Expected<std::unique_ptr<InMemoryBuffer>>
  95. createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {
  96. std::error_code EC;
  97. MemoryBlock MB = Memory::allocateMappedMemory(
  98. Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
  99. if (EC)
  100. return errorCodeToError(EC);
  101. return std::make_unique<InMemoryBuffer>(Path, MB, Size, Mode);
  102. }
  103. static Expected<std::unique_ptr<FileOutputBuffer>>
  104. createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {
  105. Expected<fs::TempFile> FileOrErr =
  106. fs::TempFile::create(Path + ".tmp%%%%%%%", Mode);
  107. if (!FileOrErr)
  108. return FileOrErr.takeError();
  109. fs::TempFile File = std::move(*FileOrErr);
  110. if (auto EC = fs::resize_file_before_mapping_readwrite(File.FD, Size)) {
  111. consumeError(File.discard());
  112. return errorCodeToError(EC);
  113. }
  114. // Mmap it.
  115. std::error_code EC;
  116. fs::mapped_file_region MappedFile =
  117. fs::mapped_file_region(fs::convertFDToNativeFile(File.FD),
  118. fs::mapped_file_region::readwrite, Size, 0, EC);
  119. // mmap(2) can fail if the underlying filesystem does not support it.
  120. // If that happens, we fall back to in-memory buffer as the last resort.
  121. if (EC) {
  122. consumeError(File.discard());
  123. return createInMemoryBuffer(Path, Size, Mode);
  124. }
  125. return std::make_unique<OnDiskBuffer>(Path, std::move(File),
  126. std::move(MappedFile));
  127. }
  128. // Create an instance of FileOutputBuffer.
  129. Expected<std::unique_ptr<FileOutputBuffer>>
  130. FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {
  131. // Handle "-" as stdout just like llvm::raw_ostream does.
  132. if (Path == "-")
  133. return createInMemoryBuffer("-", Size, /*Mode=*/0);
  134. unsigned Mode = fs::all_read | fs::all_write;
  135. if (Flags & F_executable)
  136. Mode |= fs::all_exe;
  137. // If Size is zero, don't use mmap which will fail with EINVAL.
  138. if (Size == 0)
  139. return createInMemoryBuffer(Path, Size, Mode);
  140. fs::file_status Stat;
  141. fs::status(Path, Stat);
  142. // Usually, we want to create OnDiskBuffer to create a temporary file in
  143. // the same directory as the destination file and atomically replaces it
  144. // by rename(2).
  145. //
  146. // However, if the destination file is a special file, we don't want to
  147. // use rename (e.g. we don't want to replace /dev/null with a regular
  148. // file.) If that's the case, we create an in-memory buffer, open the
  149. // destination file and write to it on commit().
  150. switch (Stat.type()) {
  151. case fs::file_type::directory_file:
  152. return errorCodeToError(errc::is_a_directory);
  153. case fs::file_type::regular_file:
  154. case fs::file_type::file_not_found:
  155. case fs::file_type::status_error:
  156. if (Flags & F_no_mmap)
  157. return createInMemoryBuffer(Path, Size, Mode);
  158. else
  159. return createOnDiskBuffer(Path, Size, Mode);
  160. default:
  161. return createInMemoryBuffer(Path, Size, Mode);
  162. }
  163. }