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