blob: 0a5306f684d4ead4a8672a92faac74e1a8d6bdb9 [file] [log] [blame]
Nick Kledzik5fce8c42012-08-01 02:29:50 +00001//===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Nick Kledzik5fce8c42012-08-01 02:29:50 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Utility for creating a in-memory buffer that will be written to a file.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruthd9903882015-01-14 11:23:27 +000013#include "llvm/Support/FileOutputBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000014#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/SmallString.h"
16#include "llvm/Support/Errc.h"
Rui Ueyamaa16fe652017-11-01 21:38:14 +000017#include "llvm/Support/Memory.h"
Rafael Espindolad4b24ed2017-01-09 21:52:35 +000018#include "llvm/Support/Path.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000019#include <system_error>
Nick Kledzik5fce8c42012-08-01 02:29:50 +000020
Rafael Espindola7eb1f182014-12-11 20:12:55 +000021#if !defined(_MSC_VER) && !defined(__MINGW32__)
22#include <unistd.h>
23#else
24#include <io.h>
25#endif
26
Rui Ueyamaa16fe652017-11-01 21:38:14 +000027using namespace llvm;
28using namespace llvm::sys;
Nick Kledzik5fce8c42012-08-01 02:29:50 +000029
Benjamin Kramer51ebcaa2017-11-24 14:55:41 +000030namespace {
Rui Ueyamaa16fe652017-11-01 21:38:14 +000031// 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().
34class OnDiskBuffer : public FileOutputBuffer {
35public:
Rafael Espindola58fe67a2017-11-13 18:33:44 +000036 OnDiskBuffer(StringRef Path, fs::TempFile Temp,
Rui Ueyamaa16fe652017-11-01 21:38:14 +000037 std::unique_ptr<fs::mapped_file_region> Buf)
Rafael Espindola58fe67a2017-11-13 18:33:44 +000038 : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {}
Nick Kledzik5fce8c42012-08-01 02:29:50 +000039
Rui Ueyamaa16fe652017-11-01 21:38:14 +000040 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();
Nick Kledzik5fce8c42012-08-01 02:29:50 +000044 }
45
Rui Ueyamaa16fe652017-11-01 21:38:14 +000046 size_t getBufferSize() const override { return Buffer->size(); }
47
Rafael Espindola0d7a38a2017-11-08 01:50:29 +000048 Error commit() override {
Rui Ueyamaa16fe652017-11-01 21:38:14 +000049 // 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.
Rafael Espindola58fe67a2017-11-13 18:33:44 +000053 return Temp.keep(FinalPath);
Rui Ueyamaa16fe652017-11-01 21:38:14 +000054 }
55
56 ~OnDiskBuffer() override {
57 // Close the mapping before deleting the temp file, so that the removal
58 // succeeds.
59 Buffer.reset();
Rafael Espindola58fe67a2017-11-13 18:33:44 +000060 consumeError(Temp.discard());
Rui Ueyamaa16fe652017-11-01 21:38:14 +000061 }
62
Martin Storsjo4153e9f2018-08-24 18:36:22 +000063 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
Rui Ueyamaa16fe652017-11-01 21:38:14 +000069private:
70 std::unique_ptr<fs::mapped_file_region> Buffer;
Rafael Espindola58fe67a2017-11-13 18:33:44 +000071 fs::TempFile Temp;
Rui Ueyamaa16fe652017-11-01 21:38:14 +000072};
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.
76class InMemoryBuffer : public FileOutputBuffer {
77public:
Lang Hames93d2bdd2019-05-20 20:53:05 +000078 InMemoryBuffer(StringRef Path, MemoryBlock Buf, std::size_t BufSize,
79 unsigned Mode)
80 : FileOutputBuffer(Path), Buffer(Buf), BufferSize(BufSize),
81 Mode(Mode) {}
Rui Ueyamaa16fe652017-11-01 21:38:14 +000082
Rui Ueyamaa16fe652017-11-01 21:38:14 +000083 uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }
84
85 uint8_t *getBufferEnd() const override {
Lang Hames93d2bdd2019-05-20 20:53:05 +000086 return (uint8_t *)Buffer.base() + BufferSize;
Rui Ueyamaa16fe652017-11-01 21:38:14 +000087 }
88
Lang Hames93d2bdd2019-05-20 20:53:05 +000089 size_t getBufferSize() const override { return BufferSize; }
Rui Ueyamaa16fe652017-11-01 21:38:14 +000090
Rafael Espindola0d7a38a2017-11-08 01:50:29 +000091 Error commit() override {
Rui Ueyama4063cfc2019-01-22 18:44:04 +000092 if (FinalPath == "-") {
Lang Hames93d2bdd2019-05-20 20:53:05 +000093 llvm::outs() << StringRef((const char *)Buffer.base(), BufferSize);
Rui Ueyama4063cfc2019-01-22 18:44:04 +000094 llvm::outs().flush();
95 return Error::success();
96 }
97
Zachary Turner1f67a3c2018-06-07 19:58:58 +000098 using namespace sys::fs;
Rui Ueyamaa16fe652017-11-01 21:38:14 +000099 int FD;
100 std::error_code EC;
Zachary Turner154a72d2018-06-07 20:07:08 +0000101 if (auto EC =
102 openFileForWrite(FinalPath, FD, CD_CreateAlways, OF_None, Mode))
Rafael Espindola0d7a38a2017-11-08 01:50:29 +0000103 return errorCodeToError(EC);
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000104 raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true);
Lang Hames93d2bdd2019-05-20 20:53:05 +0000105 OS << StringRef((const char *)Buffer.base(), BufferSize);
Rafael Espindola0d7a38a2017-11-08 01:50:29 +0000106 return Error::success();
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000107 }
108
109private:
Lang Hames93d2bdd2019-05-20 20:53:05 +0000110 // Buffer may actually contain a larger memory block than BufferSize
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000111 OwningMemoryBlock Buffer;
Lang Hames93d2bdd2019-05-20 20:53:05 +0000112 size_t BufferSize;
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000113 unsigned Mode;
114};
Benjamin Kramer51ebcaa2017-11-24 14:55:41 +0000115} // namespace
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000116
Rui Ueyamaf6490e02017-11-08 22:57:48 +0000117static Expected<std::unique_ptr<InMemoryBuffer>>
118createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {
119 std::error_code EC;
120 MemoryBlock MB = Memory::allocateMappedMemory(
121 Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
122 if (EC)
123 return errorCodeToError(EC);
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000124 return std::make_unique<InMemoryBuffer>(Path, MB, Size, Mode);
Rui Ueyamaf6490e02017-11-08 22:57:48 +0000125}
126
Rui Ueyama21d451c2019-01-22 21:49:56 +0000127static Expected<std::unique_ptr<FileOutputBuffer>>
Rui Ueyama8e7600d2019-01-19 00:07:57 +0000128createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000129 Expected<fs::TempFile> FileOrErr =
130 fs::TempFile::create(Path + ".tmp%%%%%%%", Mode);
131 if (!FileOrErr)
132 return FileOrErr.takeError();
133 fs::TempFile File = std::move(*FileOrErr);
Rafael Espindola7dbb5772015-09-18 15:17:53 +0000134
Nico Weber712e8d22018-04-29 00:45:03 +0000135#ifndef _WIN32
Rui Ueyama8e7600d2019-01-19 00:07:57 +0000136 // On Windows, CreateFileMapping (the mmap function on Windows)
137 // automatically extends the underlying file. We don't need to
138 // extend the file beforehand. _chsize (ftruncate on Windows) is
139 // pretty slow just like it writes specified amount of bytes,
140 // so we should avoid calling that function.
141 if (auto EC = fs::resize_file(File.FD, Size)) {
142 consumeError(File.discard());
143 return errorCodeToError(EC);
Zachary Turner1adca7c2018-06-28 18:49:09 +0000144 }
Rui Ueyama8e7600d2019-01-19 00:07:57 +0000145#endif
Rafael Espindolac69f13b2014-12-12 18:13:23 +0000146
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000147 // Mmap it.
148 std::error_code EC;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000149 auto MappedFile = std::make_unique<fs::mapped_file_region>(
Reid Klecknercc418a32019-07-10 00:34:13 +0000150 fs::convertFDToNativeFile(File.FD), fs::mapped_file_region::readwrite,
151 Size, 0, EC);
Rui Ueyama21d451c2019-01-22 21:49:56 +0000152
153 // mmap(2) can fail if the underlying filesystem does not support it.
154 // If that happens, we fall back to in-memory buffer as the last resort.
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000155 if (EC) {
156 consumeError(File.discard());
Rui Ueyama21d451c2019-01-22 21:49:56 +0000157 return createInMemoryBuffer(Path, Size, Mode);
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000158 }
Rui Ueyama21d451c2019-01-22 21:49:56 +0000159
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000160 return std::make_unique<OnDiskBuffer>(Path, std::move(File),
Rafael Espindola58fe67a2017-11-13 18:33:44 +0000161 std::move(MappedFile));
Michael J. Spencer7fe24f52012-12-03 22:09:52 +0000162}
Nick Kledzik5fce8c42012-08-01 02:29:50 +0000163
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000164// Create an instance of FileOutputBuffer.
Rafael Espindolae0df3572017-11-08 01:05:44 +0000165Expected<std::unique_ptr<FileOutputBuffer>>
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000166FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {
Rui Ueyama4063cfc2019-01-22 18:44:04 +0000167 // Handle "-" as stdout just like llvm::raw_ostream does.
168 if (Path == "-")
169 return createInMemoryBuffer("-", Size, /*Mode=*/0);
170
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000171 unsigned Mode = fs::all_read | fs::all_write;
172 if (Flags & F_executable)
173 Mode |= fs::all_exe;
Michael J. Spencer7fe24f52012-12-03 22:09:52 +0000174
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000175 fs::file_status Stat;
176 fs::status(Path, Stat);
177
178 // Usually, we want to create OnDiskBuffer to create a temporary file in
179 // the same directory as the destination file and atomically replaces it
180 // by rename(2).
181 //
182 // However, if the destination file is a special file, we don't want to
183 // use rename (e.g. we don't want to replace /dev/null with a regular
184 // file.) If that's the case, we create an in-memory buffer, open the
185 // destination file and write to it on commit().
186 switch (Stat.type()) {
187 case fs::file_type::directory_file:
Rafael Espindolae0df3572017-11-08 01:05:44 +0000188 return errorCodeToError(errc::is_a_directory);
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000189 case fs::file_type::regular_file:
190 case fs::file_type::file_not_found:
191 case fs::file_type::status_error:
Nick Terrell68142322019-10-29 15:46:22 -0700192 if (Flags & F_no_mmap)
193 return createInMemoryBuffer(Path, Size, Mode);
194 else
195 return createOnDiskBuffer(Path, Size, Mode);
Rui Ueyamaa16fe652017-11-01 21:38:14 +0000196 default:
Rui Ueyamaf6490e02017-11-08 22:57:48 +0000197 return createInMemoryBuffer(Path, Size, Mode);
Rafael Espindolad4b24ed2017-01-09 21:52:35 +0000198 }
Nick Kledzik5fce8c42012-08-01 02:29:50 +0000199}