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/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>
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, unsigned Mode)
79       : FileOutputBuffer(Path), Buffer(Buf), Mode(Mode) {}
80 
81   uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }
82 
83   uint8_t *getBufferEnd() const override {
84     return (uint8_t *)Buffer.base() + Buffer.size();
85   }
86 
87   size_t getBufferSize() const override { return Buffer.size(); }
88 
89   Error commit() override {
90     using namespace sys::fs;
91     int FD;
92     std::error_code EC;
93     if (auto EC =
94             openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode))
95       return errorCodeToError(EC);
96     raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true);
97     OS << StringRef((const char *)Buffer.base(), Buffer.size());
98     return Error::success();
99   }
100 
101 private:
102   OwningMemoryBlock Buffer;
103   unsigned Mode;
104 };
105 } // namespace
106 
107 static Expected<std::unique_ptr<InMemoryBuffer>>
108 createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {
109   std::error_code EC;
110   MemoryBlock MB = Memory::allocateMappedMemory(
111       Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
112   if (EC)
113     return errorCodeToError(EC);
114   return llvm::make_unique<InMemoryBuffer>(Path, MB, Mode);
115 }
116 
117 static Expected<std::unique_ptr<OnDiskBuffer>>
118 createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {
119   Expected<fs::TempFile> FileOrErr =
120       fs::TempFile::create(Path + ".tmp%%%%%%%", Mode);
121   if (!FileOrErr)
122     return FileOrErr.takeError();
123   fs::TempFile File = std::move(*FileOrErr);
124 
125 #ifndef _WIN32
126   // On Windows, CreateFileMapping (the mmap function on Windows)
127   // automatically extends the underlying file. We don't need to
128   // extend the file beforehand. _chsize (ftruncate on Windows) is
129   // pretty slow just like it writes specified amount of bytes,
130   // so we should avoid calling that function.
131   if (auto EC = fs::resize_file(File.FD, Size)) {
132     consumeError(File.discard());
133     return errorCodeToError(EC);
134   }
135 #endif
136 
137   // Mmap it.
138   std::error_code EC;
139   auto MappedFile = llvm::make_unique<fs::mapped_file_region>(
140       File.FD, fs::mapped_file_region::readwrite, Size, 0, EC);
141   if (EC) {
142     consumeError(File.discard());
143     return errorCodeToError(EC);
144   }
145   return llvm::make_unique<OnDiskBuffer>(Path, std::move(File),
146                                          std::move(MappedFile));
147 }
148 
149 // Create an instance of FileOutputBuffer.
150 Expected<std::unique_ptr<FileOutputBuffer>>
151 FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {
152   unsigned Mode = fs::all_read | fs::all_write;
153   if (Flags & F_executable)
154     Mode |= fs::all_exe;
155 
156   fs::file_status Stat;
157   fs::status(Path, Stat);
158 
159   // Usually, we want to create OnDiskBuffer to create a temporary file in
160   // the same directory as the destination file and atomically replaces it
161   // by rename(2).
162   //
163   // However, if the destination file is a special file, we don't want to
164   // use rename (e.g. we don't want to replace /dev/null with a regular
165   // file.) If that's the case, we create an in-memory buffer, open the
166   // destination file and write to it on commit().
167   switch (Stat.type()) {
168   case fs::file_type::directory_file:
169     return errorCodeToError(errc::is_a_directory);
170   case fs::file_type::regular_file:
171   case fs::file_type::file_not_found:
172   case fs::file_type::status_error:
173     return createOnDiskBuffer(Path, Size, Mode);
174   default:
175     return createInMemoryBuffer(Path, Size, Mode);
176   }
177 }
178