1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the MemoryBuffer interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Support/MemoryBuffer.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/Config/config.h" 17 #include "llvm/Support/Errc.h" 18 #include "llvm/Support/Errno.h" 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/MathExtras.h" 21 #include "llvm/Support/Path.h" 22 #include "llvm/Support/Process.h" 23 #include "llvm/Support/Program.h" 24 #include <cassert> 25 #include <cerrno> 26 #include <cstdio> 27 #include <cstring> 28 #include <new> 29 #include <sys/types.h> 30 #include <system_error> 31 #if !defined(_MSC_VER) && !defined(__MINGW32__) 32 #include <unistd.h> 33 #else 34 #include <io.h> 35 #endif 36 using namespace llvm; 37 38 //===----------------------------------------------------------------------===// 39 // MemoryBuffer implementation itself. 40 //===----------------------------------------------------------------------===// 41 42 MemoryBuffer::~MemoryBuffer() { } 43 44 /// init - Initialize this MemoryBuffer as a reference to externally allocated 45 /// memory, memory that we know is already null terminated. 46 void MemoryBuffer::init(const char *BufStart, const char *BufEnd, 47 bool RequiresNullTerminator) { 48 assert((!RequiresNullTerminator || BufEnd[0] == 0) && 49 "Buffer is not null terminated!"); 50 BufferStart = BufStart; 51 BufferEnd = BufEnd; 52 } 53 54 //===----------------------------------------------------------------------===// 55 // MemoryBufferMem implementation. 56 //===----------------------------------------------------------------------===// 57 58 /// CopyStringRef - Copies contents of a StringRef into a block of memory and 59 /// null-terminates it. 60 static void CopyStringRef(char *Memory, StringRef Data) { 61 memcpy(Memory, Data.data(), Data.size()); 62 Memory[Data.size()] = 0; // Null terminate string. 63 } 64 65 namespace { 66 struct NamedBufferAlloc { 67 StringRef Name; 68 NamedBufferAlloc(StringRef Name) : Name(Name) {} 69 }; 70 } 71 72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) { 73 char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1)); 74 CopyStringRef(Mem + N, Alloc.Name); 75 return Mem; 76 } 77 78 namespace { 79 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory. 80 class MemoryBufferMem : public MemoryBuffer { 81 public: 82 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) { 83 init(InputData.begin(), InputData.end(), RequiresNullTerminator); 84 } 85 86 const char *getBufferIdentifier() const override { 87 // The name is stored after the class itself. 88 return reinterpret_cast<const char*>(this + 1); 89 } 90 91 BufferKind getBufferKind() const override { 92 return MemoryBuffer_Malloc; 93 } 94 }; 95 } 96 97 std::unique_ptr<MemoryBuffer> 98 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName, 99 bool RequiresNullTerminator) { 100 auto *Ret = new (NamedBufferAlloc(BufferName)) 101 MemoryBufferMem(InputData, RequiresNullTerminator); 102 return std::unique_ptr<MemoryBuffer>(Ret); 103 } 104 105 std::unique_ptr<MemoryBuffer> 106 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) { 107 return std::unique_ptr<MemoryBuffer>(getMemBuffer( 108 Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator)); 109 } 110 111 std::unique_ptr<MemoryBuffer> 112 MemoryBuffer::getMemBufferCopy(StringRef InputData, StringRef BufferName) { 113 std::unique_ptr<MemoryBuffer> Buf = 114 getNewUninitMemBuffer(InputData.size(), BufferName); 115 if (!Buf) 116 return nullptr; 117 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(), 118 InputData.size()); 119 return Buf; 120 } 121 122 std::unique_ptr<MemoryBuffer> 123 MemoryBuffer::getNewUninitMemBuffer(size_t Size, StringRef BufferName) { 124 // Allocate space for the MemoryBuffer, the data and the name. It is important 125 // that MemoryBuffer and data are aligned so PointerIntPair works with them. 126 // TODO: Is 16-byte alignment enough? We copy small object files with large 127 // alignment expectations into this buffer. 128 size_t AlignedStringLen = 129 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16); 130 size_t RealLen = AlignedStringLen + Size + 1; 131 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 132 if (!Mem) 133 return nullptr; 134 135 // The name is stored after the class itself. 136 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName); 137 138 // The buffer begins after the name and must be aligned. 139 char *Buf = Mem + AlignedStringLen; 140 Buf[Size] = 0; // Null terminate buffer. 141 142 auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true); 143 return std::unique_ptr<MemoryBuffer>(Ret); 144 } 145 146 std::unique_ptr<MemoryBuffer> 147 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) { 148 std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName); 149 if (!SB) 150 return nullptr; 151 memset(const_cast<char*>(SB->getBufferStart()), 0, Size); 152 return SB; 153 } 154 155 ErrorOr<std::unique_ptr<MemoryBuffer>> 156 MemoryBuffer::getFileOrSTDIN(StringRef Filename, int64_t FileSize) { 157 if (Filename == "-") 158 return getSTDIN(); 159 return getFile(Filename, FileSize); 160 } 161 162 163 //===----------------------------------------------------------------------===// 164 // MemoryBuffer::getFile implementation. 165 //===----------------------------------------------------------------------===// 166 167 namespace { 168 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region. 169 /// 170 /// This handles converting the offset into a legal offset on the platform. 171 class MemoryBufferMMapFile : public MemoryBuffer { 172 sys::fs::mapped_file_region MFR; 173 174 static uint64_t getLegalMapOffset(uint64_t Offset) { 175 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1); 176 } 177 178 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) { 179 return Len + (Offset - getLegalMapOffset(Offset)); 180 } 181 182 const char *getStart(uint64_t Len, uint64_t Offset) { 183 return MFR.const_data() + (Offset - getLegalMapOffset(Offset)); 184 } 185 186 public: 187 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len, 188 uint64_t Offset, std::error_code EC) 189 : MFR(FD, false, sys::fs::mapped_file_region::readonly, 190 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) { 191 if (!EC) { 192 const char *Start = getStart(Len, Offset); 193 init(Start, Start + Len, RequiresNullTerminator); 194 } 195 } 196 197 const char *getBufferIdentifier() const override { 198 // The name is stored after the class itself. 199 return reinterpret_cast<const char *>(this + 1); 200 } 201 202 BufferKind getBufferKind() const override { 203 return MemoryBuffer_MMap; 204 } 205 }; 206 } 207 208 static ErrorOr<std::unique_ptr<MemoryBuffer>> 209 getMemoryBufferForStream(int FD, StringRef BufferName) { 210 const ssize_t ChunkSize = 4096*4; 211 SmallString<ChunkSize> Buffer; 212 ssize_t ReadBytes; 213 // Read into Buffer until we hit EOF. 214 do { 215 Buffer.reserve(Buffer.size() + ChunkSize); 216 ReadBytes = read(FD, Buffer.end(), ChunkSize); 217 if (ReadBytes == -1) { 218 if (errno == EINTR) continue; 219 return std::error_code(errno, std::generic_category()); 220 } 221 Buffer.set_size(Buffer.size() + ReadBytes); 222 } while (ReadBytes != 0); 223 224 return MemoryBuffer::getMemBufferCopy(Buffer, BufferName); 225 } 226 227 static ErrorOr<std::unique_ptr<MemoryBuffer>> 228 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator, 229 bool IsVolatileSize); 230 231 ErrorOr<std::unique_ptr<MemoryBuffer>> 232 MemoryBuffer::getFile(Twine Filename, int64_t FileSize, 233 bool RequiresNullTerminator, bool IsVolatileSize) { 234 // Ensure the path is null terminated. 235 SmallString<256> PathBuf; 236 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf); 237 return getFileAux(NullTerminatedName.data(), FileSize, RequiresNullTerminator, 238 IsVolatileSize); 239 } 240 241 static ErrorOr<std::unique_ptr<MemoryBuffer>> 242 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize, 243 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 244 bool IsVolatileSize); 245 246 static ErrorOr<std::unique_ptr<MemoryBuffer>> 247 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator, 248 bool IsVolatileSize) { 249 int FD; 250 std::error_code EC = sys::fs::openFileForRead(Filename, FD); 251 if (EC) 252 return EC; 253 254 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = 255 getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, 256 RequiresNullTerminator, IsVolatileSize); 257 close(FD); 258 return Ret; 259 } 260 261 static bool shouldUseMmap(int FD, 262 size_t FileSize, 263 size_t MapSize, 264 off_t Offset, 265 bool RequiresNullTerminator, 266 int PageSize, 267 bool IsVolatileSize) { 268 // mmap may leave the buffer without null terminator if the file size changed 269 // by the time the last page is mapped in, so avoid it if the file size is 270 // likely to change. 271 if (IsVolatileSize) 272 return false; 273 274 // We don't use mmap for small files because this can severely fragment our 275 // address space. 276 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize) 277 return false; 278 279 if (!RequiresNullTerminator) 280 return true; 281 282 283 // If we don't know the file size, use fstat to find out. fstat on an open 284 // file descriptor is cheaper than stat on a random path. 285 // FIXME: this chunk of code is duplicated, but it avoids a fstat when 286 // RequiresNullTerminator = false and MapSize != -1. 287 if (FileSize == size_t(-1)) { 288 sys::fs::file_status Status; 289 if (sys::fs::status(FD, Status)) 290 return false; 291 FileSize = Status.getSize(); 292 } 293 294 // If we need a null terminator and the end of the map is inside the file, 295 // we cannot use mmap. 296 size_t End = Offset + MapSize; 297 assert(End <= FileSize); 298 if (End != FileSize) 299 return false; 300 301 // Don't try to map files that are exactly a multiple of the system page size 302 // if we need a null terminator. 303 if ((FileSize & (PageSize -1)) == 0) 304 return false; 305 306 #if defined(__CYGWIN__) 307 // Don't try to map files that are exactly a multiple of the physical page size 308 // if we need a null terminator. 309 // FIXME: We should reorganize again getPageSize() on Win32. 310 if ((FileSize & (4096 - 1)) == 0) 311 return false; 312 #endif 313 314 return true; 315 } 316 317 static ErrorOr<std::unique_ptr<MemoryBuffer>> 318 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize, 319 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 320 bool IsVolatileSize) { 321 static int PageSize = sys::process::get_self()->page_size(); 322 323 // Default is to map the full file. 324 if (MapSize == uint64_t(-1)) { 325 // If we don't know the file size, use fstat to find out. fstat on an open 326 // file descriptor is cheaper than stat on a random path. 327 if (FileSize == uint64_t(-1)) { 328 sys::fs::file_status Status; 329 std::error_code EC = sys::fs::status(FD, Status); 330 if (EC) 331 return EC; 332 333 // If this not a file or a block device (e.g. it's a named pipe 334 // or character device), we can't trust the size. Create the memory 335 // buffer by copying off the stream. 336 sys::fs::file_type Type = Status.type(); 337 if (Type != sys::fs::file_type::regular_file && 338 Type != sys::fs::file_type::block_file) 339 return getMemoryBufferForStream(FD, Filename); 340 341 FileSize = Status.getSize(); 342 } 343 MapSize = FileSize; 344 } 345 346 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, 347 PageSize, IsVolatileSize)) { 348 std::error_code EC; 349 std::unique_ptr<MemoryBuffer> Result( 350 new (NamedBufferAlloc(Filename)) 351 MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC)); 352 if (!EC) 353 return std::move(Result); 354 } 355 356 std::unique_ptr<MemoryBuffer> Buf = 357 MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); 358 if (!Buf) { 359 // Failed to create a buffer. The only way it can fail is if 360 // new(std::nothrow) returns 0. 361 return make_error_code(errc::not_enough_memory); 362 } 363 364 char *BufPtr = const_cast<char *>(Buf->getBufferStart()); 365 366 size_t BytesLeft = MapSize; 367 #ifndef HAVE_PREAD 368 if (lseek(FD, Offset, SEEK_SET) == -1) 369 return std::error_code(errno, std::generic_category()); 370 #endif 371 372 while (BytesLeft) { 373 #ifdef HAVE_PREAD 374 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset); 375 #else 376 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft); 377 #endif 378 if (NumRead == -1) { 379 if (errno == EINTR) 380 continue; 381 // Error while reading. 382 return std::error_code(errno, std::generic_category()); 383 } 384 if (NumRead == 0) { 385 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer. 386 break; 387 } 388 BytesLeft -= NumRead; 389 BufPtr += NumRead; 390 } 391 392 return std::move(Buf); 393 } 394 395 ErrorOr<std::unique_ptr<MemoryBuffer>> 396 MemoryBuffer::getOpenFile(int FD, const char *Filename, uint64_t FileSize, 397 bool RequiresNullTerminator, bool IsVolatileSize) { 398 return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, 399 RequiresNullTerminator, IsVolatileSize); 400 } 401 402 ErrorOr<std::unique_ptr<MemoryBuffer>> 403 MemoryBuffer::getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize, 404 int64_t Offset, bool IsVolatileSize) { 405 return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false, 406 IsVolatileSize); 407 } 408 409 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() { 410 // Read in all of the data from stdin, we cannot mmap stdin. 411 // 412 // FIXME: That isn't necessarily true, we should try to mmap stdin and 413 // fallback if it fails. 414 sys::ChangeStdinToBinary(); 415 416 return getMemoryBufferForStream(0, "<stdin>"); 417 } 418 419 MemoryBufferRef MemoryBuffer::getMemBufferRef() const { 420 StringRef Data = getBuffer(); 421 StringRef Identifier = getBufferIdentifier(); 422 return MemoryBufferRef(Data, Identifier); 423 } 424