1 //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Utility for creating a in-memory buffer that will be written to a file.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/FileOutputBuffer.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Support/Errc.h"
18 #include <system_error>
20 #if !defined(_MSC_VER) && !defined(__MINGW32__)
26 using llvm::sys::fs::mapped_file_region;
29 FileOutputBuffer::FileOutputBuffer(std::unique_ptr<mapped_file_region> R,
30 StringRef Path, StringRef TmpPath)
31 : Region(std::move(R)), FinalPath(Path), TempPath(TmpPath) {}
33 FileOutputBuffer::~FileOutputBuffer() {
34 sys::fs::remove(Twine(TempPath));
38 FileOutputBuffer::create(StringRef FilePath, size_t Size,
39 std::unique_ptr<FileOutputBuffer> &Result,
41 // If file already exists, it must be a regular file (to be mappable).
42 sys::fs::file_status Stat;
43 std::error_code EC = sys::fs::status(FilePath, Stat);
44 switch (Stat.type()) {
45 case sys::fs::file_type::file_not_found:
46 // If file does not exist, we'll create one.
48 case sys::fs::file_type::regular_file: {
49 // If file is not currently writable, error out.
50 // FIXME: There is no sys::fs:: api for checking this.
51 // FIXME: In posix, you use the access() call to check this.
58 return make_error_code(errc::operation_not_permitted);
61 // Delete target file.
62 EC = sys::fs::remove(FilePath);
66 unsigned Mode = sys::fs::all_read | sys::fs::all_write;
67 // If requested, make the output file executable.
68 if (Flags & F_executable)
69 Mode |= sys::fs::all_exe;
71 // Create new file in same directory but with random name.
72 SmallString<128> TempFilePath;
74 EC = sys::fs::createUniqueFile(Twine(FilePath) + ".tmp%%%%%%%", FD,
80 // On Windows, CreateFileMapping (the mmap function on Windows)
81 // automatically extends the underlying file. We don't need to
82 // extend the file beforehand. _chsize (ftruncate on Windows) is
83 // pretty slow just like it writes specified amount of bytes,
84 // so we should avoid calling that.
85 EC = sys::fs::resize_file(FD, Size);
90 auto MappedFile = llvm::make_unique<mapped_file_region>(
91 FD, mapped_file_region::readwrite, Size, 0, EC);
96 return std::error_code(errno, std::generic_category());
99 new FileOutputBuffer(std::move(MappedFile), FilePath, TempFilePath));
101 return std::error_code();
104 std::error_code FileOutputBuffer::commit() {
105 // Unmap buffer, letting OS flush dirty pages to file on disk.
109 // Rename file to final name.
110 return sys::fs::rename(Twine(TempPath), Twine(FinalPath));