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/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>
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
, fs::mapped_file_region Buf
)
37 : FileOutputBuffer(Path
), Buffer(std::move(Buf
)), Temp(std::move(Temp
)) {}
39 uint8_t *getBufferStart() const override
{ return (uint8_t *)Buffer
.data(); }
41 uint8_t *getBufferEnd() const override
{
42 return (uint8_t *)Buffer
.data() + Buffer
.size();
45 size_t getBufferSize() const override
{ return Buffer
.size(); }
47 Error
commit() override
{
48 // Unmap buffer, letting OS flush dirty pages to file on disk.
51 // Atomically replace the existing file with the new one.
52 return Temp
.keep(FinalPath
);
55 ~OnDiskBuffer() override
{
56 // Close the mapping before deleting the temp file, so that the removal
59 consumeError(Temp
.discard());
62 void discard() override
{
63 // Delete the temp file if it still was open, but keeping the mapping
65 consumeError(Temp
.discard());
69 fs::mapped_file_region Buffer
;
73 // A FileOutputBuffer which keeps data in memory and writes to the final
74 // output file on commit(). This is used only when we cannot use OnDiskBuffer.
75 class InMemoryBuffer
: public FileOutputBuffer
{
77 InMemoryBuffer(StringRef Path
, MemoryBlock Buf
, std::size_t BufSize
,
79 : FileOutputBuffer(Path
), Buffer(Buf
), BufferSize(BufSize
),
82 uint8_t *getBufferStart() const override
{ return (uint8_t *)Buffer
.base(); }
84 uint8_t *getBufferEnd() const override
{
85 return (uint8_t *)Buffer
.base() + BufferSize
;
88 size_t getBufferSize() const override
{ return BufferSize
; }
90 Error
commit() override
{
91 if (FinalPath
== "-") {
92 llvm::outs() << StringRef((const char *)Buffer
.base(), BufferSize
);
94 return Error::success();
97 using namespace sys::fs
;
101 openFileForWrite(FinalPath
, FD
, CD_CreateAlways
, OF_None
, Mode
))
102 return errorCodeToError(EC
);
103 raw_fd_ostream
OS(FD
, /*shouldClose=*/true, /*unbuffered=*/true);
104 OS
<< StringRef((const char *)Buffer
.base(), BufferSize
);
105 return Error::success();
109 // Buffer may actually contain a larger memory block than BufferSize
110 OwningMemoryBlock Buffer
;
116 static Expected
<std::unique_ptr
<InMemoryBuffer
>>
117 createInMemoryBuffer(StringRef Path
, size_t Size
, unsigned Mode
) {
119 MemoryBlock MB
= Memory::allocateMappedMemory(
120 Size
, nullptr, sys::Memory::MF_READ
| sys::Memory::MF_WRITE
, EC
);
122 return errorCodeToError(EC
);
123 return std::make_unique
<InMemoryBuffer
>(Path
, MB
, Size
, Mode
);
126 static Expected
<std::unique_ptr
<FileOutputBuffer
>>
127 createOnDiskBuffer(StringRef Path
, size_t Size
, unsigned Mode
) {
128 Expected
<fs::TempFile
> FileOrErr
=
129 fs::TempFile::create(Path
+ ".tmp%%%%%%%", Mode
);
131 return FileOrErr
.takeError();
132 fs::TempFile File
= std::move(*FileOrErr
);
134 if (auto EC
= fs::resize_file_before_mapping_readwrite(File
.FD
, Size
)) {
135 consumeError(File
.discard());
136 return errorCodeToError(EC
);
141 fs::mapped_file_region MappedFile
=
142 fs::mapped_file_region(fs::convertFDToNativeFile(File
.FD
),
143 fs::mapped_file_region::readwrite
, Size
, 0, EC
);
145 // mmap(2) can fail if the underlying filesystem does not support it.
146 // If that happens, we fall back to in-memory buffer as the last resort.
148 consumeError(File
.discard());
149 return createInMemoryBuffer(Path
, Size
, Mode
);
152 return std::make_unique
<OnDiskBuffer
>(Path
, std::move(File
),
153 std::move(MappedFile
));
156 // Create an instance of FileOutputBuffer.
157 Expected
<std::unique_ptr
<FileOutputBuffer
>>
158 FileOutputBuffer::create(StringRef Path
, size_t Size
, unsigned Flags
) {
159 // Handle "-" as stdout just like llvm::raw_ostream does.
161 return createInMemoryBuffer("-", Size
, /*Mode=*/0);
163 unsigned Mode
= fs::all_read
| fs::all_write
;
164 if (Flags
& F_executable
)
167 // If Size is zero, don't use mmap which will fail with EINVAL.
169 return createInMemoryBuffer(Path
, Size
, Mode
);
171 fs::file_status Stat
;
172 fs::status(Path
, Stat
);
174 // Usually, we want to create OnDiskBuffer to create a temporary file in
175 // the same directory as the destination file and atomically replaces it
178 // However, if the destination file is a special file, we don't want to
179 // use rename (e.g. we don't want to replace /dev/null with a regular
180 // file.) If that's the case, we create an in-memory buffer, open the
181 // destination file and write to it on commit().
182 switch (Stat
.type()) {
183 case fs::file_type::directory_file
:
184 return errorCodeToError(errc::is_a_directory
);
185 case fs::file_type::regular_file
:
186 case fs::file_type::file_not_found
:
187 case fs::file_type::status_error
:
188 if (Flags
& F_no_mmap
)
189 return createInMemoryBuffer(Path
, Size
, Mode
);
191 return createOnDiskBuffer(Path
, Size
, Mode
);
193 return createInMemoryBuffer(Path
, Size
, Mode
);