xref: /src/contrib/llvm-project/llvm/lib/Support/FileOutputBuffer.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
158b69754SDimitry Andric //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
258b69754SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
658b69754SDimitry Andric //
758b69754SDimitry Andric //===----------------------------------------------------------------------===//
858b69754SDimitry Andric //
958b69754SDimitry Andric // Utility for creating a in-memory buffer that will be written to a file.
1058b69754SDimitry Andric //
1158b69754SDimitry Andric //===----------------------------------------------------------------------===//
1258b69754SDimitry Andric 
1367c32a98SDimitry Andric #include "llvm/Support/FileOutputBuffer.h"
145a5ac124SDimitry Andric #include "llvm/Support/Errc.h"
15cfca06d7SDimitry Andric #include "llvm/Support/FileSystem.h"
16044eb2f6SDimitry Andric #include "llvm/Support/Memory.h"
17b1c73532SDimitry Andric #include "llvm/Support/TimeProfiler.h"
185ca98fd9SDimitry Andric #include <system_error>
1958b69754SDimitry Andric 
2067c32a98SDimitry Andric #if !defined(_MSC_VER) && !defined(__MINGW32__)
2167c32a98SDimitry Andric #include <unistd.h>
2267c32a98SDimitry Andric #else
2367c32a98SDimitry Andric #include <io.h>
2467c32a98SDimitry Andric #endif
2567c32a98SDimitry Andric 
26044eb2f6SDimitry Andric using namespace llvm;
27044eb2f6SDimitry Andric using namespace llvm::sys;
2858b69754SDimitry Andric 
29044eb2f6SDimitry Andric namespace {
30044eb2f6SDimitry Andric // A FileOutputBuffer which creates a temporary file in the same directory
31044eb2f6SDimitry Andric // as the final output file. The final output file is atomically replaced
32044eb2f6SDimitry Andric // with the temporary file on commit().
33044eb2f6SDimitry Andric class OnDiskBuffer : public FileOutputBuffer {
34044eb2f6SDimitry Andric public:
OnDiskBuffer(StringRef Path,fs::TempFile Temp,fs::mapped_file_region Buf)35344a3780SDimitry Andric   OnDiskBuffer(StringRef Path, fs::TempFile Temp, fs::mapped_file_region Buf)
36044eb2f6SDimitry Andric       : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {}
3758b69754SDimitry Andric 
getBufferStart() const38344a3780SDimitry Andric   uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.data(); }
39044eb2f6SDimitry Andric 
getBufferEnd() const40044eb2f6SDimitry Andric   uint8_t *getBufferEnd() const override {
41344a3780SDimitry Andric     return (uint8_t *)Buffer.data() + Buffer.size();
42044eb2f6SDimitry Andric   }
43044eb2f6SDimitry Andric 
getBufferSize() const44344a3780SDimitry Andric   size_t getBufferSize() const override { return Buffer.size(); }
45044eb2f6SDimitry Andric 
commit()46044eb2f6SDimitry Andric   Error commit() override {
47b1c73532SDimitry Andric     llvm::TimeTraceScope timeScope("Commit buffer to disk");
48b1c73532SDimitry Andric 
49044eb2f6SDimitry Andric     // Unmap buffer, letting OS flush dirty pages to file on disk.
50344a3780SDimitry Andric     Buffer.unmap();
51044eb2f6SDimitry Andric 
52044eb2f6SDimitry Andric     // Atomically replace the existing file with the new one.
53044eb2f6SDimitry Andric     return Temp.keep(FinalPath);
54044eb2f6SDimitry Andric   }
55044eb2f6SDimitry Andric 
~OnDiskBuffer()56044eb2f6SDimitry Andric   ~OnDiskBuffer() override {
57b915e9e0SDimitry Andric     // Close the mapping before deleting the temp file, so that the removal
58b915e9e0SDimitry Andric     // succeeds.
59344a3780SDimitry Andric     Buffer.unmap();
60044eb2f6SDimitry Andric     consumeError(Temp.discard());
6158b69754SDimitry Andric   }
6258b69754SDimitry Andric 
discard()63d8e91e46SDimitry Andric   void discard() override {
64d8e91e46SDimitry Andric     // Delete the temp file if it still was open, but keeping the mapping
65d8e91e46SDimitry Andric     // active.
66d8e91e46SDimitry Andric     consumeError(Temp.discard());
67d8e91e46SDimitry Andric   }
68d8e91e46SDimitry Andric 
69044eb2f6SDimitry Andric private:
70344a3780SDimitry Andric   fs::mapped_file_region Buffer;
71044eb2f6SDimitry Andric   fs::TempFile Temp;
72044eb2f6SDimitry Andric };
73044eb2f6SDimitry Andric 
74044eb2f6SDimitry Andric // A FileOutputBuffer which keeps data in memory and writes to the final
75044eb2f6SDimitry Andric // output file on commit(). This is used only when we cannot use OnDiskBuffer.
76044eb2f6SDimitry Andric class InMemoryBuffer : public FileOutputBuffer {
77044eb2f6SDimitry Andric public:
InMemoryBuffer(StringRef Path,MemoryBlock Buf,std::size_t BufSize,unsigned Mode)78e6d15924SDimitry Andric   InMemoryBuffer(StringRef Path, MemoryBlock Buf, std::size_t BufSize,
79e6d15924SDimitry Andric                  unsigned Mode)
80e6d15924SDimitry Andric       : FileOutputBuffer(Path), Buffer(Buf), BufferSize(BufSize),
81e6d15924SDimitry Andric         Mode(Mode) {}
82044eb2f6SDimitry Andric 
getBufferStart() const83044eb2f6SDimitry Andric   uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }
84044eb2f6SDimitry Andric 
getBufferEnd() const85044eb2f6SDimitry Andric   uint8_t *getBufferEnd() const override {
86e6d15924SDimitry Andric     return (uint8_t *)Buffer.base() + BufferSize;
8758b69754SDimitry Andric   }
8858b69754SDimitry Andric 
getBufferSize() const89e6d15924SDimitry Andric   size_t getBufferSize() const override { return BufferSize; }
9058b69754SDimitry Andric 
commit()91044eb2f6SDimitry Andric   Error commit() override {
92e6d15924SDimitry Andric     if (FinalPath == "-") {
93e6d15924SDimitry Andric       llvm::outs() << StringRef((const char *)Buffer.base(), BufferSize);
94e6d15924SDimitry Andric       llvm::outs().flush();
95e6d15924SDimitry Andric       return Error::success();
96e6d15924SDimitry Andric     }
97e6d15924SDimitry Andric 
98eb11fae6SDimitry Andric     using namespace sys::fs;
99581a6d85SDimitry Andric     int FD;
100044eb2f6SDimitry Andric     std::error_code EC;
101eb11fae6SDimitry Andric     if (auto EC =
102eb11fae6SDimitry Andric             openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode))
103044eb2f6SDimitry Andric       return errorCodeToError(EC);
104044eb2f6SDimitry Andric     raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true);
105e6d15924SDimitry Andric     OS << StringRef((const char *)Buffer.base(), BufferSize);
106044eb2f6SDimitry Andric     return Error::success();
107581a6d85SDimitry Andric   }
108581a6d85SDimitry Andric 
109044eb2f6SDimitry Andric private:
110e6d15924SDimitry Andric   // Buffer may actually contain a larger memory block than BufferSize
111044eb2f6SDimitry Andric   OwningMemoryBlock Buffer;
112e6d15924SDimitry Andric   size_t BufferSize;
113044eb2f6SDimitry Andric   unsigned Mode;
114044eb2f6SDimitry Andric };
115044eb2f6SDimitry Andric } // namespace
11658b69754SDimitry Andric 
117044eb2f6SDimitry Andric static Expected<std::unique_ptr<InMemoryBuffer>>
createInMemoryBuffer(StringRef Path,size_t Size,unsigned Mode)118044eb2f6SDimitry Andric createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {
119044eb2f6SDimitry Andric   std::error_code EC;
120044eb2f6SDimitry Andric   MemoryBlock MB = Memory::allocateMappedMemory(
121044eb2f6SDimitry Andric       Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
122044eb2f6SDimitry Andric   if (EC)
123044eb2f6SDimitry Andric     return errorCodeToError(EC);
1241d5ae102SDimitry Andric   return std::make_unique<InMemoryBuffer>(Path, MB, Size, Mode);
125044eb2f6SDimitry Andric }
126044eb2f6SDimitry Andric 
127e6d15924SDimitry Andric static Expected<std::unique_ptr<FileOutputBuffer>>
createOnDiskBuffer(StringRef Path,size_t Size,unsigned Mode)128e6d15924SDimitry Andric createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {
129044eb2f6SDimitry Andric   Expected<fs::TempFile> FileOrErr =
130044eb2f6SDimitry Andric       fs::TempFile::create(Path + ".tmp%%%%%%%", Mode);
131044eb2f6SDimitry Andric   if (!FileOrErr)
132044eb2f6SDimitry Andric     return FileOrErr.takeError();
133044eb2f6SDimitry Andric   fs::TempFile File = std::move(*FileOrErr);
134dd58ef01SDimitry Andric 
135344a3780SDimitry Andric   if (auto EC = fs::resize_file_before_mapping_readwrite(File.FD, Size)) {
136044eb2f6SDimitry Andric     consumeError(File.discard());
137044eb2f6SDimitry Andric     return errorCodeToError(EC);
138044eb2f6SDimitry Andric   }
13958b69754SDimitry Andric 
140044eb2f6SDimitry Andric   // Mmap it.
141581a6d85SDimitry Andric   std::error_code EC;
142344a3780SDimitry Andric   fs::mapped_file_region MappedFile =
143344a3780SDimitry Andric       fs::mapped_file_region(fs::convertFDToNativeFile(File.FD),
144344a3780SDimitry Andric                              fs::mapped_file_region::readwrite, Size, 0, EC);
145e6d15924SDimitry Andric 
146e6d15924SDimitry Andric   // mmap(2) can fail if the underlying filesystem does not support it.
147e6d15924SDimitry Andric   // If that happens, we fall back to in-memory buffer as the last resort.
148044eb2f6SDimitry Andric   if (EC) {
149044eb2f6SDimitry Andric     consumeError(File.discard());
150e6d15924SDimitry Andric     return createInMemoryBuffer(Path, Size, Mode);
151044eb2f6SDimitry Andric   }
152e6d15924SDimitry Andric 
1531d5ae102SDimitry Andric   return std::make_unique<OnDiskBuffer>(Path, std::move(File),
154044eb2f6SDimitry Andric                                          std::move(MappedFile));
155581a6d85SDimitry Andric }
156581a6d85SDimitry Andric 
157044eb2f6SDimitry Andric // Create an instance of FileOutputBuffer.
158044eb2f6SDimitry Andric Expected<std::unique_ptr<FileOutputBuffer>>
create(StringRef Path,size_t Size,unsigned Flags)159044eb2f6SDimitry Andric FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {
160e6d15924SDimitry Andric   // Handle "-" as stdout just like llvm::raw_ostream does.
161e6d15924SDimitry Andric   if (Path == "-")
162e6d15924SDimitry Andric     return createInMemoryBuffer("-", Size, /*Mode=*/0);
163e6d15924SDimitry Andric 
164044eb2f6SDimitry Andric   unsigned Mode = fs::all_read | fs::all_write;
165044eb2f6SDimitry Andric   if (Flags & F_executable)
166044eb2f6SDimitry Andric     Mode |= fs::all_exe;
167044eb2f6SDimitry Andric 
168cfca06d7SDimitry Andric   // If Size is zero, don't use mmap which will fail with EINVAL.
169cfca06d7SDimitry Andric   if (Size == 0)
170cfca06d7SDimitry Andric     return createInMemoryBuffer(Path, Size, Mode);
171cfca06d7SDimitry Andric 
172044eb2f6SDimitry Andric   fs::file_status Stat;
173044eb2f6SDimitry Andric   fs::status(Path, Stat);
174044eb2f6SDimitry Andric 
175044eb2f6SDimitry Andric   // Usually, we want to create OnDiskBuffer to create a temporary file in
176044eb2f6SDimitry Andric   // the same directory as the destination file and atomically replaces it
177044eb2f6SDimitry Andric   // by rename(2).
178044eb2f6SDimitry Andric   //
179044eb2f6SDimitry Andric   // However, if the destination file is a special file, we don't want to
180044eb2f6SDimitry Andric   // use rename (e.g. we don't want to replace /dev/null with a regular
181044eb2f6SDimitry Andric   // file.) If that's the case, we create an in-memory buffer, open the
182044eb2f6SDimitry Andric   // destination file and write to it on commit().
183044eb2f6SDimitry Andric   switch (Stat.type()) {
184044eb2f6SDimitry Andric   case fs::file_type::directory_file:
185044eb2f6SDimitry Andric     return errorCodeToError(errc::is_a_directory);
186044eb2f6SDimitry Andric   case fs::file_type::regular_file:
187044eb2f6SDimitry Andric   case fs::file_type::file_not_found:
188044eb2f6SDimitry Andric   case fs::file_type::status_error:
189706b4fc4SDimitry Andric     if (Flags & F_no_mmap)
190706b4fc4SDimitry Andric       return createInMemoryBuffer(Path, Size, Mode);
191706b4fc4SDimitry Andric     else
192e6d15924SDimitry Andric       return createOnDiskBuffer(Path, Size, Mode);
193044eb2f6SDimitry Andric   default:
194044eb2f6SDimitry Andric     return createInMemoryBuffer(Path, Size, Mode);
19558b69754SDimitry Andric   }
196044eb2f6SDimitry Andric }
197