1 //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Utility for creating a in-memory buffer that will be written to a file.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/FileOutputBuffer.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/Memory.h"
18 #include "llvm/Support/Path.h"
19 #include <system_error>
21 #if !defined(_MSC_VER) && !defined(__MINGW32__)
28 using namespace llvm::sys
;
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
{
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
)) {}
40 uint8_t *getBufferStart() const override
{ return (uint8_t *)Buffer
->data(); }
42 uint8_t *getBufferEnd() const override
{
43 return (uint8_t *)Buffer
->data() + Buffer
->size();
46 size_t getBufferSize() const override
{ return Buffer
->size(); }
48 Error
commit() override
{
49 // Unmap buffer, letting OS flush dirty pages to file on disk.
52 // Atomically replace the existing file with the new one.
53 return Temp
.keep(FinalPath
);
56 ~OnDiskBuffer() override
{
57 // Close the mapping before deleting the temp file, so that the removal
60 consumeError(Temp
.discard());
63 void discard() override
{
64 // Delete the temp file if it still was open, but keeping the mapping
66 consumeError(Temp
.discard());
70 std::unique_ptr
<fs::mapped_file_region
> Buffer
;
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
{
78 InMemoryBuffer(StringRef Path
, MemoryBlock Buf
, unsigned Mode
)
79 : FileOutputBuffer(Path
), Buffer(Buf
), Mode(Mode
) {}
81 uint8_t *getBufferStart() const override
{ return (uint8_t *)Buffer
.base(); }
83 uint8_t *getBufferEnd() const override
{
84 return (uint8_t *)Buffer
.base() + Buffer
.size();
87 size_t getBufferSize() const override
{ return Buffer
.size(); }
89 Error
commit() override
{
90 if (FinalPath
== "-") {
91 llvm::outs() << StringRef((const char *)Buffer
.base(), Buffer
.size());
93 return Error::success();
96 using namespace sys::fs
;
100 openFileForWrite(FinalPath
, FD
, CD_CreateAlways
, OF_None
, Mode
))
101 return errorCodeToError(EC
);
102 raw_fd_ostream
OS(FD
, /*shouldClose=*/true, /*unbuffered=*/true);
103 OS
<< StringRef((const char *)Buffer
.base(), Buffer
.size());
104 return Error::success();
108 OwningMemoryBlock Buffer
;
113 static Expected
<std::unique_ptr
<InMemoryBuffer
>>
114 createInMemoryBuffer(StringRef Path
, size_t Size
, unsigned Mode
) {
116 MemoryBlock MB
= Memory::allocateMappedMemory(
117 Size
, nullptr, sys::Memory::MF_READ
| sys::Memory::MF_WRITE
, EC
);
119 return errorCodeToError(EC
);
120 return llvm::make_unique
<InMemoryBuffer
>(Path
, MB
, Mode
);
123 static Expected
<std::unique_ptr
<FileOutputBuffer
>>
124 createOnDiskBuffer(StringRef Path
, size_t Size
, unsigned Mode
) {
125 Expected
<fs::TempFile
> FileOrErr
=
126 fs::TempFile::create(Path
+ ".tmp%%%%%%%", Mode
);
128 return FileOrErr
.takeError();
129 fs::TempFile File
= std::move(*FileOrErr
);
132 // On Windows, CreateFileMapping (the mmap function on Windows)
133 // automatically extends the underlying file. We don't need to
134 // extend the file beforehand. _chsize (ftruncate on Windows) is
135 // pretty slow just like it writes specified amount of bytes,
136 // so we should avoid calling that function.
137 if (auto EC
= fs::resize_file(File
.FD
, Size
)) {
138 consumeError(File
.discard());
139 return errorCodeToError(EC
);
145 auto MappedFile
= llvm::make_unique
<fs::mapped_file_region
>(
146 File
.FD
, fs::mapped_file_region::readwrite
, Size
, 0, EC
);
148 // mmap(2) can fail if the underlying filesystem does not support it.
149 // If that happens, we fall back to in-memory buffer as the last resort.
151 consumeError(File
.discard());
152 return createInMemoryBuffer(Path
, Size
, Mode
);
155 return llvm::make_unique
<OnDiskBuffer
>(Path
, std::move(File
),
156 std::move(MappedFile
));
159 // Create an instance of FileOutputBuffer.
160 Expected
<std::unique_ptr
<FileOutputBuffer
>>
161 FileOutputBuffer::create(StringRef Path
, size_t Size
, unsigned Flags
) {
162 // Handle "-" as stdout just like llvm::raw_ostream does.
164 return createInMemoryBuffer("-", Size
, /*Mode=*/0);
166 unsigned Mode
= fs::all_read
| fs::all_write
;
167 if (Flags
& F_executable
)
170 fs::file_status Stat
;
171 fs::status(Path
, Stat
);
173 // Usually, we want to create OnDiskBuffer to create a temporary file in
174 // the same directory as the destination file and atomically replaces it
177 // However, if the destination file is a special file, we don't want to
178 // use rename (e.g. we don't want to replace /dev/null with a regular
179 // file.) If that's the case, we create an in-memory buffer, open the
180 // destination file and write to it on commit().
181 switch (Stat
.type()) {
182 case fs::file_type::directory_file
:
183 return errorCodeToError(errc::is_a_directory
);
184 case fs::file_type::regular_file
:
185 case fs::file_type::file_not_found
:
186 case fs::file_type::status_error
:
187 return createOnDiskBuffer(Path
, Size
, Mode
);
189 return createInMemoryBuffer(Path
, Size
, Mode
);