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/Errc.h"
15 #include "llvm/Support/FileOutputBuffer.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include <system_error>
21 using llvm::sys::fs::mapped_file_region;
24 FileOutputBuffer::FileOutputBuffer(std::unique_ptr<mapped_file_region> R,
25 StringRef Path, StringRef TmpPath)
26 : Region(std::move(R)), FinalPath(Path), TempPath(TmpPath) {}
28 FileOutputBuffer::~FileOutputBuffer() {
29 sys::fs::remove(Twine(TempPath));
33 FileOutputBuffer::create(StringRef FilePath, size_t Size,
34 std::unique_ptr<FileOutputBuffer> &Result,
36 // If file already exists, it must be a regular file (to be mappable).
37 sys::fs::file_status Stat;
38 std::error_code EC = sys::fs::status(FilePath, Stat);
39 switch (Stat.type()) {
40 case sys::fs::file_type::file_not_found:
41 // If file does not exist, we'll create one.
43 case sys::fs::file_type::regular_file: {
44 // If file is not currently writable, error out.
45 // FIXME: There is no sys::fs:: api for checking this.
46 // FIXME: In posix, you use the access() call to check this.
53 return make_error_code(errc::operation_not_permitted);
56 // Delete target file.
57 EC = sys::fs::remove(FilePath);
61 unsigned Mode = sys::fs::all_read | sys::fs::all_write;
62 // If requested, make the output file executable.
63 if (Flags & F_executable)
64 Mode |= sys::fs::all_exe;
66 // Create new file in same directory but with random name.
67 SmallString<128> TempFilePath;
69 EC = sys::fs::createUniqueFile(Twine(FilePath) + ".tmp%%%%%%%", FD,
74 auto MappedFile = llvm::make_unique<mapped_file_region>(
75 FD, true, mapped_file_region::readwrite, Size, 0, EC);
80 new FileOutputBuffer(std::move(MappedFile), FilePath, TempFilePath));
82 return std::error_code();
85 std::error_code FileOutputBuffer::commit(int64_t NewSmallerSize) {
86 // Unmap buffer, letting OS flush dirty pages to file on disk.
89 // If requested, resize file as part of commit.
90 if ( NewSmallerSize != -1 ) {
91 std::error_code EC = sys::fs::resize_file(Twine(TempPath), NewSmallerSize);
96 // Rename file to final name.
97 return sys::fs::rename(Twine(TempPath), Twine(FinalPath));