In llvm::MemoryBuffer::getFile() remove an unnecessary stat call check.
[oota-llvm.git] / lib / Support / MemoryBuffer.cpp
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 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
76 template <typename T>
77 static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
78                          bool RequiresNullTerminator) {
79   char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
80   CopyStringRef(Mem + sizeof(T), Name);
81   return new (Mem) T(Buffer, RequiresNullTerminator);
82 }
83
84 namespace {
85 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
86 class MemoryBufferMem : public MemoryBuffer {
87 public:
88   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
89     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
90   }
91
92   virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
93      // The name is stored after the class itself.
94     return reinterpret_cast<const char*>(this + 1);
95   }
96
97   virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
98     return MemoryBuffer_Malloc;
99   }
100 };
101 }
102
103 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
104 /// that InputData must be a null terminated if RequiresNullTerminator is true!
105 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
106                                          StringRef BufferName,
107                                          bool RequiresNullTerminator) {
108   return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
109                                          RequiresNullTerminator);
110 }
111
112 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
113 /// copying the contents and taking ownership of it.  This has no requirements
114 /// on EndPtr[0].
115 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
116                                              StringRef BufferName) {
117   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
118   if (!Buf) return 0;
119   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
120          InputData.size());
121   return Buf;
122 }
123
124 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
125 /// that is not initialized.  Note that the caller should initialize the
126 /// memory allocated by this method.  The memory is owned by the MemoryBuffer
127 /// object.
128 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
129                                                   StringRef BufferName) {
130   // Allocate space for the MemoryBuffer, the data and the name. It is important
131   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
132   size_t AlignedStringLen =
133     RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
134                        sizeof(void*)); // TODO: Is sizeof(void*) enough?
135   size_t RealLen = AlignedStringLen + Size + 1;
136   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
137   if (!Mem) return 0;
138
139   // The name is stored after the class itself.
140   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
141
142   // The buffer begins after the name and must be aligned.
143   char *Buf = Mem + AlignedStringLen;
144   Buf[Size] = 0; // Null terminate buffer.
145
146   return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
147 }
148
149 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
150 /// is completely initialized to zeros.  Note that the caller should
151 /// initialize the memory allocated by this method.  The memory is owned by
152 /// the MemoryBuffer object.
153 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
154   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
155   if (!SB) return 0;
156   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
157   return SB;
158 }
159
160
161 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
162 /// if the Filename is "-".  If an error occurs, this returns null and fills
163 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
164 /// returns an empty buffer.
165 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
166                                         OwningPtr<MemoryBuffer> &result,
167                                         int64_t FileSize) {
168   if (Filename == "-")
169     return getSTDIN(result);
170   return getFile(Filename, result, FileSize);
171 }
172
173 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
174                                         OwningPtr<MemoryBuffer> &result,
175                                         int64_t FileSize) {
176   if (strcmp(Filename, "-") == 0)
177     return getSTDIN(result);
178   return getFile(Filename, result, FileSize);
179 }
180
181 //===----------------------------------------------------------------------===//
182 // MemoryBuffer::getFile implementation.
183 //===----------------------------------------------------------------------===//
184
185 namespace {
186 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
187 /// sys::Path::MapInFilePages method.  When destroyed, it calls the
188 /// sys::Path::UnMapFilePages method.
189 class MemoryBufferMMapFile : public MemoryBufferMem {
190 public:
191   MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
192     : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
193
194   ~MemoryBufferMMapFile() {
195     static int PageSize = sys::process::get_self()->page_size();
196
197     uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
198     size_t Size = getBufferSize();
199     uintptr_t RealStart = Start & ~(PageSize - 1);
200     size_t RealSize = Size + (Start - RealStart);
201
202     sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
203                               RealSize);
204   }
205
206   virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
207     return MemoryBuffer_MMap;
208   }
209 };
210 }
211
212 static error_code getMemoryBufferForStream(int FD, 
213                                            StringRef BufferName,
214                                            OwningPtr<MemoryBuffer> &result) {
215   const ssize_t ChunkSize = 4096*4;
216   SmallString<ChunkSize> Buffer;
217   ssize_t ReadBytes;
218   // Read into Buffer until we hit EOF.
219   do {
220     Buffer.reserve(Buffer.size() + ChunkSize);
221     ReadBytes = read(FD, Buffer.end(), ChunkSize);
222     if (ReadBytes == -1) {
223       if (errno == EINTR) continue;
224       return error_code(errno, posix_category());
225     }
226     Buffer.set_size(Buffer.size() + ReadBytes);
227   } while (ReadBytes != 0);
228
229   result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
230   return error_code::success();
231 }
232
233 error_code MemoryBuffer::getFile(StringRef Filename,
234                                  OwningPtr<MemoryBuffer> &result,
235                                  int64_t FileSize,
236                                  bool RequiresNullTerminator) {
237   // Ensure the path is null terminated.
238   SmallString<256> PathBuf(Filename.begin(), Filename.end());
239   return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
240                                RequiresNullTerminator);
241 }
242
243 error_code MemoryBuffer::getFile(const char *Filename,
244                                  OwningPtr<MemoryBuffer> &result,
245                                  int64_t FileSize,
246                                  bool RequiresNullTerminator) {
247   // FIXME: Review if this check is unnecessary on windows as well.
248 #ifdef LLVM_ON_WIN32
249   // First check that the "file" is not a directory
250   bool is_dir = false;
251   error_code err = sys::fs::is_directory(Filename, is_dir);
252   if (err)
253     return err;
254   if (is_dir)
255     return make_error_code(errc::is_a_directory);
256 #endif
257
258   int OpenFlags = O_RDONLY;
259 #ifdef O_BINARY
260   OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
261 #endif
262   int FD = ::open(Filename, OpenFlags);
263   if (FD == -1)
264     return error_code(errno, posix_category());
265
266   error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
267                                0, RequiresNullTerminator);
268   close(FD);
269   return ret;
270 }
271
272 static bool shouldUseMmap(int FD,
273                           size_t FileSize,
274                           size_t MapSize,
275                           off_t Offset,
276                           bool RequiresNullTerminator,
277                           int PageSize) {
278   // We don't use mmap for small files because this can severely fragment our
279   // address space.
280   if (MapSize < 4096*4)
281     return false;
282
283   if (!RequiresNullTerminator)
284     return true;
285
286
287   // If we don't know the file size, use fstat to find out.  fstat on an open
288   // file descriptor is cheaper than stat on a random path.
289   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
290   // RequiresNullTerminator = false and MapSize != -1.
291   if (FileSize == size_t(-1)) {
292     struct stat FileInfo;
293     // TODO: This should use fstat64 when available.
294     if (fstat(FD, &FileInfo) == -1) {
295       return error_code(errno, posix_category());
296     }
297     FileSize = FileInfo.st_size;
298   }
299
300   // If we need a null terminator and the end of the map is inside the file,
301   // we cannot use mmap.
302   size_t End = Offset + MapSize;
303   assert(End <= FileSize);
304   if (End != FileSize)
305     return false;
306
307   // Don't try to map files that are exactly a multiple of the system page size
308   // if we need a null terminator.
309   if ((FileSize & (PageSize -1)) == 0)
310     return false;
311
312   return true;
313 }
314
315 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
316                                      OwningPtr<MemoryBuffer> &result,
317                                      uint64_t FileSize, uint64_t MapSize,
318                                      int64_t Offset,
319                                      bool RequiresNullTerminator) {
320   static int PageSize = sys::process::get_self()->page_size();
321
322   // Default is to map the full file.
323   if (MapSize == uint64_t(-1)) {
324     // If we don't know the file size, use fstat to find out.  fstat on an open
325     // file descriptor is cheaper than stat on a random path.
326     if (FileSize == uint64_t(-1)) {
327       struct stat FileInfo;
328       // TODO: This should use fstat64 when available.
329       if (fstat(FD, &FileInfo) == -1) {
330         return error_code(errno, posix_category());
331       }
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       if (!S_ISREG(FileInfo.st_mode) && !S_ISBLK(FileInfo.st_mode)) {
337         return getMemoryBufferForStream(FD, Filename, result);
338       }
339
340       FileSize = FileInfo.st_size;
341     }
342     MapSize = FileSize;
343   }
344
345   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
346                     PageSize)) {
347     off_t RealMapOffset = Offset & ~(PageSize - 1);
348     off_t Delta = Offset - RealMapOffset;
349     size_t RealMapSize = MapSize + Delta;
350
351     if (const char *Pages = sys::Path::MapInFilePages(FD,
352                                                       RealMapSize,
353                                                       RealMapOffset)) {
354       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
355           StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
356       return error_code::success();
357     }
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   OwningPtr<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       assert(0 && "We got inaccurate FileSize value or fstat reported an "
390                    "invalid file size.");
391       *BufPtr = '\0'; // null-terminate at the actual size.
392       break;
393     }
394     BytesLeft -= NumRead;
395     BufPtr += NumRead;
396   }
397
398   result.swap(SB);
399   return error_code::success();
400 }
401
402 //===----------------------------------------------------------------------===//
403 // MemoryBuffer::getSTDIN implementation.
404 //===----------------------------------------------------------------------===//
405
406 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
407   // Read in all of the data from stdin, we cannot mmap stdin.
408   //
409   // FIXME: That isn't necessarily true, we should try to mmap stdin and
410   // fallback if it fails.
411   sys::Program::ChangeStdinToBinary();
412
413   return getMemoryBufferForStream(0, "<stdin>", result);
414 }