Add overloads for getFile and getFileOrSTDIN which take a const char *
[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/System/Errno.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/System/Process.h"
20 #include "llvm/System/Program.h"
21 #include <cassert>
22 #include <cstdio>
23 #include <cstring>
24 #include <cerrno>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #if !defined(_MSC_VER) && !defined(__MINGW32__)
28 #include <unistd.h>
29 #include <sys/uio.h>
30 #else
31 #include <io.h>
32 #endif
33 #include <fcntl.h>
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 // MemoryBuffer implementation itself.
38 //===----------------------------------------------------------------------===//
39
40 MemoryBuffer::~MemoryBuffer() {
41   if (MustDeleteBuffer)
42     free((void*)BufferStart);
43 }
44
45 /// initCopyOf - Initialize this source buffer with a copy of the specified
46 /// memory range.  We make the copy so that we can null terminate it
47 /// successfully.
48 void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
49   size_t Size = BufEnd-BufStart;
50   BufferStart = (char *)malloc(Size+1);
51   BufferEnd = BufferStart+Size;
52   memcpy(const_cast<char*>(BufferStart), BufStart, Size);
53   *const_cast<char*>(BufferEnd) = 0;   // Null terminate buffer.
54   MustDeleteBuffer = true;
55 }
56
57 /// init - Initialize this MemoryBuffer as a reference to externally allocated
58 /// memory, memory that we know is already null terminated.
59 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
60   assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
61   BufferStart = BufStart;
62   BufferEnd = BufEnd;
63   MustDeleteBuffer = false;
64 }
65
66 //===----------------------------------------------------------------------===//
67 // MemoryBufferMem implementation.
68 //===----------------------------------------------------------------------===//
69
70 namespace {
71 class MemoryBufferMem : public MemoryBuffer {
72   std::string FileID;
73 public:
74   MemoryBufferMem(StringRef InputData, StringRef FID, bool Copy = false)
75   : FileID(FID) {
76     if (!Copy)
77       init(InputData.data(), InputData.data()+InputData.size());
78     else
79       initCopyOf(InputData.data(), InputData.data()+InputData.size());
80   }
81   
82   virtual const char *getBufferIdentifier() const {
83     return FileID.c_str();
84   }
85 };
86 }
87
88 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
89 /// that EndPtr[0] must be a null byte and be accessible!
90 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
91                                          const char *BufferName) {
92   return new MemoryBufferMem(InputData, BufferName);
93 }
94
95 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
96 /// copying the contents and taking ownership of it.  This has no requirements
97 /// on EndPtr[0].
98 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
99                                              const char *BufferName) {
100   return new MemoryBufferMem(InputData, BufferName, true);
101 }
102
103 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
104 /// that is completely initialized to zeros.  Note that the caller should
105 /// initialize the memory allocated by this method.  The memory is owned by
106 /// the MemoryBuffer object.
107 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
108                                                   StringRef BufferName) {
109   char *Buf = (char *)malloc(Size+1);
110   if (!Buf) return 0;
111   Buf[Size] = 0;
112   MemoryBufferMem *SB = new MemoryBufferMem(StringRef(Buf, Size), BufferName);
113   // The memory for this buffer is owned by the MemoryBuffer.
114   SB->MustDeleteBuffer = true;
115   return SB;
116 }
117
118 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
119 /// is completely initialized to zeros.  Note that the caller should
120 /// initialize the memory allocated by this method.  The memory is owned by
121 /// the MemoryBuffer object.
122 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
123                                             const char *BufferName) {
124   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
125   if (!SB) return 0;
126   memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
127   return SB;
128 }
129
130
131 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
132 /// if the Filename is "-".  If an error occurs, this returns null and fills
133 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
134 /// returns an empty buffer.
135 MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
136                                            std::string *ErrStr,
137                                            int64_t FileSize,
138                                            struct stat *FileInfo) {
139   if (Filename == "-")
140     return getSTDIN(ErrStr);
141   return getFile(Filename, ErrStr, FileSize, FileInfo);
142 }
143
144 MemoryBuffer *MemoryBuffer::getFileOrSTDIN(const char *Filename,
145                                            std::string *ErrStr,
146                                            int64_t FileSize,
147                                            struct stat *FileInfo) {
148   if (strcmp(Filename, "-") == 0)
149     return getSTDIN(ErrStr);
150   return getFile(Filename, ErrStr, FileSize, FileInfo);
151 }
152
153 //===----------------------------------------------------------------------===//
154 // MemoryBuffer::getFile implementation.
155 //===----------------------------------------------------------------------===//
156
157 namespace {
158 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
159 /// sys::Path::MapInFilePages method.  When destroyed, it calls the
160 /// sys::Path::UnMapFilePages method.
161 class MemoryBufferMMapFile : public MemoryBuffer {
162   std::string Filename;
163 public:
164   MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
165     : Filename(filename) {
166     init(Pages, Pages+Size);
167   }
168   
169   virtual const char *getBufferIdentifier() const {
170     return Filename.c_str();
171   }
172     
173   ~MemoryBufferMMapFile() {
174     sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
175   }
176 };
177
178 /// FileCloser - RAII object to make sure an FD gets closed properly.
179 class FileCloser {
180   int FD;
181 public:
182   explicit FileCloser(int FD) : FD(FD) {}
183   ~FileCloser() { ::close(FD); }
184 };
185 }
186
187 MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
188                                     int64_t FileSize, struct stat *FileInfo) {
189   SmallString<256> PathBuf(Filename.begin(), Filename.end());
190   return MemoryBuffer::getFile(PathBuf.c_str(), ErrStr, FileSize, FileInfo);
191 }
192
193 MemoryBuffer *MemoryBuffer::getFile(const char *Filename, std::string *ErrStr,
194                                     int64_t FileSize, struct stat *FileInfo) {
195   int OpenFlags = O_RDONLY;
196 #ifdef O_BINARY
197   OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
198 #endif
199   int FD = ::open(Filename, OpenFlags);
200   if (FD == -1) {
201     if (ErrStr) *ErrStr = sys::StrError();
202     return 0;
203   }
204   FileCloser FC(FD); // Close FD on return.
205   
206   // If we don't know the file size, use fstat to find out.  fstat on an open
207   // file descriptor is cheaper than stat on a random path.
208   if (FileSize == -1 || FileInfo) {
209     struct stat MyFileInfo;
210     struct stat *FileInfoPtr = FileInfo? FileInfo : &MyFileInfo;
211     
212     // TODO: This should use fstat64 when available.
213     if (fstat(FD, FileInfoPtr) == -1) {
214       if (ErrStr) *ErrStr = sys::StrError();
215       return 0;
216     }
217     FileSize = FileInfoPtr->st_size;
218   }
219   
220   
221   // If the file is large, try to use mmap to read it in.  We don't use mmap
222   // for small files, because this can severely fragment our address space. Also
223   // don't try to map files that are exactly a multiple of the system page size,
224   // as the file would not have the required null terminator.
225   //
226   // FIXME: Can we just mmap an extra page in the latter case?
227   if (FileSize >= 4096*4 &&
228       (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
229     if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
230       // Close the file descriptor, now that the whole file is in memory.
231       return new MemoryBufferMMapFile(Filename, Pages, FileSize);
232     }
233   }
234
235   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
236   if (!Buf) {
237     // Failed to create a buffer.
238     if (ErrStr) *ErrStr = "could not allocate buffer";
239     return 0;
240   }
241
242   OwningPtr<MemoryBuffer> SB(Buf);
243   char *BufPtr = const_cast<char*>(SB->getBufferStart());
244
245   size_t BytesLeft = FileSize;
246   while (BytesLeft) {
247     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
248     if (NumRead == -1) {
249       if (errno == EINTR)
250         continue;
251       // Error while reading.
252       if (ErrStr) *ErrStr = sys::StrError();
253       return 0;
254     } else if (NumRead == 0) {
255       // We hit EOF early, truncate and terminate buffer.
256       Buf->BufferEnd = BufPtr;
257       *BufPtr = 0;
258       return SB.take();
259     }
260     BytesLeft -= NumRead;
261     BufPtr += NumRead;
262   }
263
264   return SB.take();
265 }
266
267 //===----------------------------------------------------------------------===//
268 // MemoryBuffer::getSTDIN implementation.
269 //===----------------------------------------------------------------------===//
270
271 namespace {
272 class STDINBufferFile : public MemoryBuffer {
273 public:
274   virtual const char *getBufferIdentifier() const {
275     return "<stdin>";
276   }
277 };
278 }
279
280 MemoryBuffer *MemoryBuffer::getSTDIN(std::string *ErrStr) {
281   char Buffer[4096*4];
282
283   std::vector<char> FileData;
284
285   // Read in all of the data from stdin, we cannot mmap stdin.
286   //
287   // FIXME: That isn't necessarily true, we should try to mmap stdin and
288   // fallback if it fails.
289   sys::Program::ChangeStdinToBinary();
290   size_t ReadBytes;
291   do {
292     ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
293     FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
294   } while (ReadBytes == sizeof(Buffer));
295
296   if (!feof(stdin)) {
297     if (ErrStr) *ErrStr = "error reading from stdin";
298     return 0;
299   }
300
301   FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
302   size_t Size = FileData.size();
303   MemoryBuffer *B = new STDINBufferFile();
304   B->initCopyOf(&FileData[0], &FileData[Size-1]);
305   return B;
306 }