1 //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Utility for creating a in-memory buffer that will be written to a file. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Support/FileOutputBuffer.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/Support/Errc.h" 18 #include "llvm/Support/Memory.h" 19 #include "llvm/Support/Path.h" 20 #include <system_error> 21 22 #if !defined(_MSC_VER) && !defined(__MINGW32__) 23 #include <unistd.h> 24 #else 25 #include <io.h> 26 #endif 27 28 using namespace llvm; 29 using namespace llvm::sys; 30 31 namespace { 32 // A FileOutputBuffer which creates a temporary file in the same directory 33 // as the final output file. The final output file is atomically replaced 34 // with the temporary file on commit(). 35 class OnDiskBuffer : public FileOutputBuffer { 36 public: 37 OnDiskBuffer(StringRef Path, fs::TempFile Temp, 38 std::unique_ptr<fs::mapped_file_region> Buf) 39 : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {} 40 41 uint8_t *getBufferStart() const override { return (uint8_t *)Buffer->data(); } 42 43 uint8_t *getBufferEnd() const override { 44 return (uint8_t *)Buffer->data() + Buffer->size(); 45 } 46 47 size_t getBufferSize() const override { return Buffer->size(); } 48 49 Error commit() override { 50 // Unmap buffer, letting OS flush dirty pages to file on disk. 51 Buffer.reset(); 52 53 // Atomically replace the existing file with the new one. 54 return Temp.keep(FinalPath); 55 } 56 57 ~OnDiskBuffer() override { 58 // Close the mapping before deleting the temp file, so that the removal 59 // succeeds. 60 Buffer.reset(); 61 consumeError(Temp.discard()); 62 } 63 64 void discard() override { 65 // Delete the temp file if it still was open, but keeping the mapping 66 // active. 67 consumeError(Temp.discard()); 68 } 69 70 private: 71 std::unique_ptr<fs::mapped_file_region> Buffer; 72 fs::TempFile Temp; 73 }; 74 75 // A FileOutputBuffer which keeps data in memory and writes to the final 76 // output file on commit(). This is used only when we cannot use OnDiskBuffer. 77 class InMemoryBuffer : public FileOutputBuffer { 78 public: 79 InMemoryBuffer(StringRef Path, MemoryBlock Buf, unsigned Mode) 80 : FileOutputBuffer(Path), Buffer(Buf), Mode(Mode) {} 81 82 uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); } 83 84 uint8_t *getBufferEnd() const override { 85 return (uint8_t *)Buffer.base() + Buffer.size(); 86 } 87 88 size_t getBufferSize() const override { return Buffer.size(); } 89 90 Error commit() override { 91 using namespace sys::fs; 92 int FD; 93 std::error_code EC; 94 if (auto EC = 95 openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode)) 96 return errorCodeToError(EC); 97 raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true); 98 OS << StringRef((const char *)Buffer.base(), Buffer.size()); 99 return Error::success(); 100 } 101 102 private: 103 OwningMemoryBlock Buffer; 104 unsigned Mode; 105 }; 106 } // namespace 107 108 static Expected<std::unique_ptr<InMemoryBuffer>> 109 createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) { 110 std::error_code EC; 111 MemoryBlock MB = Memory::allocateMappedMemory( 112 Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC); 113 if (EC) 114 return errorCodeToError(EC); 115 return llvm::make_unique<InMemoryBuffer>(Path, MB, Mode); 116 } 117 118 static Expected<std::unique_ptr<OnDiskBuffer>> 119 createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) { 120 Expected<fs::TempFile> FileOrErr = 121 fs::TempFile::create(Path + ".tmp%%%%%%%", Mode); 122 if (!FileOrErr) 123 return FileOrErr.takeError(); 124 fs::TempFile File = std::move(*FileOrErr); 125 126 #ifndef _WIN32 127 // On Windows, CreateFileMapping (the mmap function on Windows) 128 // automatically extends the underlying file. We don't need to 129 // extend the file beforehand. _chsize (ftruncate on Windows) is 130 // pretty slow just like it writes specified amount of bytes, 131 // so we should avoid calling that function. 132 if (auto EC = fs::resize_file(File.FD, Size)) { 133 consumeError(File.discard()); 134 return errorCodeToError(EC); 135 } 136 #endif 137 138 // Mmap it. 139 std::error_code EC; 140 auto MappedFile = llvm::make_unique<fs::mapped_file_region>( 141 File.FD, fs::mapped_file_region::readwrite, Size, 0, EC); 142 if (EC) { 143 consumeError(File.discard()); 144 return errorCodeToError(EC); 145 } 146 return llvm::make_unique<OnDiskBuffer>(Path, std::move(File), 147 std::move(MappedFile)); 148 } 149 150 // Create an instance of FileOutputBuffer. 151 Expected<std::unique_ptr<FileOutputBuffer>> 152 FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) { 153 unsigned Mode = fs::all_read | fs::all_write; 154 if (Flags & F_executable) 155 Mode |= fs::all_exe; 156 157 fs::file_status Stat; 158 fs::status(Path, Stat); 159 160 // Usually, we want to create OnDiskBuffer to create a temporary file in 161 // the same directory as the destination file and atomically replaces it 162 // by rename(2). 163 // 164 // However, if the destination file is a special file, we don't want to 165 // use rename (e.g. we don't want to replace /dev/null with a regular 166 // file.) If that's the case, we create an in-memory buffer, open the 167 // destination file and write to it on commit(). 168 switch (Stat.type()) { 169 case fs::file_type::directory_file: 170 return errorCodeToError(errc::is_a_directory); 171 case fs::file_type::regular_file: 172 case fs::file_type::file_not_found: 173 case fs::file_type::status_error: 174 return createOnDiskBuffer(Path, Size, Mode); 175 default: 176 return createInMemoryBuffer(Path, Size, Mode); 177 } 178 } 179