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