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/Support/MathExtras.h" 18 #include "llvm/Support/Errno.h" 19 #include "llvm/Support/Path.h" 20 #include "llvm/Support/Process.h" 21 #include "llvm/Support/Program.h" 22 #include "llvm/Support/system_error.h" 23 #include <cassert> 24 #include <cstdio> 25 #include <cstring> 26 #include <cerrno> 27 #include <new> 28 #include <sys/types.h> 29 #include <sys/stat.h> 30 #if !defined(_MSC_VER) && !defined(__MINGW32__) 31 #include <unistd.h> 32 #include <sys/uio.h> 33 #else 34 #include <io.h> 35 #endif 36 #include <fcntl.h> 37 using namespace llvm; 38 39 namespace { const llvm::error_code success; } 40 41 //===----------------------------------------------------------------------===// 42 // MemoryBuffer implementation itself. 43 //===----------------------------------------------------------------------===// 44 45 MemoryBuffer::~MemoryBuffer() { } 46 47 /// init - Initialize this MemoryBuffer as a reference to externally allocated 48 /// memory, memory that we know is already null terminated. 49 void MemoryBuffer::init(const char *BufStart, const char *BufEnd, 50 bool RequiresNullTerminator) { 51 assert((!RequiresNullTerminator || BufEnd[0] == 0) && 52 "Buffer is not null terminated!"); 53 BufferStart = BufStart; 54 BufferEnd = BufEnd; 55 } 56 57 //===----------------------------------------------------------------------===// 58 // MemoryBufferMem implementation. 59 //===----------------------------------------------------------------------===// 60 61 /// CopyStringRef - Copies contents of a StringRef into a block of memory and 62 /// null-terminates it. 63 static void CopyStringRef(char *Memory, StringRef Data) { 64 memcpy(Memory, Data.data(), Data.size()); 65 Memory[Data.size()] = 0; // Null terminate string. 66 } 67 68 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it. 69 template <typename T> 70 static T* GetNamedBuffer(StringRef Buffer, StringRef Name, 71 bool RequiresNullTerminator) { 72 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1)); 73 CopyStringRef(Mem + sizeof(T), Name); 74 return new (Mem) T(Buffer, RequiresNullTerminator); 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 virtual const char *getBufferIdentifier() const { 86 // The name is stored after the class itself. 87 return reinterpret_cast<const char*>(this + 1); 88 } 89 }; 90 } 91 92 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note 93 /// that EndPtr[0] must be a null byte and be accessible! 94 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData, 95 StringRef BufferName, 96 bool RequiresNullTerminator) { 97 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName, 98 RequiresNullTerminator); 99 } 100 101 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer, 102 /// copying the contents and taking ownership of it. This has no requirements 103 /// on EndPtr[0]. 104 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData, 105 StringRef BufferName) { 106 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName); 107 if (!Buf) return 0; 108 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(), 109 InputData.size()); 110 return Buf; 111 } 112 113 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size 114 /// that is not initialized. Note that the caller should initialize the 115 /// memory allocated by this method. The memory is owned by the MemoryBuffer 116 /// object. 117 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size, 118 StringRef BufferName) { 119 // Allocate space for the MemoryBuffer, the data and the name. It is important 120 // that MemoryBuffer and data are aligned so PointerIntPair works with them. 121 size_t AlignedStringLen = 122 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 123 sizeof(void*)); // TODO: Is sizeof(void*) enough? 124 size_t RealLen = AlignedStringLen + Size + 1; 125 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 126 if (!Mem) return 0; 127 128 // The name is stored after the class itself. 129 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName); 130 131 // The buffer begins after the name and must be aligned. 132 char *Buf = Mem + AlignedStringLen; 133 Buf[Size] = 0; // Null terminate buffer. 134 135 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true); 136 } 137 138 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that 139 /// is completely initialized to zeros. Note that the caller should 140 /// initialize the memory allocated by this method. The memory is owned by 141 /// the MemoryBuffer object. 142 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) { 143 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName); 144 if (!SB) return 0; 145 memset(const_cast<char*>(SB->getBufferStart()), 0, Size); 146 return SB; 147 } 148 149 150 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin 151 /// if the Filename is "-". If an error occurs, this returns null and fills 152 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN) 153 /// returns an empty buffer. 154 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename, 155 OwningPtr<MemoryBuffer> &result, 156 int64_t FileSize) { 157 if (Filename == "-") 158 return getSTDIN(result); 159 return getFile(Filename, result, FileSize); 160 } 161 162 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename, 163 OwningPtr<MemoryBuffer> &result, 164 int64_t FileSize) { 165 if (strcmp(Filename, "-") == 0) 166 return getSTDIN(result); 167 return getFile(Filename, result, FileSize); 168 } 169 170 //===----------------------------------------------------------------------===// 171 // MemoryBuffer::getFile implementation. 172 //===----------------------------------------------------------------------===// 173 174 namespace { 175 /// MemoryBufferMMapFile - This represents a file that was mapped in with the 176 /// sys::Path::MapInFilePages method. When destroyed, it calls the 177 /// sys::Path::UnMapFilePages method. 178 class MemoryBufferMMapFile : public MemoryBufferMem { 179 public: 180 MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator) 181 : MemoryBufferMem(Buffer, RequiresNullTerminator) { } 182 183 ~MemoryBufferMMapFile() { 184 static int PageSize = sys::Process::GetPageSize(); 185 186 uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart()); 187 size_t Size = getBufferSize(); 188 uintptr_t RealStart = Start & ~(PageSize - 1); 189 size_t RealSize = Size + (Start - RealStart); 190 191 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart), 192 RealSize); 193 } 194 }; 195 } 196 197 error_code MemoryBuffer::getFile(StringRef Filename, 198 OwningPtr<MemoryBuffer> &result, 199 int64_t FileSize, 200 bool RequiresNullTerminator) { 201 // Ensure the path is null terminated. 202 SmallString<256> PathBuf(Filename.begin(), Filename.end()); 203 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize, 204 RequiresNullTerminator); 205 } 206 207 error_code MemoryBuffer::getFile(const char *Filename, 208 OwningPtr<MemoryBuffer> &result, 209 int64_t FileSize, 210 bool RequiresNullTerminator) { 211 int OpenFlags = O_RDONLY; 212 #ifdef O_BINARY 213 OpenFlags |= O_BINARY; // Open input file in binary mode on win32. 214 #endif 215 int FD = ::open(Filename, OpenFlags); 216 if (FD == -1) { 217 return error_code(errno, posix_category()); 218 } 219 error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize, 220 0, RequiresNullTerminator); 221 close(FD); 222 return ret; 223 } 224 225 static bool shouldUseMmap(int FD, 226 size_t FileSize, 227 size_t MapSize, 228 off_t Offset, 229 bool RequiresNullTerminator, 230 int PageSize) { 231 // We don't use mmap for small files because this can severely fragment our 232 // address space. 233 if (MapSize < 4096*4) 234 return false; 235 236 if (!RequiresNullTerminator) 237 return true; 238 239 240 // If we don't know the file size, use fstat to find out. fstat on an open 241 // file descriptor is cheaper than stat on a random path. 242 // FIXME: this chunk of code is duplicated, but it avoids a fstat when 243 // RequiresNullTerminator = false and MapSize != -1. 244 if (FileSize == size_t(-1)) { 245 struct stat FileInfo; 246 // TODO: This should use fstat64 when available. 247 if (fstat(FD, &FileInfo) == -1) { 248 return error_code(errno, posix_category()); 249 } 250 FileSize = FileInfo.st_size; 251 } 252 253 // If we need a null terminator and the end of the map is inside the file, 254 // we cannot use mmap. 255 size_t End = Offset + MapSize; 256 assert(End <= FileSize); 257 if (End != FileSize) 258 return false; 259 260 // Don't try to map files that are exactly a multiple of the system page size 261 // if we need a null terminator. 262 if ((FileSize & (PageSize -1)) == 0) 263 return false; 264 265 return true; 266 } 267 268 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename, 269 OwningPtr<MemoryBuffer> &result, 270 size_t FileSize, size_t MapSize, 271 off_t Offset, 272 bool RequiresNullTerminator) { 273 static int PageSize = sys::Process::GetPageSize(); 274 275 // Default is to map the full file. 276 if (MapSize == size_t(-1)) { 277 // If we don't know the file size, use fstat to find out. fstat on an open 278 // file descriptor is cheaper than stat on a random path. 279 if (FileSize == size_t(-1)) { 280 struct stat FileInfo; 281 // TODO: This should use fstat64 when available. 282 if (fstat(FD, &FileInfo) == -1) { 283 return error_code(errno, posix_category()); 284 } 285 FileSize = FileInfo.st_size; 286 } 287 MapSize = FileSize; 288 } 289 290 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, 291 PageSize)) { 292 off_t RealMapOffset = Offset & ~(PageSize - 1); 293 off_t Delta = Offset - RealMapOffset; 294 size_t RealMapSize = MapSize + Delta; 295 296 if (const char *Pages = sys::Path::MapInFilePages(FD, 297 RealMapSize, 298 RealMapOffset)) { 299 result.reset(GetNamedBuffer<MemoryBufferMMapFile>( 300 StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator)); 301 return success; 302 } 303 } 304 305 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); 306 if (!Buf) { 307 // Failed to create a buffer. The only way it can fail is if 308 // new(std::nothrow) returns 0. 309 return make_error_code(errc::not_enough_memory); 310 } 311 312 OwningPtr<MemoryBuffer> SB(Buf); 313 char *BufPtr = const_cast<char*>(SB->getBufferStart()); 314 315 size_t BytesLeft = MapSize; 316 if (lseek(FD, Offset, SEEK_SET) == -1) 317 return error_code(errno, posix_category()); 318 319 while (BytesLeft) { 320 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft); 321 if (NumRead == -1) { 322 if (errno == EINTR) 323 continue; 324 // Error while reading. 325 return error_code(errno, posix_category()); 326 } else if (NumRead == 0) { 327 // We hit EOF early, truncate and terminate buffer. 328 Buf->BufferEnd = BufPtr; 329 *BufPtr = 0; 330 result.swap(SB); 331 return success; 332 } 333 BytesLeft -= NumRead; 334 BufPtr += NumRead; 335 } 336 337 result.swap(SB); 338 return success; 339 } 340 341 //===----------------------------------------------------------------------===// 342 // MemoryBuffer::getSTDIN implementation. 343 //===----------------------------------------------------------------------===// 344 345 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) { 346 // Read in all of the data from stdin, we cannot mmap stdin. 347 // 348 // FIXME: That isn't necessarily true, we should try to mmap stdin and 349 // fallback if it fails. 350 sys::Program::ChangeStdinToBinary(); 351 352 const ssize_t ChunkSize = 4096*4; 353 SmallString<ChunkSize> Buffer; 354 ssize_t ReadBytes; 355 // Read into Buffer until we hit EOF. 356 do { 357 Buffer.reserve(Buffer.size() + ChunkSize); 358 ReadBytes = read(0, Buffer.end(), ChunkSize); 359 if (ReadBytes == -1) { 360 if (errno == EINTR) continue; 361 return error_code(errno, posix_category()); 362 } 363 Buffer.set_size(Buffer.size() + ReadBytes); 364 } while (ReadBytes != 0); 365 366 result.reset(getMemBufferCopy(Buffer, "<stdin>")); 367 return success; 368 } 369