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 13 #include "llvm/Support/FileOutputBuffer.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/Support/Errc.h" 16 #include "llvm/Support/FileSystem.h" 17 #include "llvm/Support/Memory.h" 18 #include "llvm/Support/Path.h" 19 #include <system_error> 20 21 #if !defined(_MSC_VER) && !defined(__MINGW32__) 22 #include <unistd.h> 23 #else 24 #include <io.h> 25 #endif 26 27 using namespace llvm; 28 using namespace llvm::sys; 29 30 namespace { 31 // A FileOutputBuffer which creates a temporary file in the same directory 32 // as the final output file. The final output file is atomically replaced 33 // with the temporary file on commit(). 34 class OnDiskBuffer : public FileOutputBuffer { 35 public: 36 OnDiskBuffer(StringRef Path, fs::TempFile Temp, 37 std::unique_ptr<fs::mapped_file_region> Buf) 38 : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {} 39 40 uint8_t *getBufferStart() const override { return (uint8_t *)Buffer->data(); } 41 42 uint8_t *getBufferEnd() const override { 43 return (uint8_t *)Buffer->data() + Buffer->size(); 44 } 45 46 size_t getBufferSize() const override { return Buffer->size(); } 47 48 Error commit() override { 49 // Unmap buffer, letting OS flush dirty pages to file on disk. 50 Buffer.reset(); 51 52 // Atomically replace the existing file with the new one. 53 return Temp.keep(FinalPath); 54 } 55 56 ~OnDiskBuffer() override { 57 // Close the mapping before deleting the temp file, so that the removal 58 // succeeds. 59 Buffer.reset(); 60 consumeError(Temp.discard()); 61 } 62 63 void discard() override { 64 // Delete the temp file if it still was open, but keeping the mapping 65 // active. 66 consumeError(Temp.discard()); 67 } 68 69 private: 70 std::unique_ptr<fs::mapped_file_region> Buffer; 71 fs::TempFile Temp; 72 }; 73 74 // A FileOutputBuffer which keeps data in memory and writes to the final 75 // output file on commit(). This is used only when we cannot use OnDiskBuffer. 76 class InMemoryBuffer : public FileOutputBuffer { 77 public: 78 InMemoryBuffer(StringRef Path, MemoryBlock Buf, std::size_t BufSize, 79 unsigned Mode) 80 : FileOutputBuffer(Path), Buffer(Buf), BufferSize(BufSize), 81 Mode(Mode) {} 82 83 uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); } 84 85 uint8_t *getBufferEnd() const override { 86 return (uint8_t *)Buffer.base() + BufferSize; 87 } 88 89 size_t getBufferSize() const override { return BufferSize; } 90 91 Error commit() override { 92 if (FinalPath == "-") { 93 llvm::outs() << StringRef((const char *)Buffer.base(), BufferSize); 94 llvm::outs().flush(); 95 return Error::success(); 96 } 97 98 using namespace sys::fs; 99 int FD; 100 std::error_code EC; 101 if (auto EC = 102 openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode)) 103 return errorCodeToError(EC); 104 raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true); 105 OS << StringRef((const char *)Buffer.base(), BufferSize); 106 return Error::success(); 107 } 108 109 private: 110 // Buffer may actually contain a larger memory block than BufferSize 111 OwningMemoryBlock Buffer; 112 size_t BufferSize; 113 unsigned Mode; 114 }; 115 } // namespace 116 117 static Expected<std::unique_ptr<InMemoryBuffer>> 118 createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) { 119 std::error_code EC; 120 MemoryBlock MB = Memory::allocateMappedMemory( 121 Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC); 122 if (EC) 123 return errorCodeToError(EC); 124 return std::make_unique<InMemoryBuffer>(Path, MB, Size, Mode); 125 } 126 127 static Expected<std::unique_ptr<FileOutputBuffer>> 128 createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode, 129 bool KeepOwnership, unsigned UserID, unsigned GroupID) { 130 Expected<fs::TempFile> FileOrErr = 131 fs::TempFile::create(Path + ".tmp%%%%%%%", Mode); 132 if (!FileOrErr) 133 return FileOrErr.takeError(); 134 fs::TempFile File = std::move(*FileOrErr); 135 136 #ifndef _WIN32 137 // Try to preserve file ownership if requested. 138 if (KeepOwnership) { 139 fs::file_status Stat; 140 if (!fs::status(File.FD, Stat) && Stat.getUser() == 0) 141 fs::changeFileOwnership(File.FD, UserID, GroupID); 142 } 143 144 // On Windows, CreateFileMapping (the mmap function on Windows) 145 // automatically extends the underlying file. We don't need to 146 // extend the file beforehand. _chsize (ftruncate on Windows) is 147 // pretty slow just like it writes specified amount of bytes, 148 // so we should avoid calling that function. 149 if (auto EC = fs::resize_file(File.FD, Size)) { 150 consumeError(File.discard()); 151 return errorCodeToError(EC); 152 } 153 #endif 154 155 // Mmap it. 156 std::error_code EC; 157 auto MappedFile = std::make_unique<fs::mapped_file_region>( 158 fs::convertFDToNativeFile(File.FD), fs::mapped_file_region::readwrite, 159 Size, 0, EC); 160 161 // mmap(2) can fail if the underlying filesystem does not support it. 162 // If that happens, we fall back to in-memory buffer as the last resort. 163 if (EC) { 164 consumeError(File.discard()); 165 return createInMemoryBuffer(Path, Size, Mode); 166 } 167 168 return std::make_unique<OnDiskBuffer>(Path, std::move(File), 169 std::move(MappedFile)); 170 } 171 172 // Create an instance of FileOutputBuffer. 173 Expected<std::unique_ptr<FileOutputBuffer>> 174 FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags, 175 unsigned UserID, unsigned GroupID) { 176 // Handle "-" as stdout just like llvm::raw_ostream does. 177 if (Path == "-") 178 return createInMemoryBuffer("-", Size, /*Mode=*/0); 179 180 unsigned Mode = fs::all_read | fs::all_write; 181 if (Flags & F_executable) 182 Mode |= fs::all_exe; 183 184 // If Size is zero, don't use mmap which will fail with EINVAL. 185 if (Size == 0) 186 return createInMemoryBuffer(Path, Size, Mode); 187 188 fs::file_status Stat; 189 fs::status(Path, Stat); 190 191 // Usually, we want to create OnDiskBuffer to create a temporary file in 192 // the same directory as the destination file and atomically replaces it 193 // by rename(2). 194 // 195 // However, if the destination file is a special file, we don't want to 196 // use rename (e.g. we don't want to replace /dev/null with a regular 197 // file.) If that's the case, we create an in-memory buffer, open the 198 // destination file and write to it on commit(). 199 switch (Stat.type()) { 200 case fs::file_type::directory_file: 201 return errorCodeToError(errc::is_a_directory); 202 case fs::file_type::regular_file: 203 case fs::file_type::file_not_found: 204 case fs::file_type::status_error: 205 if (Flags & F_no_mmap) 206 return createInMemoryBuffer(Path, Size, Mode); 207 else 208 return createOnDiskBuffer(Path, Size, Mode, Flags & F_keep_ownership, 209 UserID, GroupID); 210 default: 211 return createInMemoryBuffer(Path, Size, Mode); 212 } 213 } 214