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/SmallVector.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/Support/system_error.h"
19 using llvm::sys::fs::mapped_file_region;
22 FileOutputBuffer::FileOutputBuffer(mapped_file_region * R,
23 StringRef Path, StringRef TmpPath)
29 FileOutputBuffer::~FileOutputBuffer() {
30 sys::fs::remove(Twine(TempPath));
33 error_code FileOutputBuffer::create(StringRef FilePath,
35 std::unique_ptr<FileOutputBuffer> &Result,
37 // If file already exists, it must be a regular file (to be mappable).
38 sys::fs::file_status Stat;
39 error_code EC = sys::fs::status(FilePath, Stat);
40 switch (Stat.type()) {
41 case sys::fs::file_type::file_not_found:
42 // If file does not exist, we'll create one.
44 case sys::fs::file_type::regular_file: {
45 // If file is not currently writable, error out.
46 // FIXME: There is no sys::fs:: api for checking this.
47 // FIXME: In posix, you use the access() call to check this.
54 return make_error_code(std::errc::operation_not_permitted);
57 // Delete target file.
58 EC = sys::fs::remove(FilePath);
62 unsigned Mode = sys::fs::all_read | sys::fs::all_write;
63 // If requested, make the output file executable.
64 if (Flags & F_executable)
65 Mode |= sys::fs::all_exe;
67 // Create new file in same directory but with random name.
68 SmallString<128> TempFilePath;
70 EC = sys::fs::createUniqueFile(Twine(FilePath) + ".tmp%%%%%%%", FD,
75 std::unique_ptr<mapped_file_region> MappedFile(new mapped_file_region(
76 FD, true, mapped_file_region::readwrite, Size, 0, EC));
80 Result.reset(new FileOutputBuffer(MappedFile.get(), FilePath, TempFilePath));
87 error_code FileOutputBuffer::commit(int64_t NewSmallerSize) {
88 // Unmap buffer, letting OS flush dirty pages to file on disk.
89 Region.reset(nullptr);
91 // If requested, resize file as part of commit.
92 if ( NewSmallerSize != -1 ) {
93 error_code EC = sys::fs::resize_file(Twine(TempPath), NewSmallerSize);
98 // Rename file to final name.
99 return sys::fs::rename(Twine(TempPath), Twine(FinalPath));