]>
git.proxmox.com Git - rustc.git/blob - src/llvm/lib/Support/FileOutputBuffer.cpp
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/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Support/FileOutputBuffer.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include <system_error>
21 #if !defined(_MSC_VER) && !defined(__MINGW32__)
27 using llvm::sys::fs::mapped_file_region
;
30 FileOutputBuffer::FileOutputBuffer(std::unique_ptr
<mapped_file_region
> R
,
31 StringRef Path
, StringRef TmpPath
)
32 : Region(std::move(R
)), FinalPath(Path
), TempPath(TmpPath
) {}
34 FileOutputBuffer::~FileOutputBuffer() {
35 sys::fs::remove(Twine(TempPath
));
39 FileOutputBuffer::create(StringRef FilePath
, size_t Size
,
40 std::unique_ptr
<FileOutputBuffer
> &Result
,
42 // If file already exists, it must be a regular file (to be mappable).
43 sys::fs::file_status Stat
;
44 std::error_code EC
= sys::fs::status(FilePath
, Stat
);
45 switch (Stat
.type()) {
46 case sys::fs::file_type::file_not_found
:
47 // If file does not exist, we'll create one.
49 case sys::fs::file_type::regular_file
: {
50 // If file is not currently writable, error out.
51 // FIXME: There is no sys::fs:: api for checking this.
52 // FIXME: In posix, you use the access() call to check this.
59 return make_error_code(errc::operation_not_permitted
);
62 // Delete target file.
63 EC
= sys::fs::remove(FilePath
);
67 unsigned Mode
= sys::fs::all_read
| sys::fs::all_write
;
68 // If requested, make the output file executable.
69 if (Flags
& F_executable
)
70 Mode
|= sys::fs::all_exe
;
72 // Create new file in same directory but with random name.
73 SmallString
<128> TempFilePath
;
75 EC
= sys::fs::createUniqueFile(Twine(FilePath
) + ".tmp%%%%%%%", FD
,
80 EC
= sys::fs::resize_file(FD
, Size
);
84 auto MappedFile
= llvm::make_unique
<mapped_file_region
>(
85 FD
, mapped_file_region::readwrite
, Size
, 0, EC
);
90 return std::error_code(errno
, std::generic_category());
93 new FileOutputBuffer(std::move(MappedFile
), FilePath
, TempFilePath
));
95 return std::error_code();
98 std::error_code
FileOutputBuffer::commit() {
99 // Unmap buffer, letting OS flush dirty pages to file on disk.
103 // Rename file to final name.
104 return sys::fs::rename(Twine(TempPath
), Twine(FinalPath
));