Unbreak build.
[oota-llvm.git] / lib / Support / MemoryBuffer.cpp
1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/System/MappedFile.h"
16 #include "llvm/System/Process.h"
17 #include <cassert>
18 #include <cstdio>
19 #include <cstring>
20 #include <cerrno>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // MemoryBuffer implementation itself.
25 //===----------------------------------------------------------------------===//
26
27 MemoryBuffer::~MemoryBuffer() {
28   if (MustDeleteBuffer)
29     delete [] BufferStart;
30 }
31
32 /// initCopyOf - Initialize this source buffer with a copy of the specified
33 /// memory range.  We make the copy so that we can null terminate it
34 /// successfully.
35 void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
36   size_t Size = BufEnd-BufStart;
37   BufferStart = new char[Size+1];
38   BufferEnd = BufferStart+Size;
39   memcpy(const_cast<char*>(BufferStart), BufStart, Size);
40   *const_cast<char*>(BufferEnd) = 0;   // Null terminate buffer.
41   MustDeleteBuffer = false;
42 }
43
44 /// init - Initialize this MemoryBuffer as a reference to externally allocated
45 /// memory, memory that we know is already null terminated.
46 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
47   assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
48   BufferStart = BufStart;
49   BufferEnd = BufEnd;
50   MustDeleteBuffer = false;
51 }
52
53 //===----------------------------------------------------------------------===//
54 // MemoryBufferMem implementation.
55 //===----------------------------------------------------------------------===//
56
57 namespace {
58 class MemoryBufferMem : public MemoryBuffer {
59   std::string FileID;
60 public:
61   MemoryBufferMem(const char *Start, const char *End, const char *FID)
62   : FileID(FID) {
63     init(Start, End);
64   }
65   
66   virtual const char *getBufferIdentifier() const {
67     return FileID.c_str();
68   }
69 };
70 }
71
72 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
73 /// that EndPtr[0] must be a null byte and be accessible!
74 MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr, 
75                                          const char *EndPtr,
76                                          const char *BufferName) {
77   return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
78 }
79
80 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
81 /// that is completely initialized to zeros.  Note that the caller should
82 /// initialize the memory allocated by this method.  The memory is owned by
83 /// the MemoryBuffer object.
84 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(unsigned Size,
85                                                   const char *BufferName) {
86   char *Buf = new char[Size+1];
87   Buf[Size] = 0;
88   MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
89   // The memory for this buffer is owned by the MemoryBuffer.
90   SB->MustDeleteBuffer = true;
91   return SB;
92 }
93
94 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
95 /// is completely initialized to zeros.  Note that the caller should
96 /// initialize the memory allocated by this method.  The memory is owned by
97 /// the MemoryBuffer object.
98 MemoryBuffer *MemoryBuffer::getNewMemBuffer(unsigned Size,
99                                             const char *BufferName) {
100   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
101   memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
102   return SB;
103 }
104
105
106 //===----------------------------------------------------------------------===//
107 // MemoryBufferMMapFile implementation.
108 //===----------------------------------------------------------------------===//
109
110 namespace {
111 class MemoryBufferMMapFile : public MemoryBuffer {
112   sys::MappedFile File;
113 public:
114   MemoryBufferMMapFile(const sys::Path &Filename);
115   
116   virtual const char *getBufferIdentifier() const {
117     return File.path().c_str();
118   }
119     
120   ~MemoryBufferMMapFile();
121 };
122 }
123
124 MemoryBufferMMapFile::MemoryBufferMMapFile(const sys::Path &Filename) {
125   // FIXME: This does an extra stat syscall to figure out the size, but we
126   // already know the size!
127   bool Failure = File.open(Filename);
128   Failure = Failure;  // Silence warning in no-asserts mode.
129   assert(!Failure && "Can't open file??");
130   
131   File.map();
132   
133   size_t Size = File.size();
134   
135   static unsigned PageSize = sys::Process::GetPageSize();
136   assert(((PageSize & (PageSize-1)) == 0) && PageSize &&
137          "Page size is not a power of 2!");
138   
139   // If this file is not an exact multiple of the system page size (common
140   // case), then the OS has zero terminated the buffer for us.
141   if ((Size & (PageSize-1))) {
142     init(File.charBase(), File.charBase()+Size);
143   } else {
144     // Otherwise, we allocate a new memory buffer and copy the data over
145     initCopyOf(File.charBase(), File.charBase()+Size);
146     
147     // No need to keep the file mapped any longer.
148     File.unmap();
149   }
150 }
151
152 MemoryBufferMMapFile::~MemoryBufferMMapFile() {
153   File.unmap();
154 }
155
156 //===----------------------------------------------------------------------===//
157 // MemoryBuffer::getFile implementation.
158 //===----------------------------------------------------------------------===//
159
160 MemoryBuffer *MemoryBuffer::getFile(const char *FilenameStart, unsigned FnSize,
161                                     int64_t FileSize) {
162   sys::PathWithStatus P(std::string(FilenameStart, FnSize));
163 #if 1
164   return new MemoryBufferMMapFile(P);
165 #else
166   // FIXME: We need an efficient and portable method to open a file and then use
167   // 'read' to copy the bits out.  The unix implementation is below.  This is
168   // an important optimization for clients that want to open large numbers of
169   // small files (using mmap on everything can easily exhaust address space!).
170   
171   // If the user didn't specify a filesize, do a stat to find it.
172   if (FileSize == -1) {
173     const sys::FileStatus *FS = P.getFileStatus();
174     if (FS == 0) return 0;  // Error stat'ing file.
175    
176     FileSize = FS->fileSize;
177   }
178   
179   // If the file is larger than some threshold, use mmap, otherwise use 'read'.
180   if (FileSize >= 4096*4)
181     return new MemoryBufferMMapFile(P);
182   
183   MemoryBuffer *SB = getNewUninitMemBuffer(FileSize, FilenameStart);
184   char *BufPtr = const_cast<char*>(SB->getBufferStart());
185   
186   int FD = ::open(FilenameStart, O_RDONLY);
187   if (FD == -1) {
188     delete SB;
189     return 0;
190   }
191   
192   unsigned BytesLeft = FileSize;
193   while (BytesLeft) {
194     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
195     if (NumRead != -1) {
196       BytesLeft -= NumRead;
197       BufPtr += NumRead;
198     } else if (errno == EINTR) {
199       // try again
200     } else {
201       // error reading.
202       close(FD);
203       delete SB;
204       return 0;
205     }
206   }
207   close(FD);
208   
209   return SB;
210 #endif
211 }
212
213
214 //===----------------------------------------------------------------------===//
215 // MemoryBuffer::getSTDIN implementation.
216 //===----------------------------------------------------------------------===//
217
218 namespace {
219 class STDINBufferFile : public MemoryBuffer {
220 public:
221   virtual const char *getBufferIdentifier() const {
222     return "<stdin>";
223   }
224 };
225 }
226
227 MemoryBuffer *MemoryBuffer::getSTDIN() {
228   char Buffer[4096*4];
229   
230   std::vector<char> FileData;
231   
232   // Read in all of the data from stdin, we cannot mmap stdin.
233   while (size_t ReadBytes = fread(Buffer, 1, 4096*4, stdin))
234     FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
235   
236   size_t Size = FileData.size();
237   MemoryBuffer *B = new STDINBufferFile();
238   B->initCopyOf(&FileData[0], &FileData[Size]);
239   return B;
240 }