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