Use %ull here.
[llvm/stm8.git] / lib / Support / MemoryBuffer.cpp
blobea72720b7f01c53e0cb7c799391cb0ab2c6b521a
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.
12 //===----------------------------------------------------------------------===//
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;
39 namespace { const llvm::error_code success; }
41 //===----------------------------------------------------------------------===//
42 // MemoryBuffer implementation itself.
43 //===----------------------------------------------------------------------===//
45 MemoryBuffer::~MemoryBuffer() { }
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 bool RequiresNullTerminator) {
51 assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
52 "Buffer is not null terminated!");
53 BufferStart = BufStart;
54 BufferEnd = BufEnd;
57 //===----------------------------------------------------------------------===//
58 // MemoryBufferMem implementation.
59 //===----------------------------------------------------------------------===//
61 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
62 /// null-terminates it.
63 static void CopyStringRef(char *Memory, StringRef Data) {
64 memcpy(Memory, Data.data(), Data.size());
65 Memory[Data.size()] = 0; // Null terminate string.
68 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
69 template <typename T>
70 static T* GetNamedBuffer(StringRef Buffer, StringRef Name,
71 bool RequiresNullTerminator) {
72 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
73 CopyStringRef(Mem + sizeof(T), Name);
74 return new (Mem) T(Buffer, RequiresNullTerminator);
77 namespace {
78 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
79 class MemoryBufferMem : public MemoryBuffer {
80 public:
81 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
82 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
85 virtual const char *getBufferIdentifier() const {
86 // The name is stored after the class itself.
87 return reinterpret_cast<const char*>(this + 1);
92 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
93 /// that EndPtr[0] must be a null byte and be accessible!
94 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
95 StringRef BufferName,
96 bool RequiresNullTerminator) {
97 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
98 RequiresNullTerminator);
101 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
102 /// copying the contents and taking ownership of it. This has no requirements
103 /// on EndPtr[0].
104 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
105 StringRef BufferName) {
106 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
107 if (!Buf) return 0;
108 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
109 InputData.size());
110 return Buf;
113 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
114 /// that is not initialized. Note that the caller should initialize the
115 /// memory allocated by this method. The memory is owned by the MemoryBuffer
116 /// object.
117 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
118 StringRef BufferName) {
119 // Allocate space for the MemoryBuffer, the data and the name. It is important
120 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
121 size_t AlignedStringLen =
122 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
123 sizeof(void*)); // TODO: Is sizeof(void*) enough?
124 size_t RealLen = AlignedStringLen + Size + 1;
125 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
126 if (!Mem) return 0;
128 // The name is stored after the class itself.
129 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
131 // The buffer begins after the name and must be aligned.
132 char *Buf = Mem + AlignedStringLen;
133 Buf[Size] = 0; // Null terminate buffer.
135 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
138 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
139 /// is completely initialized to zeros. Note that the caller should
140 /// initialize the memory allocated by this method. The memory is owned by
141 /// the MemoryBuffer object.
142 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
143 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
144 if (!SB) return 0;
145 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
146 return SB;
150 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
151 /// if the Filename is "-". If an error occurs, this returns null and fills
152 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
153 /// returns an empty buffer.
154 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
155 OwningPtr<MemoryBuffer> &result,
156 int64_t FileSize) {
157 if (Filename == "-")
158 return getSTDIN(result);
159 return getFile(Filename, result, FileSize);
162 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
163 OwningPtr<MemoryBuffer> &result,
164 int64_t FileSize) {
165 if (strcmp(Filename, "-") == 0)
166 return getSTDIN(result);
167 return getFile(Filename, result, FileSize);
170 //===----------------------------------------------------------------------===//
171 // MemoryBuffer::getFile implementation.
172 //===----------------------------------------------------------------------===//
174 namespace {
175 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
176 /// sys::Path::MapInFilePages method. When destroyed, it calls the
177 /// sys::Path::UnMapFilePages method.
178 class MemoryBufferMMapFile : public MemoryBufferMem {
179 public:
180 MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
181 : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
183 ~MemoryBufferMMapFile() {
184 static int PageSize = sys::Process::GetPageSize();
186 uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
187 size_t Size = getBufferSize();
188 uintptr_t RealStart = Start & ~(PageSize - 1);
189 size_t RealSize = Size + (Start - RealStart);
191 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
192 RealSize);
197 error_code MemoryBuffer::getFile(StringRef Filename,
198 OwningPtr<MemoryBuffer> &result,
199 int64_t FileSize,
200 bool RequiresNullTerminator) {
201 // Ensure the path is null terminated.
202 SmallString<256> PathBuf(Filename.begin(), Filename.end());
203 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
204 RequiresNullTerminator);
207 error_code MemoryBuffer::getFile(const char *Filename,
208 OwningPtr<MemoryBuffer> &result,
209 int64_t FileSize,
210 bool RequiresNullTerminator) {
211 int OpenFlags = O_RDONLY;
212 #ifdef O_BINARY
213 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
214 #endif
215 int FD = ::open(Filename, OpenFlags);
216 if (FD == -1) {
217 return error_code(errno, posix_category());
219 error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
220 0, RequiresNullTerminator);
221 close(FD);
222 return ret;
225 static bool shouldUseMmap(int FD,
226 size_t FileSize,
227 size_t MapSize,
228 off_t Offset,
229 bool RequiresNullTerminator,
230 int PageSize) {
231 // We don't use mmap for small files because this can severely fragment our
232 // address space.
233 if (MapSize < 4096*4)
234 return false;
236 if (!RequiresNullTerminator)
237 return true;
240 // If we don't know the file size, use fstat to find out. fstat on an open
241 // file descriptor is cheaper than stat on a random path.
242 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
243 // RequiresNullTerminator = false and MapSize != -1.
244 if (FileSize == size_t(-1)) {
245 struct stat FileInfo;
246 // TODO: This should use fstat64 when available.
247 if (fstat(FD, &FileInfo) == -1) {
248 return error_code(errno, posix_category());
250 FileSize = FileInfo.st_size;
253 // If we need a null terminator and the end of the map is inside the file,
254 // we cannot use mmap.
255 size_t End = Offset + MapSize;
256 assert(End <= FileSize);
257 if (End != FileSize)
258 return false;
260 // Don't try to map files that are exactly a multiple of the system page size
261 // if we need a null terminator.
262 if ((FileSize & (PageSize -1)) == 0)
263 return false;
265 return true;
268 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
269 OwningPtr<MemoryBuffer> &result,
270 size_t FileSize, size_t MapSize,
271 off_t Offset,
272 bool RequiresNullTerminator) {
273 static int PageSize = sys::Process::GetPageSize();
275 // Default is to map the full file.
276 if (MapSize == size_t(-1)) {
277 // If we don't know the file size, use fstat to find out. fstat on an open
278 // file descriptor is cheaper than stat on a random path.
279 if (FileSize == size_t(-1)) {
280 struct stat FileInfo;
281 // TODO: This should use fstat64 when available.
282 if (fstat(FD, &FileInfo) == -1) {
283 return error_code(errno, posix_category());
285 FileSize = FileInfo.st_size;
287 MapSize = FileSize;
290 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
291 PageSize)) {
292 off_t RealMapOffset = Offset & ~(PageSize - 1);
293 off_t Delta = Offset - RealMapOffset;
294 size_t RealMapSize = MapSize + Delta;
296 if (const char *Pages = sys::Path::MapInFilePages(FD,
297 RealMapSize,
298 RealMapOffset)) {
299 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
300 StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
301 return success;
305 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
306 if (!Buf) {
307 // Failed to create a buffer. The only way it can fail is if
308 // new(std::nothrow) returns 0.
309 return make_error_code(errc::not_enough_memory);
312 OwningPtr<MemoryBuffer> SB(Buf);
313 char *BufPtr = const_cast<char*>(SB->getBufferStart());
315 size_t BytesLeft = MapSize;
316 if (lseek(FD, Offset, SEEK_SET) == -1)
317 return error_code(errno, posix_category());
319 while (BytesLeft) {
320 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
321 if (NumRead == -1) {
322 if (errno == EINTR)
323 continue;
324 // Error while reading.
325 return error_code(errno, posix_category());
326 } else if (NumRead == 0) {
327 // We hit EOF early, truncate and terminate buffer.
328 Buf->BufferEnd = BufPtr;
329 *BufPtr = 0;
330 result.swap(SB);
331 return success;
333 BytesLeft -= NumRead;
334 BufPtr += NumRead;
337 result.swap(SB);
338 return success;
341 //===----------------------------------------------------------------------===//
342 // MemoryBuffer::getSTDIN implementation.
343 //===----------------------------------------------------------------------===//
345 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
346 // Read in all of the data from stdin, we cannot mmap stdin.
348 // FIXME: That isn't necessarily true, we should try to mmap stdin and
349 // fallback if it fails.
350 sys::Program::ChangeStdinToBinary();
352 const ssize_t ChunkSize = 4096*4;
353 SmallString<ChunkSize> Buffer;
354 ssize_t ReadBytes;
355 // Read into Buffer until we hit EOF.
356 do {
357 Buffer.reserve(Buffer.size() + ChunkSize);
358 ReadBytes = read(0, Buffer.end(), ChunkSize);
359 if (ReadBytes == -1) {
360 if (errno == EINTR) continue;
361 return error_code(errno, posix_category());
363 Buffer.set_size(Buffer.size() + ReadBytes);
364 } while (ReadBytes != 0);
366 result.reset(getMemBufferCopy(Buffer, "<stdin>"));
367 return success;