15fce8c4fSNick Kledzik //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
25fce8c4fSNick Kledzik //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65fce8c4fSNick Kledzik //
75fce8c4fSNick Kledzik //===----------------------------------------------------------------------===//
85fce8c4fSNick Kledzik //
95fce8c4fSNick Kledzik // Utility for creating a in-memory buffer that will be written to a file.
105fce8c4fSNick Kledzik //
115fce8c4fSNick Kledzik //===----------------------------------------------------------------------===//
125fce8c4fSNick Kledzik 
13d9903888SChandler Carruth #include "llvm/Support/FileOutputBuffer.h"
1416132e6fSBenjamin Kramer #include "llvm/ADT/STLExtras.h"
1516132e6fSBenjamin Kramer #include "llvm/ADT/SmallString.h"
1616132e6fSBenjamin Kramer #include "llvm/Support/Errc.h"
17a16fe65bSRui Ueyama #include "llvm/Support/Memory.h"
18d4b24edaSRafael Espindola #include "llvm/Support/Path.h"
19a6e9c3e4SRafael Espindola #include <system_error>
205fce8c4fSNick Kledzik 
217eb1f185SRafael Espindola #if !defined(_MSC_VER) && !defined(__MINGW32__)
227eb1f185SRafael Espindola #include <unistd.h>
237eb1f185SRafael Espindola #else
247eb1f185SRafael Espindola #include <io.h>
257eb1f185SRafael Espindola #endif
267eb1f185SRafael Espindola 
27a16fe65bSRui Ueyama using namespace llvm;
28a16fe65bSRui Ueyama using namespace llvm::sys;
295fce8c4fSNick Kledzik 
3051ebcaafSBenjamin Kramer namespace {
31a16fe65bSRui Ueyama // A FileOutputBuffer which creates a temporary file in the same directory
32a16fe65bSRui Ueyama // as the final output file. The final output file is atomically replaced
33a16fe65bSRui Ueyama // with the temporary file on commit().
34a16fe65bSRui Ueyama class OnDiskBuffer : public FileOutputBuffer {
35a16fe65bSRui Ueyama public:
3658fe67a9SRafael Espindola   OnDiskBuffer(StringRef Path, fs::TempFile Temp,
37a16fe65bSRui Ueyama                std::unique_ptr<fs::mapped_file_region> Buf)
3858fe67a9SRafael Espindola       : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {}
395fce8c4fSNick Kledzik 
40a16fe65bSRui Ueyama   uint8_t *getBufferStart() const override { return (uint8_t *)Buffer->data(); }
41a16fe65bSRui Ueyama 
42a16fe65bSRui Ueyama   uint8_t *getBufferEnd() const override {
43a16fe65bSRui Ueyama     return (uint8_t *)Buffer->data() + Buffer->size();
44a16fe65bSRui Ueyama   }
45a16fe65bSRui Ueyama 
46a16fe65bSRui Ueyama   size_t getBufferSize() const override { return Buffer->size(); }
47a16fe65bSRui Ueyama 
480d7a38a8SRafael Espindola   Error commit() override {
49a16fe65bSRui Ueyama     // Unmap buffer, letting OS flush dirty pages to file on disk.
50a16fe65bSRui Ueyama     Buffer.reset();
51a16fe65bSRui Ueyama 
52a16fe65bSRui Ueyama     // Atomically replace the existing file with the new one.
5358fe67a9SRafael Espindola     return Temp.keep(FinalPath);
54a16fe65bSRui Ueyama   }
55a16fe65bSRui Ueyama 
56a16fe65bSRui Ueyama   ~OnDiskBuffer() override {
571a4398a1SReid Kleckner     // Close the mapping before deleting the temp file, so that the removal
581a4398a1SReid Kleckner     // succeeds.
59a16fe65bSRui Ueyama     Buffer.reset();
6058fe67a9SRafael Espindola     consumeError(Temp.discard());
615fce8c4fSNick Kledzik   }
625fce8c4fSNick Kledzik 
634153e9fbSMartin Storsjo   void discard() override {
644153e9fbSMartin Storsjo     // Delete the temp file if it still was open, but keeping the mapping
654153e9fbSMartin Storsjo     // active.
664153e9fbSMartin Storsjo     consumeError(Temp.discard());
674153e9fbSMartin Storsjo   }
684153e9fbSMartin Storsjo 
69a16fe65bSRui Ueyama private:
70a16fe65bSRui Ueyama   std::unique_ptr<fs::mapped_file_region> Buffer;
7158fe67a9SRafael Espindola   fs::TempFile Temp;
72a16fe65bSRui Ueyama };
73a16fe65bSRui Ueyama 
74a16fe65bSRui Ueyama // A FileOutputBuffer which keeps data in memory and writes to the final
75a16fe65bSRui Ueyama // output file on commit(). This is used only when we cannot use OnDiskBuffer.
76a16fe65bSRui Ueyama class InMemoryBuffer : public FileOutputBuffer {
77a16fe65bSRui Ueyama public:
7893d2bddaSLang Hames   InMemoryBuffer(StringRef Path, MemoryBlock Buf, std::size_t BufSize,
7993d2bddaSLang Hames                  unsigned Mode)
8093d2bddaSLang Hames       : FileOutputBuffer(Path), Buffer(Buf), BufferSize(BufSize),
8193d2bddaSLang Hames         Mode(Mode) {}
82a16fe65bSRui Ueyama 
83a16fe65bSRui Ueyama   uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }
84a16fe65bSRui Ueyama 
85a16fe65bSRui Ueyama   uint8_t *getBufferEnd() const override {
8693d2bddaSLang Hames     return (uint8_t *)Buffer.base() + BufferSize;
87a16fe65bSRui Ueyama   }
88a16fe65bSRui Ueyama 
8993d2bddaSLang Hames   size_t getBufferSize() const override { return BufferSize; }
90a16fe65bSRui Ueyama 
910d7a38a8SRafael Espindola   Error commit() override {
924063cfc7SRui Ueyama     if (FinalPath == "-") {
9393d2bddaSLang Hames       llvm::outs() << StringRef((const char *)Buffer.base(), BufferSize);
944063cfc7SRui Ueyama       llvm::outs().flush();
954063cfc7SRui Ueyama       return Error::success();
964063cfc7SRui Ueyama     }
974063cfc7SRui Ueyama 
981f67a3cbSZachary Turner     using namespace sys::fs;
99d4b24edaSRafael Espindola     int FD;
100a16fe65bSRui Ueyama     std::error_code EC;
101154a72ddSZachary Turner     if (auto EC =
102154a72ddSZachary Turner             openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode))
1030d7a38a8SRafael Espindola       return errorCodeToError(EC);
104a16fe65bSRui Ueyama     raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true);
10593d2bddaSLang Hames     OS << StringRef((const char *)Buffer.base(), BufferSize);
1060d7a38a8SRafael Espindola     return Error::success();
107d4b24edaSRafael Espindola   }
108d4b24edaSRafael Espindola 
109a16fe65bSRui Ueyama private:
11093d2bddaSLang Hames   // Buffer may actually contain a larger memory block than BufferSize
111a16fe65bSRui Ueyama   OwningMemoryBlock Buffer;
11293d2bddaSLang Hames   size_t BufferSize;
113a16fe65bSRui Ueyama   unsigned Mode;
114a16fe65bSRui Ueyama };
11551ebcaafSBenjamin Kramer } // namespace
116a16fe65bSRui Ueyama 
117f6490e04SRui Ueyama static Expected<std::unique_ptr<InMemoryBuffer>>
118f6490e04SRui Ueyama createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {
119f6490e04SRui Ueyama   std::error_code EC;
120f6490e04SRui Ueyama   MemoryBlock MB = Memory::allocateMappedMemory(
121f6490e04SRui Ueyama       Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
122f6490e04SRui Ueyama   if (EC)
123f6490e04SRui Ueyama     return errorCodeToError(EC);
124*0eaee545SJonas Devlieghere   return std::make_unique<InMemoryBuffer>(Path, MB, Size, Mode);
125f6490e04SRui Ueyama }
126f6490e04SRui Ueyama 
12721d451caSRui Ueyama static Expected<std::unique_ptr<FileOutputBuffer>>
1288e7600dcSRui Ueyama createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {
12958fe67a9SRafael Espindola   Expected<fs::TempFile> FileOrErr =
13058fe67a9SRafael Espindola       fs::TempFile::create(Path + ".tmp%%%%%%%", Mode);
13158fe67a9SRafael Espindola   if (!FileOrErr)
13258fe67a9SRafael Espindola     return FileOrErr.takeError();
13358fe67a9SRafael Espindola   fs::TempFile File = std::move(*FileOrErr);
1347dbb5778SRafael Espindola 
135712e8d29SNico Weber #ifndef _WIN32
136da9bc2e5SRui Ueyama   // On Windows, CreateFileMapping (the mmap function on Windows)
137da9bc2e5SRui Ueyama   // automatically extends the underlying file. We don't need to
138da9bc2e5SRui Ueyama   // extend the file beforehand. _chsize (ftruncate on Windows) is
139da9bc2e5SRui Ueyama   // pretty slow just like it writes specified amount of bytes,
140a16fe65bSRui Ueyama   // so we should avoid calling that function.
14158fe67a9SRafael Espindola   if (auto EC = fs::resize_file(File.FD, Size)) {
14258fe67a9SRafael Espindola     consumeError(File.discard());
143e0df357dSRafael Espindola     return errorCodeToError(EC);
14458fe67a9SRafael Espindola   }
145da9bc2e5SRui Ueyama #endif
146c69f13bfSRafael Espindola 
147a16fe65bSRui Ueyama   // Mmap it.
148a16fe65bSRui Ueyama   std::error_code EC;
149*0eaee545SJonas Devlieghere   auto MappedFile = std::make_unique<fs::mapped_file_region>(
150cc418a3aSReid Kleckner       fs::convertFDToNativeFile(File.FD), fs::mapped_file_region::readwrite,
151cc418a3aSReid Kleckner       Size, 0, EC);
15221d451caSRui Ueyama 
15321d451caSRui Ueyama   // mmap(2) can fail if the underlying filesystem does not support it.
15421d451caSRui Ueyama   // If that happens, we fall back to in-memory buffer as the last resort.
15558fe67a9SRafael Espindola   if (EC) {
15658fe67a9SRafael Espindola     consumeError(File.discard());
15721d451caSRui Ueyama     return createInMemoryBuffer(Path, Size, Mode);
15858fe67a9SRafael Espindola   }
15921d451caSRui Ueyama 
160*0eaee545SJonas Devlieghere   return std::make_unique<OnDiskBuffer>(Path, std::move(File),
16158fe67a9SRafael Espindola                                          std::move(MappedFile));
1625fce8c4fSNick Kledzik }
1635fce8c4fSNick Kledzik 
164a16fe65bSRui Ueyama // Create an instance of FileOutputBuffer.
165e0df357dSRafael Espindola Expected<std::unique_ptr<FileOutputBuffer>>
166a16fe65bSRui Ueyama FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {
1674063cfc7SRui Ueyama   // Handle "-" as stdout just like llvm::raw_ostream does.
1684063cfc7SRui Ueyama   if (Path == "-")
1694063cfc7SRui Ueyama     return createInMemoryBuffer("-", Size, /*Mode=*/0);
1704063cfc7SRui Ueyama 
171a16fe65bSRui Ueyama   unsigned Mode = fs::all_read | fs::all_write;
172a16fe65bSRui Ueyama   if (Flags & F_executable)
173a16fe65bSRui Ueyama     Mode |= fs::all_exe;
1745fce8c4fSNick Kledzik 
175a16fe65bSRui Ueyama   fs::file_status Stat;
176a16fe65bSRui Ueyama   fs::status(Path, Stat);
177d4b24edaSRafael Espindola 
178a16fe65bSRui Ueyama   // Usually, we want to create OnDiskBuffer to create a temporary file in
179a16fe65bSRui Ueyama   // the same directory as the destination file and atomically replaces it
180a16fe65bSRui Ueyama   // by rename(2).
181a16fe65bSRui Ueyama   //
182a16fe65bSRui Ueyama   // However, if the destination file is a special file, we don't want to
183a16fe65bSRui Ueyama   // use rename (e.g. we don't want to replace /dev/null with a regular
184a16fe65bSRui Ueyama   // file.) If that's the case, we create an in-memory buffer, open the
185a16fe65bSRui Ueyama   // destination file and write to it on commit().
186a16fe65bSRui Ueyama   switch (Stat.type()) {
187a16fe65bSRui Ueyama   case fs::file_type::directory_file:
188e0df357dSRafael Espindola     return errorCodeToError(errc::is_a_directory);
189a16fe65bSRui Ueyama   case fs::file_type::regular_file:
190a16fe65bSRui Ueyama   case fs::file_type::file_not_found:
191a16fe65bSRui Ueyama   case fs::file_type::status_error:
1928e7600dcSRui Ueyama     return createOnDiskBuffer(Path, Size, Mode);
193a16fe65bSRui Ueyama   default:
194f6490e04SRui Ueyama     return createInMemoryBuffer(Path, Size, Mode);
1955fce8c4fSNick Kledzik   }
196a16fe65bSRui Ueyama }
197