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