]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Support/MemoryBuffer.cpp
Fix a memory leak in if_delgroups() introduced in r334118.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Support / MemoryBuffer.cpp
1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the MemoryBuffer interface.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/Errno.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/Program.h"
23 #include "llvm/Support/SmallVectorMemoryBuffer.h"
24 #include <cassert>
25 #include <cerrno>
26 #include <cstring>
27 #include <new>
28 #include <sys/types.h>
29 #include <system_error>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
31 #include <unistd.h>
32 #else
33 #include <io.h>
34 #endif
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 // MemoryBuffer implementation itself.
39 //===----------------------------------------------------------------------===//
40
41 MemoryBuffer::~MemoryBuffer() { }
42
43 /// init - Initialize this MemoryBuffer as a reference to externally allocated
44 /// memory, memory that we know is already null terminated.
45 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
46                         bool RequiresNullTerminator) {
47   assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
48          "Buffer is not null terminated!");
49   BufferStart = BufStart;
50   BufferEnd = BufEnd;
51 }
52
53 //===----------------------------------------------------------------------===//
54 // MemoryBufferMem implementation.
55 //===----------------------------------------------------------------------===//
56
57 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
58 /// null-terminates it.
59 static void CopyStringRef(char *Memory, StringRef Data) {
60   if (!Data.empty())
61     memcpy(Memory, Data.data(), Data.size());
62   Memory[Data.size()] = 0; // Null terminate string.
63 }
64
65 namespace {
66 struct NamedBufferAlloc {
67   const Twine &Name;
68   NamedBufferAlloc(const Twine &Name) : Name(Name) {}
69 };
70 }
71
72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
73   SmallString<256> NameBuf;
74   StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
75
76   char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
77   CopyStringRef(Mem + N, NameRef);
78   return Mem;
79 }
80
81 namespace {
82 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
83 template<typename MB>
84 class MemoryBufferMem : public MB {
85 public:
86   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
87     MemoryBuffer::init(InputData.begin(), InputData.end(),
88                        RequiresNullTerminator);
89   }
90
91   /// Disable sized deallocation for MemoryBufferMem, because it has
92   /// tail-allocated data.
93   void operator delete(void *p) { ::operator delete(p); }
94
95   StringRef getBufferIdentifier() const override {
96     // The name is stored after the class itself.
97     return StringRef(reinterpret_cast<const char *>(this + 1));
98   }
99
100   MemoryBuffer::BufferKind getBufferKind() const override {
101     return MemoryBuffer::MemoryBuffer_Malloc;
102   }
103 };
104 }
105
106 template <typename MB>
107 static ErrorOr<std::unique_ptr<MB>>
108 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
109            uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile);
110
111 std::unique_ptr<MemoryBuffer>
112 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
113                            bool RequiresNullTerminator) {
114   auto *Ret = new (NamedBufferAlloc(BufferName))
115       MemoryBufferMem<MemoryBuffer>(InputData, RequiresNullTerminator);
116   return std::unique_ptr<MemoryBuffer>(Ret);
117 }
118
119 std::unique_ptr<MemoryBuffer>
120 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
121   return std::unique_ptr<MemoryBuffer>(getMemBuffer(
122       Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
123 }
124
125 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
126 getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) {
127   auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(InputData.size(), BufferName);
128   if (!Buf)
129     return make_error_code(errc::not_enough_memory);
130   memcpy(Buf->getBufferStart(), InputData.data(), InputData.size());
131   return std::move(Buf);
132 }
133
134 std::unique_ptr<MemoryBuffer>
135 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
136   auto Buf = getMemBufferCopyImpl(InputData, BufferName);
137   if (Buf)
138     return std::move(*Buf);
139   return nullptr;
140 }
141
142 ErrorOr<std::unique_ptr<MemoryBuffer>>
143 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
144                              bool RequiresNullTerminator) {
145   SmallString<256> NameBuf;
146   StringRef NameRef = Filename.toStringRef(NameBuf);
147
148   if (NameRef == "-")
149     return getSTDIN();
150   return getFile(Filename, FileSize, RequiresNullTerminator);
151 }
152
153 ErrorOr<std::unique_ptr<MemoryBuffer>>
154 MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
155                            uint64_t Offset, bool IsVolatile) {
156   return getFileAux<MemoryBuffer>(FilePath, -1, MapSize, Offset, false,
157                                   IsVolatile);
158 }
159
160 //===----------------------------------------------------------------------===//
161 // MemoryBuffer::getFile implementation.
162 //===----------------------------------------------------------------------===//
163
164 namespace {
165 /// Memory maps a file descriptor using sys::fs::mapped_file_region.
166 ///
167 /// This handles converting the offset into a legal offset on the platform.
168 template<typename MB>
169 class MemoryBufferMMapFile : public MB {
170   sys::fs::mapped_file_region MFR;
171
172   static uint64_t getLegalMapOffset(uint64_t Offset) {
173     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
174   }
175
176   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
177     return Len + (Offset - getLegalMapOffset(Offset));
178   }
179
180   const char *getStart(uint64_t Len, uint64_t Offset) {
181     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
182   }
183
184 public:
185   MemoryBufferMMapFile(bool RequiresNullTerminator, sys::fs::file_t FD, uint64_t Len,
186                        uint64_t Offset, std::error_code &EC)
187       : MFR(FD, MB::Mapmode, getLegalMapSize(Len, Offset),
188             getLegalMapOffset(Offset), EC) {
189     if (!EC) {
190       const char *Start = getStart(Len, Offset);
191       MemoryBuffer::init(Start, Start + Len, RequiresNullTerminator);
192     }
193   }
194
195   /// Disable sized deallocation for MemoryBufferMMapFile, because it has
196   /// tail-allocated data.
197   void operator delete(void *p) { ::operator delete(p); }
198
199   StringRef getBufferIdentifier() const override {
200     // The name is stored after the class itself.
201     return StringRef(reinterpret_cast<const char *>(this + 1));
202   }
203
204   MemoryBuffer::BufferKind getBufferKind() const override {
205     return MemoryBuffer::MemoryBuffer_MMap;
206   }
207 };
208 }
209
210 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
211 getMemoryBufferForStream(sys::fs::file_t FD, const Twine &BufferName) {
212   const ssize_t ChunkSize = 4096*4;
213   SmallString<ChunkSize> Buffer;
214   size_t ReadBytes;
215   // Read into Buffer until we hit EOF.
216   do {
217     Buffer.reserve(Buffer.size() + ChunkSize);
218     if (auto EC = sys::fs::readNativeFile(
219             FD, makeMutableArrayRef(Buffer.end(), ChunkSize), &ReadBytes))
220       return EC;
221     Buffer.set_size(Buffer.size() + ReadBytes);
222   } while (ReadBytes != 0);
223
224   return getMemBufferCopyImpl(Buffer, BufferName);
225 }
226
227
228 ErrorOr<std::unique_ptr<MemoryBuffer>>
229 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
230                       bool RequiresNullTerminator, bool IsVolatile) {
231   return getFileAux<MemoryBuffer>(Filename, FileSize, FileSize, 0,
232                                   RequiresNullTerminator, IsVolatile);
233 }
234
235 template <typename MB>
236 static ErrorOr<std::unique_ptr<MB>>
237 getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
238                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
239                 bool IsVolatile);
240
241 template <typename MB>
242 static ErrorOr<std::unique_ptr<MB>>
243 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
244            uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile) {
245   Expected<sys::fs::file_t> FDOrErr =
246       sys::fs::openNativeFileForRead(Filename, sys::fs::OF_None);
247   if (!FDOrErr)
248     return errorToErrorCode(FDOrErr.takeError());
249   sys::fs::file_t FD = *FDOrErr;
250   auto Ret = getOpenFileImpl<MB>(FD, Filename, FileSize, MapSize, Offset,
251                                  RequiresNullTerminator, IsVolatile);
252   sys::fs::closeFile(FD);
253   return Ret;
254 }
255
256 ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
257 WritableMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
258                               bool IsVolatile) {
259   return getFileAux<WritableMemoryBuffer>(Filename, FileSize, FileSize, 0,
260                                           /*RequiresNullTerminator*/ false,
261                                           IsVolatile);
262 }
263
264 ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
265 WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
266                                    uint64_t Offset, bool IsVolatile) {
267   return getFileAux<WritableMemoryBuffer>(Filename, -1, MapSize, Offset, false,
268                                           IsVolatile);
269 }
270
271 std::unique_ptr<WritableMemoryBuffer>
272 WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
273   using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>;
274   // Allocate space for the MemoryBuffer, the data and the name. It is important
275   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
276   // TODO: Is 16-byte alignment enough?  We copy small object files with large
277   // alignment expectations into this buffer.
278   SmallString<256> NameBuf;
279   StringRef NameRef = BufferName.toStringRef(NameBuf);
280   size_t AlignedStringLen = alignTo(sizeof(MemBuffer) + NameRef.size() + 1, 16);
281   size_t RealLen = AlignedStringLen + Size + 1;
282   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
283   if (!Mem)
284     return nullptr;
285
286   // The name is stored after the class itself.
287   CopyStringRef(Mem + sizeof(MemBuffer), NameRef);
288
289   // The buffer begins after the name and must be aligned.
290   char *Buf = Mem + AlignedStringLen;
291   Buf[Size] = 0; // Null terminate buffer.
292
293   auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true);
294   return std::unique_ptr<WritableMemoryBuffer>(Ret);
295 }
296
297 std::unique_ptr<WritableMemoryBuffer>
298 WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) {
299   auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName);
300   if (!SB)
301     return nullptr;
302   memset(SB->getBufferStart(), 0, Size);
303   return SB;
304 }
305
306 static bool shouldUseMmap(sys::fs::file_t FD,
307                           size_t FileSize,
308                           size_t MapSize,
309                           off_t Offset,
310                           bool RequiresNullTerminator,
311                           int PageSize,
312                           bool IsVolatile) {
313   // mmap may leave the buffer without null terminator if the file size changed
314   // by the time the last page is mapped in, so avoid it if the file size is
315   // likely to change.
316   if (IsVolatile)
317     return false;
318
319   // We don't use mmap for small files because this can severely fragment our
320   // address space.
321   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
322     return false;
323
324   if (!RequiresNullTerminator)
325     return true;
326
327   // If we don't know the file size, use fstat to find out.  fstat on an open
328   // file descriptor is cheaper than stat on a random path.
329   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
330   // RequiresNullTerminator = false and MapSize != -1.
331   if (FileSize == size_t(-1)) {
332     sys::fs::file_status Status;
333     if (sys::fs::status(FD, Status))
334       return false;
335     FileSize = Status.getSize();
336   }
337
338   // If we need a null terminator and the end of the map is inside the file,
339   // we cannot use mmap.
340   size_t End = Offset + MapSize;
341   assert(End <= FileSize);
342   if (End != FileSize)
343     return false;
344
345   // Don't try to map files that are exactly a multiple of the system page size
346   // if we need a null terminator.
347   if ((FileSize & (PageSize -1)) == 0)
348     return false;
349
350 #if defined(__CYGWIN__)
351   // Don't try to map files that are exactly a multiple of the physical page size
352   // if we need a null terminator.
353   // FIXME: We should reorganize again getPageSize() on Win32.
354   if ((FileSize & (4096 - 1)) == 0)
355     return false;
356 #endif
357
358   return true;
359 }
360
361 static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
362 getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize,
363                  uint64_t Offset) {
364   Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForReadWrite(
365       Filename, sys::fs::CD_OpenExisting, sys::fs::OF_None);
366   if (!FDOrErr)
367     return errorToErrorCode(FDOrErr.takeError());
368   sys::fs::file_t FD = *FDOrErr;
369
370   // Default is to map the full file.
371   if (MapSize == uint64_t(-1)) {
372     // If we don't know the file size, use fstat to find out.  fstat on an open
373     // file descriptor is cheaper than stat on a random path.
374     if (FileSize == uint64_t(-1)) {
375       sys::fs::file_status Status;
376       std::error_code EC = sys::fs::status(FD, Status);
377       if (EC)
378         return EC;
379
380       // If this not a file or a block device (e.g. it's a named pipe
381       // or character device), we can't mmap it, so error out.
382       sys::fs::file_type Type = Status.type();
383       if (Type != sys::fs::file_type::regular_file &&
384           Type != sys::fs::file_type::block_file)
385         return make_error_code(errc::invalid_argument);
386
387       FileSize = Status.getSize();
388     }
389     MapSize = FileSize;
390   }
391
392   std::error_code EC;
393   std::unique_ptr<WriteThroughMemoryBuffer> Result(
394       new (NamedBufferAlloc(Filename))
395           MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize,
396                                                          Offset, EC));
397   if (EC)
398     return EC;
399   return std::move(Result);
400 }
401
402 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
403 WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) {
404   return getReadWriteFile(Filename, FileSize, FileSize, 0);
405 }
406
407 /// Map a subrange of the specified file as a WritableMemoryBuffer.
408 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
409 WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
410                                        uint64_t Offset) {
411   return getReadWriteFile(Filename, -1, MapSize, Offset);
412 }
413
414 template <typename MB>
415 static ErrorOr<std::unique_ptr<MB>>
416 getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
417                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
418                 bool IsVolatile) {
419   static int PageSize = sys::Process::getPageSizeEstimate();
420
421   // Default is to map the full file.
422   if (MapSize == uint64_t(-1)) {
423     // If we don't know the file size, use fstat to find out.  fstat on an open
424     // file descriptor is cheaper than stat on a random path.
425     if (FileSize == uint64_t(-1)) {
426       sys::fs::file_status Status;
427       std::error_code EC = sys::fs::status(FD, Status);
428       if (EC)
429         return EC;
430
431       // If this not a file or a block device (e.g. it's a named pipe
432       // or character device), we can't trust the size. Create the memory
433       // buffer by copying off the stream.
434       sys::fs::file_type Type = Status.type();
435       if (Type != sys::fs::file_type::regular_file &&
436           Type != sys::fs::file_type::block_file)
437         return getMemoryBufferForStream(FD, Filename);
438
439       FileSize = Status.getSize();
440     }
441     MapSize = FileSize;
442   }
443
444   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
445                     PageSize, IsVolatile)) {
446     std::error_code EC;
447     std::unique_ptr<MB> Result(
448         new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
449             RequiresNullTerminator, FD, MapSize, Offset, EC));
450     if (!EC)
451       return std::move(Result);
452   }
453
454   auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
455   if (!Buf) {
456     // Failed to create a buffer. The only way it can fail is if
457     // new(std::nothrow) returns 0.
458     return make_error_code(errc::not_enough_memory);
459   }
460
461   sys::fs::readNativeFileSlice(FD, Buf->getBuffer(), Offset);
462
463   return std::move(Buf);
464 }
465
466 ErrorOr<std::unique_ptr<MemoryBuffer>>
467 MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
468                           bool RequiresNullTerminator, bool IsVolatile) {
469   return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, FileSize, 0,
470                          RequiresNullTerminator, IsVolatile);
471 }
472
473 ErrorOr<std::unique_ptr<MemoryBuffer>>
474 MemoryBuffer::getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize,
475                                int64_t Offset, bool IsVolatile) {
476   assert(MapSize != uint64_t(-1));
477   return getOpenFileImpl<MemoryBuffer>(FD, Filename, -1, MapSize, Offset, false,
478                                        IsVolatile);
479 }
480
481 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
482   // Read in all of the data from stdin, we cannot mmap stdin.
483   //
484   // FIXME: That isn't necessarily true, we should try to mmap stdin and
485   // fallback if it fails.
486   sys::ChangeStdinToBinary();
487
488   return getMemoryBufferForStream(sys::fs::getStdinHandle(), "<stdin>");
489 }
490
491 ErrorOr<std::unique_ptr<MemoryBuffer>>
492 MemoryBuffer::getFileAsStream(const Twine &Filename) {
493   Expected<sys::fs::file_t> FDOrErr =
494       sys::fs::openNativeFileForRead(Filename, sys::fs::OF_None);
495   if (!FDOrErr)
496     return errorToErrorCode(FDOrErr.takeError());
497   sys::fs::file_t FD = *FDOrErr;
498   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
499       getMemoryBufferForStream(FD, Filename);
500   sys::fs::closeFile(FD);
501   return Ret;
502 }
503
504 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
505   StringRef Data = getBuffer();
506   StringRef Identifier = getBufferIdentifier();
507   return MemoryBufferRef(Data, Identifier);
508 }
509
510 SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() {}