1f22ef01cSRoman Divacky //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the MemoryBuffer interface.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky
14f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h"
15f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h"
16dff0c46cSDimitry Andric #include "llvm/Config/config.h"
1791bc56edSDimitry Andric #include "llvm/Support/Errc.h"
182754fe60SDimitry Andric #include "llvm/Support/Errno.h"
197ae0e2c9SDimitry Andric #include "llvm/Support/FileSystem.h"
20139f7f9bSDimitry Andric #include "llvm/Support/MathExtras.h"
212754fe60SDimitry Andric #include "llvm/Support/Path.h"
222754fe60SDimitry Andric #include "llvm/Support/Process.h"
232754fe60SDimitry Andric #include "llvm/Support/Program.h"
24*4ba319b5SDimitry Andric #include "llvm/Support/SmallVectorMemoryBuffer.h"
25f22ef01cSRoman Divacky #include <cassert>
26139f7f9bSDimitry Andric #include <cerrno>
27f22ef01cSRoman Divacky #include <cstring>
282754fe60SDimitry Andric #include <new>
29139f7f9bSDimitry Andric #include <sys/types.h>
3091bc56edSDimitry Andric #include <system_error>
31f22ef01cSRoman Divacky #if !defined(_MSC_VER) && !defined(__MINGW32__)
32f22ef01cSRoman Divacky #include <unistd.h>
33f22ef01cSRoman Divacky #else
34f22ef01cSRoman Divacky #include <io.h>
35f22ef01cSRoman Divacky #endif
36f22ef01cSRoman Divacky using namespace llvm;
37f22ef01cSRoman Divacky
38f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
39f22ef01cSRoman Divacky // MemoryBuffer implementation itself.
40f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
41f22ef01cSRoman Divacky
~MemoryBuffer()42ffd1746dSEd Schouten MemoryBuffer::~MemoryBuffer() { }
43f22ef01cSRoman Divacky
44f22ef01cSRoman Divacky /// init - Initialize this MemoryBuffer as a reference to externally allocated
45f22ef01cSRoman Divacky /// memory, memory that we know is already null terminated.
init(const char * BufStart,const char * BufEnd,bool RequiresNullTerminator)463b0f4066SDimitry Andric void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
473b0f4066SDimitry Andric bool RequiresNullTerminator) {
483b0f4066SDimitry Andric assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
493b0f4066SDimitry Andric "Buffer is not null terminated!");
50f22ef01cSRoman Divacky BufferStart = BufStart;
51f22ef01cSRoman Divacky BufferEnd = BufEnd;
52f22ef01cSRoman Divacky }
53f22ef01cSRoman Divacky
54f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
55f22ef01cSRoman Divacky // MemoryBufferMem implementation.
56f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
57f22ef01cSRoman Divacky
58ffd1746dSEd Schouten /// CopyStringRef - Copies contents of a StringRef into a block of memory and
59ffd1746dSEd Schouten /// null-terminates it.
CopyStringRef(char * Memory,StringRef Data)60ffd1746dSEd Schouten static void CopyStringRef(char *Memory, StringRef Data) {
61b6c25e0eSDimitry Andric if (!Data.empty())
62ffd1746dSEd Schouten memcpy(Memory, Data.data(), Data.size());
63ffd1746dSEd Schouten Memory[Data.size()] = 0; // Null terminate string.
64ffd1746dSEd Schouten }
65ffd1746dSEd Schouten
66139f7f9bSDimitry Andric namespace {
67139f7f9bSDimitry Andric struct NamedBufferAlloc {
6839d628a0SDimitry Andric const Twine &Name;
NamedBufferAlloc__anoncca12af40111::NamedBufferAlloc6939d628a0SDimitry Andric NamedBufferAlloc(const Twine &Name) : Name(Name) {}
70139f7f9bSDimitry Andric };
71139f7f9bSDimitry Andric }
72139f7f9bSDimitry Andric
operator new(size_t N,const NamedBufferAlloc & Alloc)73139f7f9bSDimitry Andric void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
7439d628a0SDimitry Andric SmallString<256> NameBuf;
7539d628a0SDimitry Andric StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
7639d628a0SDimitry Andric
7739d628a0SDimitry Andric char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
7839d628a0SDimitry Andric CopyStringRef(Mem + N, NameRef);
79139f7f9bSDimitry Andric return Mem;
80ffd1746dSEd Schouten }
81ffd1746dSEd Schouten
82f22ef01cSRoman Divacky namespace {
83ffd1746dSEd Schouten /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
84da09e106SDimitry Andric template<typename MB>
85da09e106SDimitry Andric class MemoryBufferMem : public MB {
86f22ef01cSRoman Divacky public:
MemoryBufferMem(StringRef InputData,bool RequiresNullTerminator)873b0f4066SDimitry Andric MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
88da09e106SDimitry Andric MemoryBuffer::init(InputData.begin(), InputData.end(),
89da09e106SDimitry Andric RequiresNullTerminator);
90f22ef01cSRoman Divacky }
91f22ef01cSRoman Divacky
923ca95b02SDimitry Andric /// Disable sized deallocation for MemoryBufferMem, because it has
933ca95b02SDimitry Andric /// tail-allocated data.
operator delete(void * p)943ca95b02SDimitry Andric void operator delete(void *p) { ::operator delete(p); }
953ca95b02SDimitry Andric
getBufferIdentifier() const96d88c1a5aSDimitry Andric StringRef getBufferIdentifier() const override {
97ffd1746dSEd Schouten // The name is stored after the class itself.
98d88c1a5aSDimitry Andric return StringRef(reinterpret_cast<const char *>(this + 1));
99f22ef01cSRoman Divacky }
1003b0f4066SDimitry Andric
getBufferKind() const101da09e106SDimitry Andric MemoryBuffer::BufferKind getBufferKind() const override {
102da09e106SDimitry Andric return MemoryBuffer::MemoryBuffer_Malloc;
1033b0f4066SDimitry Andric }
104f22ef01cSRoman Divacky };
1053dac3a9bSDimitry Andric }
106f22ef01cSRoman Divacky
107da09e106SDimitry Andric template <typename MB>
108da09e106SDimitry Andric static ErrorOr<std::unique_ptr<MB>>
10939d628a0SDimitry Andric getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
1107a7e6055SDimitry Andric uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile);
11139d628a0SDimitry Andric
11239d628a0SDimitry Andric std::unique_ptr<MemoryBuffer>
getMemBuffer(StringRef InputData,StringRef BufferName,bool RequiresNullTerminator)11339d628a0SDimitry Andric MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
1143b0f4066SDimitry Andric bool RequiresNullTerminator) {
11539d628a0SDimitry Andric auto *Ret = new (NamedBufferAlloc(BufferName))
116da09e106SDimitry Andric MemoryBufferMem<MemoryBuffer>(InputData, RequiresNullTerminator);
11739d628a0SDimitry Andric return std::unique_ptr<MemoryBuffer>(Ret);
118f22ef01cSRoman Divacky }
119f22ef01cSRoman Divacky
12039d628a0SDimitry Andric std::unique_ptr<MemoryBuffer>
getMemBuffer(MemoryBufferRef Ref,bool RequiresNullTerminator)12139d628a0SDimitry Andric MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
12239d628a0SDimitry Andric return std::unique_ptr<MemoryBuffer>(getMemBuffer(
12339d628a0SDimitry Andric Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
12439d628a0SDimitry Andric }
12539d628a0SDimitry Andric
126da09e106SDimitry Andric static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
getMemBufferCopyImpl(StringRef InputData,const Twine & BufferName)127da09e106SDimitry Andric getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) {
128da09e106SDimitry Andric auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(InputData.size(), BufferName);
12939d628a0SDimitry Andric if (!Buf)
130da09e106SDimitry Andric return make_error_code(errc::not_enough_memory);
131da09e106SDimitry Andric memcpy(Buf->getBufferStart(), InputData.data(), InputData.size());
132da09e106SDimitry Andric return std::move(Buf);
133f22ef01cSRoman Divacky }
134f22ef01cSRoman Divacky
13539d628a0SDimitry Andric std::unique_ptr<MemoryBuffer>
getMemBufferCopy(StringRef InputData,const Twine & BufferName)136da09e106SDimitry Andric MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
137da09e106SDimitry Andric auto Buf = getMemBufferCopyImpl(InputData, BufferName);
138da09e106SDimitry Andric if (Buf)
139da09e106SDimitry Andric return std::move(*Buf);
14039d628a0SDimitry Andric return nullptr;
141f22ef01cSRoman Divacky }
142f22ef01cSRoman Divacky
14391bc56edSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getFileOrSTDIN(const Twine & Filename,int64_t FileSize,bool RequiresNullTerminator)1447d523365SDimitry Andric MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
1457d523365SDimitry Andric bool RequiresNullTerminator) {
14639d628a0SDimitry Andric SmallString<256> NameBuf;
14739d628a0SDimitry Andric StringRef NameRef = Filename.toStringRef(NameBuf);
14839d628a0SDimitry Andric
14939d628a0SDimitry Andric if (NameRef == "-")
15091bc56edSDimitry Andric return getSTDIN();
1517d523365SDimitry Andric return getFile(Filename, FileSize, RequiresNullTerminator);
152ffd1746dSEd Schouten }
153ffd1746dSEd Schouten
15439d628a0SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getFileSlice(const Twine & FilePath,uint64_t MapSize,uint64_t Offset,bool IsVolatile)15539d628a0SDimitry Andric MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
1567a7e6055SDimitry Andric uint64_t Offset, bool IsVolatile) {
157da09e106SDimitry Andric return getFileAux<MemoryBuffer>(FilePath, -1, MapSize, Offset, false,
158da09e106SDimitry Andric IsVolatile);
15939d628a0SDimitry Andric }
16039d628a0SDimitry Andric
161f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
162f22ef01cSRoman Divacky // MemoryBuffer::getFile implementation.
163f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
164f22ef01cSRoman Divacky
165f22ef01cSRoman Divacky namespace {
166*4ba319b5SDimitry Andric /// Memory maps a file descriptor using sys::fs::mapped_file_region.
167139f7f9bSDimitry Andric ///
168139f7f9bSDimitry Andric /// This handles converting the offset into a legal offset on the platform.
169da09e106SDimitry Andric template<typename MB>
170da09e106SDimitry Andric class MemoryBufferMMapFile : public MB {
171139f7f9bSDimitry Andric sys::fs::mapped_file_region MFR;
172139f7f9bSDimitry Andric
getLegalMapOffset(uint64_t Offset)173139f7f9bSDimitry Andric static uint64_t getLegalMapOffset(uint64_t Offset) {
174139f7f9bSDimitry Andric return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
175139f7f9bSDimitry Andric }
176139f7f9bSDimitry Andric
getLegalMapSize(uint64_t Len,uint64_t Offset)177139f7f9bSDimitry Andric static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
178139f7f9bSDimitry Andric return Len + (Offset - getLegalMapOffset(Offset));
179139f7f9bSDimitry Andric }
180139f7f9bSDimitry Andric
getStart(uint64_t Len,uint64_t Offset)181139f7f9bSDimitry Andric const char *getStart(uint64_t Len, uint64_t Offset) {
182139f7f9bSDimitry Andric return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
183139f7f9bSDimitry Andric }
184139f7f9bSDimitry Andric
185f22ef01cSRoman Divacky public:
MemoryBufferMMapFile(bool RequiresNullTerminator,int FD,uint64_t Len,uint64_t Offset,std::error_code & EC)186139f7f9bSDimitry Andric MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
18739d628a0SDimitry Andric uint64_t Offset, std::error_code &EC)
188*4ba319b5SDimitry Andric : MFR(FD, MB::Mapmode, getLegalMapSize(Len, Offset),
189*4ba319b5SDimitry Andric getLegalMapOffset(Offset), EC) {
190139f7f9bSDimitry Andric if (!EC) {
191139f7f9bSDimitry Andric const char *Start = getStart(Len, Offset);
192da09e106SDimitry Andric MemoryBuffer::init(Start, Start + Len, RequiresNullTerminator);
193139f7f9bSDimitry Andric }
194139f7f9bSDimitry Andric }
195f22ef01cSRoman Divacky
1963ca95b02SDimitry Andric /// Disable sized deallocation for MemoryBufferMMapFile, because it has
1973ca95b02SDimitry Andric /// tail-allocated data.
operator delete(void * p)1983ca95b02SDimitry Andric void operator delete(void *p) { ::operator delete(p); }
1993ca95b02SDimitry Andric
getBufferIdentifier() const200d88c1a5aSDimitry Andric StringRef getBufferIdentifier() const override {
201139f7f9bSDimitry Andric // The name is stored after the class itself.
202d88c1a5aSDimitry Andric return StringRef(reinterpret_cast<const char *>(this + 1));
2033b0f4066SDimitry Andric }
2043b0f4066SDimitry Andric
getBufferKind() const205da09e106SDimitry Andric MemoryBuffer::BufferKind getBufferKind() const override {
206da09e106SDimitry Andric return MemoryBuffer::MemoryBuffer_MMap;
207f22ef01cSRoman Divacky }
208f22ef01cSRoman Divacky };
2093dac3a9bSDimitry Andric }
210f22ef01cSRoman Divacky
211da09e106SDimitry Andric static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
getMemoryBufferForStream(int FD,const Twine & BufferName)21239d628a0SDimitry Andric getMemoryBufferForStream(int FD, const Twine &BufferName) {
2133861d79fSDimitry Andric const ssize_t ChunkSize = 4096*4;
2143861d79fSDimitry Andric SmallString<ChunkSize> Buffer;
2153861d79fSDimitry Andric ssize_t ReadBytes;
2163861d79fSDimitry Andric // Read into Buffer until we hit EOF.
2173861d79fSDimitry Andric do {
2183861d79fSDimitry Andric Buffer.reserve(Buffer.size() + ChunkSize);
219*4ba319b5SDimitry Andric ReadBytes = sys::RetryAfterSignal(-1, ::read, FD, Buffer.end(), ChunkSize);
220a580b014SDimitry Andric if (ReadBytes == -1)
22191bc56edSDimitry Andric return std::error_code(errno, std::generic_category());
2223861d79fSDimitry Andric Buffer.set_size(Buffer.size() + ReadBytes);
2233861d79fSDimitry Andric } while (ReadBytes != 0);
2243861d79fSDimitry Andric
225da09e106SDimitry Andric return getMemBufferCopyImpl(Buffer, BufferName);
2263861d79fSDimitry Andric }
2273861d79fSDimitry Andric
228f785676fSDimitry Andric
22991bc56edSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getFile(const Twine & Filename,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)23039d628a0SDimitry Andric MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
2317a7e6055SDimitry Andric bool RequiresNullTerminator, bool IsVolatile) {
232da09e106SDimitry Andric return getFileAux<MemoryBuffer>(Filename, FileSize, FileSize, 0,
2337a7e6055SDimitry Andric RequiresNullTerminator, IsVolatile);
234ffd1746dSEd Schouten }
235ffd1746dSEd Schouten
236da09e106SDimitry Andric template <typename MB>
237da09e106SDimitry Andric static ErrorOr<std::unique_ptr<MB>>
23839d628a0SDimitry Andric getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
23991bc56edSDimitry Andric uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
2407a7e6055SDimitry Andric bool IsVolatile);
241f785676fSDimitry Andric
242da09e106SDimitry Andric template <typename MB>
243da09e106SDimitry Andric static ErrorOr<std::unique_ptr<MB>>
getFileAux(const Twine & Filename,int64_t FileSize,uint64_t MapSize,uint64_t Offset,bool RequiresNullTerminator,bool IsVolatile)24439d628a0SDimitry Andric getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
2457a7e6055SDimitry Andric uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile) {
246f785676fSDimitry Andric int FD;
247*4ba319b5SDimitry Andric std::error_code EC = sys::fs::openFileForRead(Filename, FD, sys::fs::OF_None);
248da09e106SDimitry Andric
249f785676fSDimitry Andric if (EC)
250f785676fSDimitry Andric return EC;
2517ae0e2c9SDimitry Andric
252da09e106SDimitry Andric auto Ret = getOpenFileImpl<MB>(FD, Filename, FileSize, MapSize, Offset,
2537a7e6055SDimitry Andric RequiresNullTerminator, IsVolatile);
2542754fe60SDimitry Andric close(FD);
25591bc56edSDimitry Andric return Ret;
2562754fe60SDimitry Andric }
257f22ef01cSRoman Divacky
258da09e106SDimitry Andric ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
getFile(const Twine & Filename,int64_t FileSize,bool IsVolatile)259da09e106SDimitry Andric WritableMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
260da09e106SDimitry Andric bool IsVolatile) {
261da09e106SDimitry Andric return getFileAux<WritableMemoryBuffer>(Filename, FileSize, FileSize, 0,
262da09e106SDimitry Andric /*RequiresNullTerminator*/ false,
263da09e106SDimitry Andric IsVolatile);
264da09e106SDimitry Andric }
265da09e106SDimitry Andric
266da09e106SDimitry Andric ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
getFileSlice(const Twine & Filename,uint64_t MapSize,uint64_t Offset,bool IsVolatile)267da09e106SDimitry Andric WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
268da09e106SDimitry Andric uint64_t Offset, bool IsVolatile) {
269da09e106SDimitry Andric return getFileAux<WritableMemoryBuffer>(Filename, -1, MapSize, Offset, false,
270da09e106SDimitry Andric IsVolatile);
271da09e106SDimitry Andric }
272da09e106SDimitry Andric
273da09e106SDimitry Andric std::unique_ptr<WritableMemoryBuffer>
getNewUninitMemBuffer(size_t Size,const Twine & BufferName)274da09e106SDimitry Andric WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
275da09e106SDimitry Andric using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>;
276da09e106SDimitry Andric // Allocate space for the MemoryBuffer, the data and the name. It is important
277da09e106SDimitry Andric // that MemoryBuffer and data are aligned so PointerIntPair works with them.
278da09e106SDimitry Andric // TODO: Is 16-byte alignment enough? We copy small object files with large
279da09e106SDimitry Andric // alignment expectations into this buffer.
280da09e106SDimitry Andric SmallString<256> NameBuf;
281da09e106SDimitry Andric StringRef NameRef = BufferName.toStringRef(NameBuf);
282da09e106SDimitry Andric size_t AlignedStringLen = alignTo(sizeof(MemBuffer) + NameRef.size() + 1, 16);
283da09e106SDimitry Andric size_t RealLen = AlignedStringLen + Size + 1;
284da09e106SDimitry Andric char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
285da09e106SDimitry Andric if (!Mem)
286da09e106SDimitry Andric return nullptr;
287da09e106SDimitry Andric
288da09e106SDimitry Andric // The name is stored after the class itself.
289da09e106SDimitry Andric CopyStringRef(Mem + sizeof(MemBuffer), NameRef);
290da09e106SDimitry Andric
291da09e106SDimitry Andric // The buffer begins after the name and must be aligned.
292da09e106SDimitry Andric char *Buf = Mem + AlignedStringLen;
293da09e106SDimitry Andric Buf[Size] = 0; // Null terminate buffer.
294da09e106SDimitry Andric
295da09e106SDimitry Andric auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true);
296da09e106SDimitry Andric return std::unique_ptr<WritableMemoryBuffer>(Ret);
297da09e106SDimitry Andric }
298da09e106SDimitry Andric
299*4ba319b5SDimitry Andric std::unique_ptr<WritableMemoryBuffer>
getNewMemBuffer(size_t Size,const Twine & BufferName)300*4ba319b5SDimitry Andric WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) {
301*4ba319b5SDimitry Andric auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName);
302*4ba319b5SDimitry Andric if (!SB)
303*4ba319b5SDimitry Andric return nullptr;
304*4ba319b5SDimitry Andric memset(SB->getBufferStart(), 0, Size);
305*4ba319b5SDimitry Andric return SB;
306*4ba319b5SDimitry Andric }
307*4ba319b5SDimitry Andric
shouldUseMmap(int FD,size_t FileSize,size_t MapSize,off_t Offset,bool RequiresNullTerminator,int PageSize,bool IsVolatile)3083b0f4066SDimitry Andric static bool shouldUseMmap(int FD,
3093b0f4066SDimitry Andric size_t FileSize,
3103b0f4066SDimitry Andric size_t MapSize,
3113b0f4066SDimitry Andric off_t Offset,
3123b0f4066SDimitry Andric bool RequiresNullTerminator,
31391bc56edSDimitry Andric int PageSize,
3147a7e6055SDimitry Andric bool IsVolatile) {
31591bc56edSDimitry Andric // mmap may leave the buffer without null terminator if the file size changed
31691bc56edSDimitry Andric // by the time the last page is mapped in, so avoid it if the file size is
31791bc56edSDimitry Andric // likely to change.
3187a7e6055SDimitry Andric if (IsVolatile)
31991bc56edSDimitry Andric return false;
32091bc56edSDimitry Andric
3213b0f4066SDimitry Andric // We don't use mmap for small files because this can severely fragment our
3223b0f4066SDimitry Andric // address space.
323f785676fSDimitry Andric if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
3243b0f4066SDimitry Andric return false;
3253b0f4066SDimitry Andric
3263b0f4066SDimitry Andric if (!RequiresNullTerminator)
3273b0f4066SDimitry Andric return true;
3283b0f4066SDimitry Andric
329f22ef01cSRoman Divacky // If we don't know the file size, use fstat to find out. fstat on an open
330f22ef01cSRoman Divacky // file descriptor is cheaper than stat on a random path.
3313b0f4066SDimitry Andric // FIXME: this chunk of code is duplicated, but it avoids a fstat when
3323b0f4066SDimitry Andric // RequiresNullTerminator = false and MapSize != -1.
3333b0f4066SDimitry Andric if (FileSize == size_t(-1)) {
334f785676fSDimitry Andric sys::fs::file_status Status;
33591bc56edSDimitry Andric if (sys::fs::status(FD, Status))
33691bc56edSDimitry Andric return false;
337f785676fSDimitry Andric FileSize = Status.getSize();
338f22ef01cSRoman Divacky }
339f22ef01cSRoman Divacky
3403b0f4066SDimitry Andric // If we need a null terminator and the end of the map is inside the file,
3413b0f4066SDimitry Andric // we cannot use mmap.
3423b0f4066SDimitry Andric size_t End = Offset + MapSize;
3433b0f4066SDimitry Andric assert(End <= FileSize);
3443b0f4066SDimitry Andric if (End != FileSize)
3453b0f4066SDimitry Andric return false;
346f22ef01cSRoman Divacky
3473b0f4066SDimitry Andric // Don't try to map files that are exactly a multiple of the system page size
3483b0f4066SDimitry Andric // if we need a null terminator.
3493b0f4066SDimitry Andric if ((FileSize & (PageSize -1)) == 0)
3503b0f4066SDimitry Andric return false;
3513b0f4066SDimitry Andric
35239d628a0SDimitry Andric #if defined(__CYGWIN__)
35339d628a0SDimitry Andric // Don't try to map files that are exactly a multiple of the physical page size
35439d628a0SDimitry Andric // if we need a null terminator.
35539d628a0SDimitry Andric // FIXME: We should reorganize again getPageSize() on Win32.
35639d628a0SDimitry Andric if ((FileSize & (4096 - 1)) == 0)
35739d628a0SDimitry Andric return false;
35839d628a0SDimitry Andric #endif
35939d628a0SDimitry Andric
3603b0f4066SDimitry Andric return true;
3613b0f4066SDimitry Andric }
3623b0f4066SDimitry Andric
363*4ba319b5SDimitry Andric static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
getReadWriteFile(const Twine & Filename,uint64_t FileSize,uint64_t MapSize,uint64_t Offset)364*4ba319b5SDimitry Andric getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize,
365*4ba319b5SDimitry Andric uint64_t Offset) {
366*4ba319b5SDimitry Andric int FD;
367*4ba319b5SDimitry Andric std::error_code EC = sys::fs::openFileForReadWrite(
368*4ba319b5SDimitry Andric Filename, FD, sys::fs::CD_OpenExisting, sys::fs::OF_None);
369*4ba319b5SDimitry Andric
370*4ba319b5SDimitry Andric if (EC)
371*4ba319b5SDimitry Andric return EC;
372*4ba319b5SDimitry Andric
373*4ba319b5SDimitry Andric // Default is to map the full file.
374*4ba319b5SDimitry Andric if (MapSize == uint64_t(-1)) {
375*4ba319b5SDimitry Andric // If we don't know the file size, use fstat to find out. fstat on an open
376*4ba319b5SDimitry Andric // file descriptor is cheaper than stat on a random path.
377*4ba319b5SDimitry Andric if (FileSize == uint64_t(-1)) {
378*4ba319b5SDimitry Andric sys::fs::file_status Status;
379*4ba319b5SDimitry Andric std::error_code EC = sys::fs::status(FD, Status);
380*4ba319b5SDimitry Andric if (EC)
381*4ba319b5SDimitry Andric return EC;
382*4ba319b5SDimitry Andric
383*4ba319b5SDimitry Andric // If this not a file or a block device (e.g. it's a named pipe
384*4ba319b5SDimitry Andric // or character device), we can't mmap it, so error out.
385*4ba319b5SDimitry Andric sys::fs::file_type Type = Status.type();
386*4ba319b5SDimitry Andric if (Type != sys::fs::file_type::regular_file &&
387*4ba319b5SDimitry Andric Type != sys::fs::file_type::block_file)
388*4ba319b5SDimitry Andric return make_error_code(errc::invalid_argument);
389*4ba319b5SDimitry Andric
390*4ba319b5SDimitry Andric FileSize = Status.getSize();
391*4ba319b5SDimitry Andric }
392*4ba319b5SDimitry Andric MapSize = FileSize;
393*4ba319b5SDimitry Andric }
394*4ba319b5SDimitry Andric
395*4ba319b5SDimitry Andric std::unique_ptr<WriteThroughMemoryBuffer> Result(
396*4ba319b5SDimitry Andric new (NamedBufferAlloc(Filename))
397*4ba319b5SDimitry Andric MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize,
398*4ba319b5SDimitry Andric Offset, EC));
399*4ba319b5SDimitry Andric if (EC)
400*4ba319b5SDimitry Andric return EC;
401*4ba319b5SDimitry Andric return std::move(Result);
402*4ba319b5SDimitry Andric }
403*4ba319b5SDimitry Andric
404*4ba319b5SDimitry Andric ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
getFile(const Twine & Filename,int64_t FileSize)405*4ba319b5SDimitry Andric WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) {
406*4ba319b5SDimitry Andric return getReadWriteFile(Filename, FileSize, FileSize, 0);
407*4ba319b5SDimitry Andric }
408*4ba319b5SDimitry Andric
409*4ba319b5SDimitry Andric /// Map a subrange of the specified file as a WritableMemoryBuffer.
410*4ba319b5SDimitry Andric ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
getFileSlice(const Twine & Filename,uint64_t MapSize,uint64_t Offset)411*4ba319b5SDimitry Andric WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
412*4ba319b5SDimitry Andric uint64_t Offset) {
413*4ba319b5SDimitry Andric return getReadWriteFile(Filename, -1, MapSize, Offset);
414*4ba319b5SDimitry Andric }
415*4ba319b5SDimitry Andric
416da09e106SDimitry Andric template <typename MB>
417da09e106SDimitry Andric static ErrorOr<std::unique_ptr<MB>>
getOpenFileImpl(int FD,const Twine & Filename,uint64_t FileSize,uint64_t MapSize,int64_t Offset,bool RequiresNullTerminator,bool IsVolatile)41839d628a0SDimitry Andric getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
41991bc56edSDimitry Andric uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
4207a7e6055SDimitry Andric bool IsVolatile) {
42139d628a0SDimitry Andric static int PageSize = sys::Process::getPageSize();
4223b0f4066SDimitry Andric
4233b0f4066SDimitry Andric // Default is to map the full file.
4246122f3e6SDimitry Andric if (MapSize == uint64_t(-1)) {
4253b0f4066SDimitry Andric // If we don't know the file size, use fstat to find out. fstat on an open
4263b0f4066SDimitry Andric // file descriptor is cheaper than stat on a random path.
4276122f3e6SDimitry Andric if (FileSize == uint64_t(-1)) {
428f785676fSDimitry Andric sys::fs::file_status Status;
42991bc56edSDimitry Andric std::error_code EC = sys::fs::status(FD, Status);
430f785676fSDimitry Andric if (EC)
431f785676fSDimitry Andric return EC;
4323861d79fSDimitry Andric
433139f7f9bSDimitry Andric // If this not a file or a block device (e.g. it's a named pipe
434139f7f9bSDimitry Andric // or character device), we can't trust the size. Create the memory
4353861d79fSDimitry Andric // buffer by copying off the stream.
436f785676fSDimitry Andric sys::fs::file_type Type = Status.type();
437f785676fSDimitry Andric if (Type != sys::fs::file_type::regular_file &&
438f785676fSDimitry Andric Type != sys::fs::file_type::block_file)
43991bc56edSDimitry Andric return getMemoryBufferForStream(FD, Filename);
4403861d79fSDimitry Andric
441f785676fSDimitry Andric FileSize = Status.getSize();
4423b0f4066SDimitry Andric }
4433b0f4066SDimitry Andric MapSize = FileSize;
4443b0f4066SDimitry Andric }
4453b0f4066SDimitry Andric
4463b0f4066SDimitry Andric if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
4477a7e6055SDimitry Andric PageSize, IsVolatile)) {
44891bc56edSDimitry Andric std::error_code EC;
449da09e106SDimitry Andric std::unique_ptr<MB> Result(
450da09e106SDimitry Andric new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
451da09e106SDimitry Andric RequiresNullTerminator, FD, MapSize, Offset, EC));
452139f7f9bSDimitry Andric if (!EC)
45391bc56edSDimitry Andric return std::move(Result);
454f22ef01cSRoman Divacky }
455f22ef01cSRoman Divacky
456da09e106SDimitry Andric auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
457f22ef01cSRoman Divacky if (!Buf) {
4582754fe60SDimitry Andric // Failed to create a buffer. The only way it can fail is if
4592754fe60SDimitry Andric // new(std::nothrow) returns 0.
4602754fe60SDimitry Andric return make_error_code(errc::not_enough_memory);
461f22ef01cSRoman Divacky }
462f22ef01cSRoman Divacky
463da09e106SDimitry Andric char *BufPtr = Buf.get()->getBufferStart();
464f22ef01cSRoman Divacky
4653b0f4066SDimitry Andric size_t BytesLeft = MapSize;
466dff0c46cSDimitry Andric #ifndef HAVE_PREAD
4673b0f4066SDimitry Andric if (lseek(FD, Offset, SEEK_SET) == -1)
46891bc56edSDimitry Andric return std::error_code(errno, std::generic_category());
469dff0c46cSDimitry Andric #endif
4703b0f4066SDimitry Andric
471f22ef01cSRoman Divacky while (BytesLeft) {
472dff0c46cSDimitry Andric #ifdef HAVE_PREAD
473a580b014SDimitry Andric ssize_t NumRead = sys::RetryAfterSignal(-1, ::pread, FD, BufPtr, BytesLeft,
474a580b014SDimitry Andric MapSize - BytesLeft + Offset);
475dff0c46cSDimitry Andric #else
476a580b014SDimitry Andric ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, BufPtr, BytesLeft);
477dff0c46cSDimitry Andric #endif
478f22ef01cSRoman Divacky if (NumRead == -1) {
479f22ef01cSRoman Divacky // Error while reading.
48091bc56edSDimitry Andric return std::error_code(errno, std::generic_category());
481dff0c46cSDimitry Andric }
482dff0c46cSDimitry Andric if (NumRead == 0) {
48391bc56edSDimitry Andric memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
484dff0c46cSDimitry Andric break;
485f22ef01cSRoman Divacky }
486f22ef01cSRoman Divacky BytesLeft -= NumRead;
487f22ef01cSRoman Divacky BufPtr += NumRead;
488f22ef01cSRoman Divacky }
489f22ef01cSRoman Divacky
49039d628a0SDimitry Andric return std::move(Buf);
491f22ef01cSRoman Divacky }
492f22ef01cSRoman Divacky
49391bc56edSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getOpenFile(int FD,const Twine & Filename,uint64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)49439d628a0SDimitry Andric MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
4957a7e6055SDimitry Andric bool RequiresNullTerminator, bool IsVolatile) {
496da09e106SDimitry Andric return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, FileSize, 0,
4977a7e6055SDimitry Andric RequiresNullTerminator, IsVolatile);
498f785676fSDimitry Andric }
499f785676fSDimitry Andric
50091bc56edSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getOpenFileSlice(int FD,const Twine & Filename,uint64_t MapSize,int64_t Offset,bool IsVolatile)50139d628a0SDimitry Andric MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
5027a7e6055SDimitry Andric int64_t Offset, bool IsVolatile) {
50339d628a0SDimitry Andric assert(MapSize != uint64_t(-1));
504da09e106SDimitry Andric return getOpenFileImpl<MemoryBuffer>(FD, Filename, -1, MapSize, Offset, false,
505da09e106SDimitry Andric IsVolatile);
506f785676fSDimitry Andric }
507f785676fSDimitry Andric
getSTDIN()50891bc56edSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
509f22ef01cSRoman Divacky // Read in all of the data from stdin, we cannot mmap stdin.
510f22ef01cSRoman Divacky //
511f22ef01cSRoman Divacky // FIXME: That isn't necessarily true, we should try to mmap stdin and
512f22ef01cSRoman Divacky // fallback if it fails.
513f785676fSDimitry Andric sys::ChangeStdinToBinary();
514f22ef01cSRoman Divacky
51591bc56edSDimitry Andric return getMemoryBufferForStream(0, "<stdin>");
516f22ef01cSRoman Divacky }
51739d628a0SDimitry Andric
518d88c1a5aSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
getFileAsStream(const Twine & Filename)519d88c1a5aSDimitry Andric MemoryBuffer::getFileAsStream(const Twine &Filename) {
520d88c1a5aSDimitry Andric int FD;
521*4ba319b5SDimitry Andric std::error_code EC = sys::fs::openFileForRead(Filename, FD, sys::fs::OF_None);
522d88c1a5aSDimitry Andric if (EC)
523d88c1a5aSDimitry Andric return EC;
524d88c1a5aSDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
525d88c1a5aSDimitry Andric getMemoryBufferForStream(FD, Filename);
526d88c1a5aSDimitry Andric close(FD);
527d88c1a5aSDimitry Andric return Ret;
528d88c1a5aSDimitry Andric }
529d88c1a5aSDimitry Andric
getMemBufferRef() const53039d628a0SDimitry Andric MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
53139d628a0SDimitry Andric StringRef Data = getBuffer();
53239d628a0SDimitry Andric StringRef Identifier = getBufferIdentifier();
53339d628a0SDimitry Andric return MemoryBufferRef(Data, Identifier);
53439d628a0SDimitry Andric }
535*4ba319b5SDimitry Andric
~SmallVectorMemoryBuffer()536*4ba319b5SDimitry Andric SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() {}
537