Don't open the file again in the gold plugin. To be able to do this, update
[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/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   assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
51   BufferStart = BufStart;
52   BufferEnd = BufEnd;
53 }
54
55 //===----------------------------------------------------------------------===//
56 // MemoryBufferMem implementation.
57 //===----------------------------------------------------------------------===//
58
59 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
60 /// null-terminates it.
61 static void CopyStringRef(char *Memory, StringRef Data) {
62   memcpy(Memory, Data.data(), Data.size());
63   Memory[Data.size()] = 0; // Null terminate string.
64 }
65
66 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
67 template <typename T>
68 static T* GetNamedBuffer(StringRef Buffer, StringRef Name) {
69   char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
70   CopyStringRef(Mem + sizeof(T), Name);
71   return new (Mem) T(Buffer);
72 }
73
74 namespace {
75 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
76 class MemoryBufferMem : public MemoryBuffer {
77 public:
78   MemoryBufferMem(StringRef InputData) {
79     init(InputData.begin(), InputData.end());
80   }
81
82   virtual const char *getBufferIdentifier() const {
83      // The name is stored after the class itself.
84     return reinterpret_cast<const char*>(this + 1);
85   }
86 };
87 }
88
89 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
90 /// that EndPtr[0] must be a null byte and be accessible!
91 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
92                                          StringRef BufferName) {
93   return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName);
94 }
95
96 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
97 /// copying the contents and taking ownership of it.  This has no requirements
98 /// on EndPtr[0].
99 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
100                                              StringRef BufferName) {
101   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
102   if (!Buf) return 0;
103   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
104          InputData.size());
105   return Buf;
106 }
107
108 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
109 /// that is not initialized.  Note that the caller should initialize the
110 /// memory allocated by this method.  The memory is owned by the MemoryBuffer
111 /// object.
112 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
113                                                   StringRef BufferName) {
114   // Allocate space for the MemoryBuffer, the data and the name. It is important
115   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
116   size_t AlignedStringLen =
117     RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
118                        sizeof(void*)); // TODO: Is sizeof(void*) enough?
119   size_t RealLen = AlignedStringLen + Size + 1;
120   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
121   if (!Mem) return 0;
122
123   // The name is stored after the class itself.
124   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
125
126   // The buffer begins after the name and must be aligned.
127   char *Buf = Mem + AlignedStringLen;
128   Buf[Size] = 0; // Null terminate buffer.
129
130   return new (Mem) MemoryBufferMem(StringRef(Buf, Size));
131 }
132
133 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
134 /// is completely initialized to zeros.  Note that the caller should
135 /// initialize the memory allocated by this method.  The memory is owned by
136 /// the MemoryBuffer object.
137 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
138   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
139   if (!SB) return 0;
140   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
141   return SB;
142 }
143
144
145 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
146 /// if the Filename is "-".  If an error occurs, this returns null and fills
147 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
148 /// returns an empty buffer.
149 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
150                                         OwningPtr<MemoryBuffer> &result,
151                                         int64_t FileSize) {
152   if (Filename == "-")
153     return getSTDIN(result);
154   return getFile(Filename, result, FileSize);
155 }
156
157 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
158                                         OwningPtr<MemoryBuffer> &result,
159                                         int64_t FileSize) {
160   if (strcmp(Filename, "-") == 0)
161     return getSTDIN(result);
162   return getFile(Filename, result, FileSize);
163 }
164
165 //===----------------------------------------------------------------------===//
166 // MemoryBuffer::getFile implementation.
167 //===----------------------------------------------------------------------===//
168
169 namespace {
170 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
171 /// sys::Path::MapInFilePages method.  When destroyed, it calls the
172 /// sys::Path::UnMapFilePages method.
173 class MemoryBufferMMapFile : public MemoryBufferMem {
174 public:
175   MemoryBufferMMapFile(StringRef Buffer)
176     : MemoryBufferMem(Buffer) { }
177
178   ~MemoryBufferMMapFile() {
179     sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
180   }
181 };
182 }
183
184 error_code MemoryBuffer::getFile(StringRef Filename,
185                                  OwningPtr<MemoryBuffer> &result,
186                                  int64_t FileSize) {
187   // Ensure the path is null terminated.
188   SmallString<256> PathBuf(Filename.begin(), Filename.end());
189   return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
190 }
191
192 error_code MemoryBuffer::getFile(const char *Filename,
193                                  OwningPtr<MemoryBuffer> &result,
194                                  int64_t FileSize) {
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     return error_code(errno, posix_category());
202   }
203   error_code ret = getOpenFile(FD, Filename, result, FileSize);
204   close(FD);
205   return ret;
206 }
207
208 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
209                                      OwningPtr<MemoryBuffer> &result,
210                                      int64_t FileSize) {
211   // If we don't know the file size, use fstat to find out.  fstat on an open
212   // file descriptor is cheaper than stat on a random path.
213   if (FileSize == -1) {
214     struct stat FileInfo;
215     // TODO: This should use fstat64 when available.
216     if (fstat(FD, &FileInfo) == -1) {
217       return error_code(errno, posix_category());
218     }
219     FileSize = FileInfo.st_size;
220   }
221
222
223   // If the file is large, try to use mmap to read it in.  We don't use mmap
224   // for small files, because this can severely fragment our address space. Also
225   // don't try to map files that are exactly a multiple of the system page size,
226   // as the file would not have the required null terminator.
227   //
228   // FIXME: Can we just mmap an extra page in the latter case?
229   if (FileSize >= 4096*4 &&
230       (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
231     if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
232       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
233         StringRef(Pages, FileSize), Filename));
234       return success;
235     }
236   }
237
238   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
239   if (!Buf) {
240     // Failed to create a buffer. The only way it can fail is if
241     // new(std::nothrow) returns 0.
242     return make_error_code(errc::not_enough_memory);
243   }
244
245   OwningPtr<MemoryBuffer> SB(Buf);
246   char *BufPtr = const_cast<char*>(SB->getBufferStart());
247
248   size_t BytesLeft = FileSize;
249   while (BytesLeft) {
250     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
251     if (NumRead == -1) {
252       if (errno == EINTR)
253         continue;
254       // Error while reading.
255       return error_code(errno, posix_category());
256     } else if (NumRead == 0) {
257       // We hit EOF early, truncate and terminate buffer.
258       Buf->BufferEnd = BufPtr;
259       *BufPtr = 0;
260       result.swap(SB);
261       return success;
262     }
263     BytesLeft -= NumRead;
264     BufPtr += NumRead;
265   }
266
267   result.swap(SB);
268   return success;
269 }
270
271 //===----------------------------------------------------------------------===//
272 // MemoryBuffer::getSTDIN implementation.
273 //===----------------------------------------------------------------------===//
274
275 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
276   // Read in all of the data from stdin, we cannot mmap stdin.
277   //
278   // FIXME: That isn't necessarily true, we should try to mmap stdin and
279   // fallback if it fails.
280   sys::Program::ChangeStdinToBinary();
281
282   const ssize_t ChunkSize = 4096*4;
283   SmallString<ChunkSize> Buffer;
284   ssize_t ReadBytes;
285   // Read into Buffer until we hit EOF.
286   do {
287     Buffer.reserve(Buffer.size() + ChunkSize);
288     ReadBytes = read(0, Buffer.end(), ChunkSize);
289     if (ReadBytes == -1) {
290       if (errno == EINTR) continue;
291       return error_code(errno, posix_category());
292     }
293     Buffer.set_size(Buffer.size() + ReadBytes);
294   } while (ReadBytes != 0);
295
296   result.reset(getMemBufferCopy(Buffer, "<stdin>"));
297   return success;
298 }