LLVM API Documentation
00001 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the MemoryBuffer interface. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/Support/MemoryBuffer.h" 00015 #include "llvm/ADT/SmallString.h" 00016 #include "llvm/Config/config.h" 00017 #include "llvm/Support/Errc.h" 00018 #include "llvm/Support/Errno.h" 00019 #include "llvm/Support/FileSystem.h" 00020 #include "llvm/Support/MathExtras.h" 00021 #include "llvm/Support/Path.h" 00022 #include "llvm/Support/Process.h" 00023 #include "llvm/Support/Program.h" 00024 #include <cassert> 00025 #include <cerrno> 00026 #include <cstdio> 00027 #include <cstring> 00028 #include <new> 00029 #include <sys/types.h> 00030 #include <system_error> 00031 #if !defined(_MSC_VER) && !defined(__MINGW32__) 00032 #include <unistd.h> 00033 #else 00034 #include <io.h> 00035 #endif 00036 using namespace llvm; 00037 00038 //===----------------------------------------------------------------------===// 00039 // MemoryBuffer implementation itself. 00040 //===----------------------------------------------------------------------===// 00041 00042 MemoryBuffer::~MemoryBuffer() { } 00043 00044 /// init - Initialize this MemoryBuffer as a reference to externally allocated 00045 /// memory, memory that we know is already null terminated. 00046 void MemoryBuffer::init(const char *BufStart, const char *BufEnd, 00047 bool RequiresNullTerminator) { 00048 assert((!RequiresNullTerminator || BufEnd[0] == 0) && 00049 "Buffer is not null terminated!"); 00050 BufferStart = BufStart; 00051 BufferEnd = BufEnd; 00052 } 00053 00054 //===----------------------------------------------------------------------===// 00055 // MemoryBufferMem implementation. 00056 //===----------------------------------------------------------------------===// 00057 00058 /// CopyStringRef - Copies contents of a StringRef into a block of memory and 00059 /// null-terminates it. 00060 static void CopyStringRef(char *Memory, StringRef Data) { 00061 memcpy(Memory, Data.data(), Data.size()); 00062 Memory[Data.size()] = 0; // Null terminate string. 00063 } 00064 00065 namespace { 00066 struct NamedBufferAlloc { 00067 StringRef Name; 00068 NamedBufferAlloc(StringRef Name) : Name(Name) {} 00069 }; 00070 } 00071 00072 void *operator new(size_t N, const NamedBufferAlloc &Alloc) { 00073 char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1)); 00074 CopyStringRef(Mem + N, Alloc.Name); 00075 return Mem; 00076 } 00077 00078 namespace { 00079 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory. 00080 class MemoryBufferMem : public MemoryBuffer { 00081 public: 00082 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) { 00083 init(InputData.begin(), InputData.end(), RequiresNullTerminator); 00084 } 00085 00086 const char *getBufferIdentifier() const override { 00087 // The name is stored after the class itself. 00088 return reinterpret_cast<const char*>(this + 1); 00089 } 00090 00091 BufferKind getBufferKind() const override { 00092 return MemoryBuffer_Malloc; 00093 } 00094 }; 00095 } 00096 00097 std::unique_ptr<MemoryBuffer> 00098 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName, 00099 bool RequiresNullTerminator) { 00100 auto *Ret = new (NamedBufferAlloc(BufferName)) 00101 MemoryBufferMem(InputData, RequiresNullTerminator); 00102 return std::unique_ptr<MemoryBuffer>(Ret); 00103 } 00104 00105 std::unique_ptr<MemoryBuffer> 00106 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) { 00107 return std::unique_ptr<MemoryBuffer>(getMemBuffer( 00108 Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator)); 00109 } 00110 00111 std::unique_ptr<MemoryBuffer> 00112 MemoryBuffer::getMemBufferCopy(StringRef InputData, StringRef BufferName) { 00113 std::unique_ptr<MemoryBuffer> Buf = 00114 getNewUninitMemBuffer(InputData.size(), BufferName); 00115 if (!Buf) 00116 return nullptr; 00117 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(), 00118 InputData.size()); 00119 return Buf; 00120 } 00121 00122 std::unique_ptr<MemoryBuffer> 00123 MemoryBuffer::getNewUninitMemBuffer(size_t Size, StringRef BufferName) { 00124 // Allocate space for the MemoryBuffer, the data and the name. It is important 00125 // that MemoryBuffer and data are aligned so PointerIntPair works with them. 00126 // TODO: Is 16-byte alignment enough? We copy small object files with large 00127 // alignment expectations into this buffer. 00128 size_t AlignedStringLen = 00129 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16); 00130 size_t RealLen = AlignedStringLen + Size + 1; 00131 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 00132 if (!Mem) 00133 return nullptr; 00134 00135 // The name is stored after the class itself. 00136 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName); 00137 00138 // The buffer begins after the name and must be aligned. 00139 char *Buf = Mem + AlignedStringLen; 00140 Buf[Size] = 0; // Null terminate buffer. 00141 00142 auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true); 00143 return std::unique_ptr<MemoryBuffer>(Ret); 00144 } 00145 00146 std::unique_ptr<MemoryBuffer> 00147 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) { 00148 std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName); 00149 if (!SB) 00150 return nullptr; 00151 memset(const_cast<char*>(SB->getBufferStart()), 0, Size); 00152 return SB; 00153 } 00154 00155 ErrorOr<std::unique_ptr<MemoryBuffer>> 00156 MemoryBuffer::getFileOrSTDIN(StringRef Filename, int64_t FileSize) { 00157 if (Filename == "-") 00158 return getSTDIN(); 00159 return getFile(Filename, FileSize); 00160 } 00161 00162 00163 //===----------------------------------------------------------------------===// 00164 // MemoryBuffer::getFile implementation. 00165 //===----------------------------------------------------------------------===// 00166 00167 namespace { 00168 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region. 00169 /// 00170 /// This handles converting the offset into a legal offset on the platform. 00171 class MemoryBufferMMapFile : public MemoryBuffer { 00172 sys::fs::mapped_file_region MFR; 00173 00174 static uint64_t getLegalMapOffset(uint64_t Offset) { 00175 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1); 00176 } 00177 00178 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) { 00179 return Len + (Offset - getLegalMapOffset(Offset)); 00180 } 00181 00182 const char *getStart(uint64_t Len, uint64_t Offset) { 00183 return MFR.const_data() + (Offset - getLegalMapOffset(Offset)); 00184 } 00185 00186 public: 00187 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len, 00188 uint64_t Offset, std::error_code EC) 00189 : MFR(FD, false, sys::fs::mapped_file_region::readonly, 00190 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) { 00191 if (!EC) { 00192 const char *Start = getStart(Len, Offset); 00193 init(Start, Start + Len, RequiresNullTerminator); 00194 } 00195 } 00196 00197 const char *getBufferIdentifier() const override { 00198 // The name is stored after the class itself. 00199 return reinterpret_cast<const char *>(this + 1); 00200 } 00201 00202 BufferKind getBufferKind() const override { 00203 return MemoryBuffer_MMap; 00204 } 00205 }; 00206 } 00207 00208 static ErrorOr<std::unique_ptr<MemoryBuffer>> 00209 getMemoryBufferForStream(int FD, StringRef BufferName) { 00210 const ssize_t ChunkSize = 4096*4; 00211 SmallString<ChunkSize> Buffer; 00212 ssize_t ReadBytes; 00213 // Read into Buffer until we hit EOF. 00214 do { 00215 Buffer.reserve(Buffer.size() + ChunkSize); 00216 ReadBytes = read(FD, Buffer.end(), ChunkSize); 00217 if (ReadBytes == -1) { 00218 if (errno == EINTR) continue; 00219 return std::error_code(errno, std::generic_category()); 00220 } 00221 Buffer.set_size(Buffer.size() + ReadBytes); 00222 } while (ReadBytes != 0); 00223 00224 return MemoryBuffer::getMemBufferCopy(Buffer, BufferName); 00225 } 00226 00227 static ErrorOr<std::unique_ptr<MemoryBuffer>> 00228 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator, 00229 bool IsVolatileSize); 00230 00231 ErrorOr<std::unique_ptr<MemoryBuffer>> 00232 MemoryBuffer::getFile(Twine Filename, int64_t FileSize, 00233 bool RequiresNullTerminator, bool IsVolatileSize) { 00234 // Ensure the path is null terminated. 00235 SmallString<256> PathBuf; 00236 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf); 00237 return getFileAux(NullTerminatedName.data(), FileSize, RequiresNullTerminator, 00238 IsVolatileSize); 00239 } 00240 00241 static ErrorOr<std::unique_ptr<MemoryBuffer>> 00242 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize, 00243 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 00244 bool IsVolatileSize); 00245 00246 static ErrorOr<std::unique_ptr<MemoryBuffer>> 00247 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator, 00248 bool IsVolatileSize) { 00249 int FD; 00250 std::error_code EC = sys::fs::openFileForRead(Filename, FD); 00251 if (EC) 00252 return EC; 00253 00254 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = 00255 getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, 00256 RequiresNullTerminator, IsVolatileSize); 00257 close(FD); 00258 return Ret; 00259 } 00260 00261 static bool shouldUseMmap(int FD, 00262 size_t FileSize, 00263 size_t MapSize, 00264 off_t Offset, 00265 bool RequiresNullTerminator, 00266 int PageSize, 00267 bool IsVolatileSize) { 00268 // mmap may leave the buffer without null terminator if the file size changed 00269 // by the time the last page is mapped in, so avoid it if the file size is 00270 // likely to change. 00271 if (IsVolatileSize) 00272 return false; 00273 00274 // We don't use mmap for small files because this can severely fragment our 00275 // address space. 00276 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize) 00277 return false; 00278 00279 if (!RequiresNullTerminator) 00280 return true; 00281 00282 00283 // If we don't know the file size, use fstat to find out. fstat on an open 00284 // file descriptor is cheaper than stat on a random path. 00285 // FIXME: this chunk of code is duplicated, but it avoids a fstat when 00286 // RequiresNullTerminator = false and MapSize != -1. 00287 if (FileSize == size_t(-1)) { 00288 sys::fs::file_status Status; 00289 if (sys::fs::status(FD, Status)) 00290 return false; 00291 FileSize = Status.getSize(); 00292 } 00293 00294 // If we need a null terminator and the end of the map is inside the file, 00295 // we cannot use mmap. 00296 size_t End = Offset + MapSize; 00297 assert(End <= FileSize); 00298 if (End != FileSize) 00299 return false; 00300 00301 // Don't try to map files that are exactly a multiple of the system page size 00302 // if we need a null terminator. 00303 if ((FileSize & (PageSize -1)) == 0) 00304 return false; 00305 00306 #if defined(__CYGWIN__) 00307 // Don't try to map files that are exactly a multiple of the physical page size 00308 // if we need a null terminator. 00309 // FIXME: We should reorganize again getPageSize() on Win32. 00310 if ((FileSize & (4096 - 1)) == 0) 00311 return false; 00312 #endif 00313 00314 return true; 00315 } 00316 00317 static ErrorOr<std::unique_ptr<MemoryBuffer>> 00318 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize, 00319 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 00320 bool IsVolatileSize) { 00321 static int PageSize = sys::process::get_self()->page_size(); 00322 00323 // Default is to map the full file. 00324 if (MapSize == uint64_t(-1)) { 00325 // If we don't know the file size, use fstat to find out. fstat on an open 00326 // file descriptor is cheaper than stat on a random path. 00327 if (FileSize == uint64_t(-1)) { 00328 sys::fs::file_status Status; 00329 std::error_code EC = sys::fs::status(FD, Status); 00330 if (EC) 00331 return EC; 00332 00333 // If this not a file or a block device (e.g. it's a named pipe 00334 // or character device), we can't trust the size. Create the memory 00335 // buffer by copying off the stream. 00336 sys::fs::file_type Type = Status.type(); 00337 if (Type != sys::fs::file_type::regular_file && 00338 Type != sys::fs::file_type::block_file) 00339 return getMemoryBufferForStream(FD, Filename); 00340 00341 FileSize = Status.getSize(); 00342 } 00343 MapSize = FileSize; 00344 } 00345 00346 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, 00347 PageSize, IsVolatileSize)) { 00348 std::error_code EC; 00349 std::unique_ptr<MemoryBuffer> Result( 00350 new (NamedBufferAlloc(Filename)) 00351 MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC)); 00352 if (!EC) 00353 return std::move(Result); 00354 } 00355 00356 std::unique_ptr<MemoryBuffer> Buf = 00357 MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); 00358 if (!Buf) { 00359 // Failed to create a buffer. The only way it can fail is if 00360 // new(std::nothrow) returns 0. 00361 return make_error_code(errc::not_enough_memory); 00362 } 00363 00364 char *BufPtr = const_cast<char *>(Buf->getBufferStart()); 00365 00366 size_t BytesLeft = MapSize; 00367 #ifndef HAVE_PREAD 00368 if (lseek(FD, Offset, SEEK_SET) == -1) 00369 return std::error_code(errno, std::generic_category()); 00370 #endif 00371 00372 while (BytesLeft) { 00373 #ifdef HAVE_PREAD 00374 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset); 00375 #else 00376 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft); 00377 #endif 00378 if (NumRead == -1) { 00379 if (errno == EINTR) 00380 continue; 00381 // Error while reading. 00382 return std::error_code(errno, std::generic_category()); 00383 } 00384 if (NumRead == 0) { 00385 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer. 00386 break; 00387 } 00388 BytesLeft -= NumRead; 00389 BufPtr += NumRead; 00390 } 00391 00392 return std::move(Buf); 00393 } 00394 00395 ErrorOr<std::unique_ptr<MemoryBuffer>> 00396 MemoryBuffer::getOpenFile(int FD, const char *Filename, uint64_t FileSize, 00397 bool RequiresNullTerminator, bool IsVolatileSize) { 00398 return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, 00399 RequiresNullTerminator, IsVolatileSize); 00400 } 00401 00402 ErrorOr<std::unique_ptr<MemoryBuffer>> 00403 MemoryBuffer::getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize, 00404 int64_t Offset, bool IsVolatileSize) { 00405 return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false, 00406 IsVolatileSize); 00407 } 00408 00409 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() { 00410 // Read in all of the data from stdin, we cannot mmap stdin. 00411 // 00412 // FIXME: That isn't necessarily true, we should try to mmap stdin and 00413 // fallback if it fails. 00414 sys::ChangeStdinToBinary(); 00415 00416 return getMemoryBufferForStream(0, "<stdin>"); 00417 } 00418 00419 MemoryBufferRef MemoryBuffer::getMemBufferRef() const { 00420 StringRef Data = getBuffer(); 00421 StringRef Identifier = getBufferIdentifier(); 00422 return MemoryBufferRef(Data, Identifier); 00423 }