LLVM  6.0.0svn
FileOutputBuffer.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/Memory.h"
19 #include "llvm/Support/Path.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 namespace llvm;
29 using namespace llvm::sys;
30 
31 // 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().
35 public:
37  std::unique_ptr<fs::mapped_file_region> Buf)
38  : FileOutputBuffer(Path), Buffer(std::move(Buf)), Temp(std::move(Temp)) {}
39 
40  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();
44  }
45 
46  size_t getBufferSize() const override { return Buffer->size(); }
47 
48  Error commit() override {
49  // 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.
53  return Temp.keep(FinalPath);
54  }
55 
56  ~OnDiskBuffer() override {
57  // Close the mapping before deleting the temp file, so that the removal
58  // succeeds.
59  Buffer.reset();
60  consumeError(Temp.discard());
61  }
62 
63 private:
64  std::unique_ptr<fs::mapped_file_region> Buffer;
65  fs::TempFile Temp;
66 };
67 
68 // A FileOutputBuffer which keeps data in memory and writes to the final
69 // output file on commit(). This is used only when we cannot use OnDiskBuffer.
71 public:
73  : FileOutputBuffer(Path), Buffer(Buf), Mode(Mode) {}
74 
75  uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }
76 
77  uint8_t *getBufferEnd() const override {
78  return (uint8_t *)Buffer.base() + Buffer.size();
79  }
80 
81  size_t getBufferSize() const override { return Buffer.size(); }
82 
83  Error commit() override {
84  int FD;
85  std::error_code EC;
86  if (auto EC = openFileForWrite(FinalPath, FD, fs::F_None, Mode))
87  return errorCodeToError(EC);
88  raw_fd_ostream OS(FD, /*shouldClose=*/true, /*unbuffered=*/true);
89  OS << StringRef((const char *)Buffer.base(), Buffer.size());
90  return Error::success();
91  }
92 
93 private:
94  OwningMemoryBlock Buffer;
95  unsigned Mode;
96 };
97 
99 createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {
100  std::error_code EC;
102  Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);
103  if (EC)
104  return errorCodeToError(EC);
105  return llvm::make_unique<InMemoryBuffer>(Path, MB, Mode);
106 }
107 
109 createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {
110  Expected<fs::TempFile> FileOrErr =
111  fs::TempFile::create(Path + ".tmp%%%%%%%", Mode);
112  if (!FileOrErr)
113  return FileOrErr.takeError();
114  fs::TempFile File = std::move(*FileOrErr);
115 
116 #ifndef LLVM_ON_WIN32
117  // On Windows, CreateFileMapping (the mmap function on Windows)
118  // automatically extends the underlying file. We don't need to
119  // extend the file beforehand. _chsize (ftruncate on Windows) is
120  // pretty slow just like it writes specified amount of bytes,
121  // so we should avoid calling that function.
122  if (auto EC = fs::resize_file(File.FD, Size)) {
123  consumeError(File.discard());
124  return errorCodeToError(EC);
125  }
126 #endif
127 
128  // Mmap it.
129  std::error_code EC;
130  auto MappedFile = llvm::make_unique<fs::mapped_file_region>(
132  if (EC) {
133  consumeError(File.discard());
134  return errorCodeToError(EC);
135  }
136  return llvm::make_unique<OnDiskBuffer>(Path, std::move(File),
137  std::move(MappedFile));
138 }
139 
140 // Create an instance of FileOutputBuffer.
142 FileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {
143  unsigned Mode = fs::all_read | fs::all_write;
144  if (Flags & F_executable)
145  Mode |= fs::all_exe;
146 
147  fs::file_status Stat;
148  fs::status(Path, Stat);
149 
150  // Usually, we want to create OnDiskBuffer to create a temporary file in
151  // the same directory as the destination file and atomically replaces it
152  // by rename(2).
153  //
154  // However, if the destination file is a special file, we don't want to
155  // use rename (e.g. we don't want to replace /dev/null with a regular
156  // file.) If that's the case, we create an in-memory buffer, open the
157  // destination file and write to it on commit().
158  switch (Stat.type()) {
164  return createOnDiskBuffer(Path, Size, Mode);
165  default:
166  return createInMemoryBuffer(Path, Size, Mode);
167  }
168 }
uint8_t * getBufferEnd() const override
Returns a pointer to the end of the buffer.
SI Whole Quad Mode
static Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
size_t getBufferSize() const override
Returns size of the buffer.
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
static Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Definition: Path.cpp:830
Represents the result of a call to sys::fs::status().
Definition: FileSystem.h:219
static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e...
Definition: BitVector.h:920
Represents a temporary file.
Definition: FileSystem.h:705
FileOutputBuffer - This interface provides simple way to create an in-memory buffer which will be wri...
uint8_t * getBufferEnd() const override
Returns a pointer to the end of the buffer.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
May access map via data and modify it. Written to path.
Definition: FileSystem.h:809
~OnDiskBuffer() override
static Expected< std::unique_ptr< OnDiskBuffer > > createOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode)
Error commit() override
Flushes the content of the buffer to its file and deallocates the buffer.
size_t getBufferSize() const override
Returns size of the buffer.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
OnDiskBuffer(StringRef Path, fs::TempFile Temp, std::unique_ptr< fs::mapped_file_region > Buf)
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
static Expected< std::unique_ptr< InMemoryBuffer > > createInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode)
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:962
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
This class encapsulates the notion of a memory block which has an address and a size.
Definition: Memory.h:29
Owning version of MemoryBlock.
Definition: Memory.h:119
uint8_t * getBufferStart() const override
Returns a pointer to the start of the buffer.
InMemoryBuffer(StringRef Path, MemoryBlock Buf, unsigned Mode)
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:361
uint8_t * getBufferStart() const override
Returns a pointer to the start of the buffer.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
Error commit() override
Flushes the content of the buffer to its file and deallocates the buffer.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)