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