1 //===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Utility for creating a in-memory buffer that will be written to a file.
11 //
12 //===----------------------------------------------------------------------===//
13 
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 "llvm/Support/Path.h"
19 #include "llvm/Support/Signals.h"
20 #include <system_error>
21 
22 #if !defined(_MSC_VER) && !defined(__MINGW32__)
23 #include <unistd.h>
24 #else
25 #include <io.h>
26 #endif
27 
28 using llvm::sys::fs::mapped_file_region;
29 
30 namespace llvm {
31 FileOutputBuffer::FileOutputBuffer(std::unique_ptr<mapped_file_region> R,
32                                    StringRef Path, StringRef TmpPath,
33                                    bool IsRegular)
34     : Region(std::move(R)), FinalPath(Path), TempPath(TmpPath),
35       IsRegular(IsRegular) {}
36 
37 FileOutputBuffer::~FileOutputBuffer() {
38   // Close the mapping before deleting the temp file, so that the removal
39   // succeeds.
40   Region.reset();
41   sys::fs::remove(Twine(TempPath));
42 }
43 
44 ErrorOr<std::unique_ptr<FileOutputBuffer>>
45 FileOutputBuffer::create(StringRef FilePath, size_t Size, unsigned Flags) {
46   // Check file is not a regular file, in which case we cannot remove it.
47   sys::fs::file_status Stat;
48   std::error_code EC = sys::fs::status(FilePath, Stat);
49   bool IsRegular = true;
50   switch (Stat.type()) {
51     case sys::fs::file_type::file_not_found:
52       // If file does not exist, we'll create one.
53       break;
54     case sys::fs::file_type::regular_file: {
55         // If file is not currently writable, error out.
56         // FIXME: There is no sys::fs:: api for checking this.
57         // FIXME: In posix, you use the access() call to check this.
58       }
59       break;
60     case sys::fs::file_type::directory_file:
61       return errc::is_a_directory;
62     default:
63       if (EC)
64         return EC;
65       IsRegular = false;
66   }
67 
68   SmallString<128> TempFilePath;
69   int FD;
70   if (IsRegular) {
71     unsigned Mode = sys::fs::all_read | sys::fs::all_write;
72     // If requested, make the output file executable.
73     if (Flags & F_executable)
74       Mode |= sys::fs::all_exe;
75     // Create new file in same directory but with random name.
76     EC = sys::fs::createUniqueFile(Twine(FilePath) + ".tmp%%%%%%%", FD,
77                                    TempFilePath, Mode);
78   } else {
79     // Create a temporary file. Since this is a special file, we will not move
80     // it and the new file can be in another filesystem. This avoids trying to
81     // create a temporary file in /dev when outputting to /dev/null for example.
82     EC = sys::fs::createTemporaryFile(sys::path::filename(FilePath), "", FD,
83                                       TempFilePath);
84   }
85 
86   if (EC)
87     return EC;
88 
89   sys::RemoveFileOnSignal(TempFilePath);
90 
91 #ifndef LLVM_ON_WIN32
92   // On Windows, CreateFileMapping (the mmap function on Windows)
93   // automatically extends the underlying file. We don't need to
94   // extend the file beforehand. _chsize (ftruncate on Windows) is
95   // pretty slow just like it writes specified amount of bytes,
96   // so we should avoid calling that.
97   EC = sys::fs::resize_file(FD, Size);
98   if (EC)
99     return EC;
100 #endif
101 
102   auto MappedFile = llvm::make_unique<mapped_file_region>(
103       FD, mapped_file_region::readwrite, Size, 0, EC);
104   int Ret = close(FD);
105   if (EC)
106     return EC;
107   if (Ret)
108     return std::error_code(errno, std::generic_category());
109 
110   std::unique_ptr<FileOutputBuffer> Buf(new FileOutputBuffer(
111       std::move(MappedFile), FilePath, TempFilePath, IsRegular));
112   return std::move(Buf);
113 }
114 
115 std::error_code FileOutputBuffer::commit() {
116   // Unmap buffer, letting OS flush dirty pages to file on disk.
117   Region.reset();
118 
119   std::error_code EC;
120   if (IsRegular) {
121     // Atomically replace the existing file with the new one.
122     EC = sys::fs::rename(Twine(TempPath), Twine(FinalPath));
123     sys::DontRemoveFileOnSignal(TempPath);
124   } else {
125     EC = sys::fs::copy_file(TempPath, FinalPath);
126     std::error_code RMEC = sys::fs::remove(TempPath);
127     sys::DontRemoveFileOnSignal(TempPath);
128     if (RMEC)
129       return RMEC;
130   }
131 
132   return EC;
133 }
134 } // namespace
135