FileOutputBuffer.cpp [plain text]
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
using llvm::sys::fs::mapped_file_region;
namespace llvm {
FileOutputBuffer::FileOutputBuffer(mapped_file_region * R,
StringRef Path, StringRef TmpPath)
: Region(R)
, FinalPath(Path)
, TempPath(TmpPath) {
}
FileOutputBuffer::~FileOutputBuffer() {
bool Existed;
sys::fs::remove(Twine(TempPath), Existed);
}
error_code FileOutputBuffer::create(StringRef FilePath,
size_t Size,
OwningPtr<FileOutputBuffer> &Result,
unsigned Flags) {
sys::fs::file_status Stat;
error_code EC = sys::fs::status(FilePath, Stat);
switch (Stat.type()) {
case sys::fs::file_type::file_not_found:
break;
case sys::fs::file_type::regular_file: {
}
break;
default:
if (EC)
return EC;
else
return make_error_code(errc::operation_not_permitted);
}
bool Existed;
EC = sys::fs::remove(FilePath, Existed);
if (EC)
return EC;
SmallString<128> TempFilePath;
int FD;
EC = sys::fs::unique_file(Twine(FilePath) + ".tmp%%%%%%%",
FD, TempFilePath, false, 0644);
if (EC)
return EC;
OwningPtr<mapped_file_region> MappedFile(
new mapped_file_region(FD, mapped_file_region::readwrite, Size, 0, EC));
if (EC)
return EC;
if ( Flags & F_executable ) {
sys::fs::file_status Stat2;
EC = sys::fs::status(Twine(TempFilePath), Stat2);
if (EC)
return EC;
sys::fs::perms new_perms = Stat2.permissions();
if ( new_perms & sys::fs::owner_read )
new_perms |= sys::fs::owner_exe;
if ( new_perms & sys::fs::group_read )
new_perms |= sys::fs::group_exe;
if ( new_perms & sys::fs::others_read )
new_perms |= sys::fs::others_exe;
new_perms |= sys::fs::add_perms;
EC = sys::fs::permissions(Twine(TempFilePath), new_perms);
if (EC)
return EC;
}
Result.reset(new FileOutputBuffer(MappedFile.get(), FilePath, TempFilePath));
if (Result)
MappedFile.take();
return error_code::success();
}
error_code FileOutputBuffer::commit(int64_t NewSmallerSize) {
Region.reset(0);
if ( NewSmallerSize != -1 ) {
error_code EC = sys::fs::resize_file(Twine(TempPath), NewSmallerSize);
if (EC)
return EC;
}
return sys::fs::rename(Twine(TempPath), Twine(FinalPath));
}
}