1 //===- FileOutputBuffer.cpp -----------------------------------------------===//
2 //
3 // The MCLinker Project
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 #include "mcld/Support/FileOutputBuffer.h"
10 #include "mcld/Support/FileHandle.h"
11 #include "mcld/Support/Path.h"
12
13 namespace mcld {
14
FileOutputBuffer(llvm::sys::fs::mapped_file_region * pRegion,FileHandle & pFileHandle)15 FileOutputBuffer::FileOutputBuffer(llvm::sys::fs::mapped_file_region* pRegion,
16 FileHandle& pFileHandle)
17 : m_pRegion(pRegion), m_FileHandle(pFileHandle) {
18 }
19
~FileOutputBuffer()20 FileOutputBuffer::~FileOutputBuffer() {
21 // Unmap buffer, letting OS flush dirty pages to file on disk.
22 m_pRegion.reset();
23 }
24
25 std::error_code
create(FileHandle & pFileHandle,size_t pSize,std::unique_ptr<FileOutputBuffer> & pResult)26 FileOutputBuffer::create(FileHandle& pFileHandle,
27 size_t pSize,
28 std::unique_ptr<FileOutputBuffer>& pResult) {
29 std::error_code ec;
30
31 // Resize the file before mapping the file region.
32 ec = llvm::sys::fs::resize_file(pFileHandle.handler(), pSize);
33 if (ec)
34 return ec;
35
36 std::unique_ptr<llvm::sys::fs::mapped_file_region> mapped_file(
37 new llvm::sys::fs::mapped_file_region(pFileHandle.handler(),
38 llvm::sys::fs::mapped_file_region::readwrite, pSize, 0, ec));
39 if (ec)
40 return ec;
41
42 pResult.reset(new FileOutputBuffer(mapped_file.get(), pFileHandle));
43 if (pResult)
44 mapped_file.release();
45
46 return std::error_code();
47 }
48
request(size_t pOffset,size_t pLength)49 MemoryRegion FileOutputBuffer::request(size_t pOffset, size_t pLength) {
50 if (pOffset > getBufferSize() || (pOffset + pLength) > getBufferSize())
51 return MemoryRegion();
52 return MemoryRegion(getBufferStart() + pOffset, pLength);
53 }
54
getPath() const55 llvm::StringRef FileOutputBuffer::getPath() const {
56 return m_FileHandle.path().native();
57 }
58
59 } // namespace mcld
60