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/STLExtras.h"
15#include "llvm/ADT/SmallString.h"
16#include "llvm/Config/config.h"
17#include "llvm/Support/Alignment.h"
18#include "llvm/Support/AutoConvert.h"
19#include "llvm/Support/Errc.h"
20#include "llvm/Support/Error.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/IOSandbox.h"
24#include "llvm/Support/Process.h"
25#include "llvm/Support/Program.h"
26#include "llvm/Support/SmallVectorMemoryBuffer.h"
27#include <algorithm>
28#include <cassert>
29#include <cstring>
30#include <new>
31#include <sys/types.h>
32#include <system_error>
33#if !defined(_MSC_VER) && !defined(__MINGW32__)
34#include <unistd.h>
35#else
36#include <io.h>
37#endif
38
39using namespace llvm;
40
41//===----------------------------------------------------------------------===//
42// MemoryBuffer implementation itself.
43//===----------------------------------------------------------------------===//
44
45MemoryBuffer::~MemoryBuffer() = default;
46
47/// init - Initialize this MemoryBuffer as a reference to externally allocated
48/// memory, memory that we know is already null terminated.
49void 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;
55}
56
57//===----------------------------------------------------------------------===//
58// MemoryBufferMem implementation.
59//===----------------------------------------------------------------------===//
60
61/// CopyStringRef - Copies contents of a StringRef into a block of memory and
62/// null-terminates it.
63static void CopyStringRef(char *Memory, StringRef Data) {
64 if (!Data.empty())
65 memcpy(dest: Memory, src: Data.data(), n: Data.size());
66 Memory[Data.size()] = 0; // Null terminate string.
67}
68
69namespace {
70struct NamedBufferAlloc {
71 const Twine &Name;
72 NamedBufferAlloc(const Twine &Name) : Name(Name) {}
73};
74} // namespace
75
76void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
77 SmallString<256> NameBuf;
78 StringRef NameRef = Alloc.Name.toStringRef(Out&: NameBuf);
79
80 // We use malloc() and manually handle it returning null instead of calling
81 // operator new because we need all uses of NamedBufferAlloc to be
82 // deallocated with a call to free() due to needing to use malloc() in
83 // WritableMemoryBuffer::getNewUninitMemBuffer() to work around the out-of-
84 // memory handler installed by default in LLVM. See operator delete() member
85 // functions within this file for the paired call to free().
86 char *Mem =
87 static_cast<char *>(std::malloc(size: N + sizeof(size_t) + NameRef.size() + 1));
88 if (!Mem)
89 llvm::report_bad_alloc_error(Reason: "Allocation failed");
90 *reinterpret_cast<size_t *>(Mem + N) = NameRef.size();
91 CopyStringRef(Memory: Mem + N + sizeof(size_t), Data: NameRef);
92 return Mem;
93}
94
95namespace {
96/// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
97template<typename MB>
98class MemoryBufferMem : public MB {
99public:
100 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
101 MemoryBuffer::init(BufStart: InputData.begin(), BufEnd: InputData.end(),
102 RequiresNullTerminator);
103 }
104
105 /// Disable sized deallocation for MemoryBufferMem, because it has
106 /// tail-allocated data.
107 void operator delete(void *p) { std::free(ptr: p); }
108
109 StringRef getBufferIdentifier() const override {
110 // The name is stored after the class itself.
111 return StringRef(reinterpret_cast<const char *>(this + 1) + sizeof(size_t),
112 *reinterpret_cast<const size_t *>(this + 1));
113 }
114
115 MemoryBuffer::BufferKind getBufferKind() const override {
116 return MemoryBuffer::MemoryBuffer_Malloc;
117 }
118};
119} // namespace
120
121template <typename MB>
122static ErrorOr<std::unique_ptr<MB>>
123getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset,
124 bool IsText, bool RequiresNullTerminator, bool IsVolatile,
125 std::optional<Align> Alignment);
126
127std::unique_ptr<MemoryBuffer>
128MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
129 bool RequiresNullTerminator) {
130 auto *Ret = new (NamedBufferAlloc(BufferName))
131 MemoryBufferMem<MemoryBuffer>(InputData, RequiresNullTerminator);
132 return std::unique_ptr<MemoryBuffer>(Ret);
133}
134
135std::unique_ptr<MemoryBuffer>
136MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
137 return std::unique_ptr<MemoryBuffer>(getMemBuffer(
138 InputData: Ref.getBuffer(), BufferName: Ref.getBufferIdentifier(), RequiresNullTerminator));
139}
140
141static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
142getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) {
143 auto Buf =
144 WritableMemoryBuffer::getNewUninitMemBuffer(Size: InputData.size(), BufferName);
145 if (!Buf)
146 return make_error_code(E: errc::not_enough_memory);
147 // Calling memcpy with null src/dst is UB, and an empty StringRef is
148 // represented with {nullptr, 0}.
149 llvm::copy(Range&: InputData, Out: Buf->getBufferStart());
150 return std::move(Buf);
151}
152
153std::unique_ptr<MemoryBuffer>
154MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
155 auto Buf = getMemBufferCopyImpl(InputData, BufferName);
156 if (Buf)
157 return std::move(*Buf);
158 return nullptr;
159}
160
161ErrorOr<std::unique_ptr<MemoryBuffer>>
162MemoryBuffer::getFileOrSTDIN(const Twine &Filename, bool IsText,
163 bool RequiresNullTerminator,
164 std::optional<Align> Alignment) {
165 sys::sandbox::violationIfEnabled();
166
167 SmallString<256> NameBuf;
168 StringRef NameRef = Filename.toStringRef(Out&: NameBuf);
169
170 if (NameRef == "-")
171 return getSTDIN();
172 return getFile(Filename, IsText, RequiresNullTerminator,
173 /*IsVolatile=*/false, Alignment);
174}
175
176ErrorOr<std::unique_ptr<MemoryBuffer>>
177MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
178 uint64_t Offset, bool IsVolatile,
179 std::optional<Align> Alignment) {
180 sys::sandbox::violationIfEnabled();
181
182 return getFileAux<MemoryBuffer>(Filename: FilePath, MapSize, Offset, /*IsText=*/false,
183 /*RequiresNullTerminator=*/false, IsVolatile,
184 Alignment);
185}
186
187//===----------------------------------------------------------------------===//
188// MemoryBuffer::getFile implementation.
189//===----------------------------------------------------------------------===//
190
191namespace {
192
193template <typename MB>
194constexpr sys::fs::mapped_file_region::mapmode Mapmode =
195 sys::fs::mapped_file_region::readonly;
196template <>
197constexpr sys::fs::mapped_file_region::mapmode Mapmode<MemoryBuffer> =
198 sys::fs::mapped_file_region::readonly;
199template <>
200constexpr sys::fs::mapped_file_region::mapmode Mapmode<WritableMemoryBuffer> =
201 sys::fs::mapped_file_region::priv;
202template <>
203constexpr sys::fs::mapped_file_region::mapmode
204 Mapmode<WriteThroughMemoryBuffer> = sys::fs::mapped_file_region::readwrite;
205
206/// Memory maps a file descriptor using sys::fs::mapped_file_region.
207///
208/// This handles converting the offset into a legal offset on the platform.
209template<typename MB>
210class MemoryBufferMMapFile : public MB {
211 sys::fs::mapped_file_region MFR;
212
213 static uint64_t getLegalMapOffset(uint64_t Offset) {
214 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
215 }
216
217 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
218 return Len + (Offset - getLegalMapOffset(Offset));
219 }
220
221 const char *getStart(uint64_t Len, uint64_t Offset) {
222 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
223 }
224
225public:
226 MemoryBufferMMapFile(bool RequiresNullTerminator, sys::fs::file_t FD, uint64_t Len,
227 uint64_t Offset, std::error_code &EC)
228 : MFR(FD, Mapmode<MB>, getLegalMapSize(Len, Offset),
229 getLegalMapOffset(Offset), EC) {
230 if (!EC) {
231 const char *Start = getStart(Len, Offset);
232 MemoryBuffer::init(BufStart: Start, BufEnd: Start + Len, RequiresNullTerminator);
233 }
234 }
235
236 /// Disable sized deallocation for MemoryBufferMMapFile, because it has
237 /// tail-allocated data.
238 void operator delete(void *p) { std::free(ptr: p); }
239
240 StringRef getBufferIdentifier() const override {
241 // The name is stored after the class itself.
242 return StringRef(reinterpret_cast<const char *>(this + 1) + sizeof(size_t),
243 *reinterpret_cast<const size_t *>(this + 1));
244 }
245
246 MemoryBuffer::BufferKind getBufferKind() const override {
247 return MemoryBuffer::MemoryBuffer_MMap;
248 }
249
250 void dontNeedIfMmap() override { MFR.dontNeed(); }
251 void willNeedIfMmap() override { MFR.willNeed(); }
252 void randomAccessIfMmap() override { MFR.randomAccess(); }
253};
254} // namespace
255
256static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
257getMemoryBufferForStream(sys::fs::file_t FD, const Twine &BufferName) {
258 SmallString<sys::fs::DefaultReadChunkSize> Buffer;
259 if (Error E = sys::fs::readNativeFileToEOF(FileHandle: FD, Buffer))
260 return errorToErrorCode(Err: std::move(E));
261 return getMemBufferCopyImpl(InputData: Buffer, BufferName);
262}
263
264ErrorOr<std::unique_ptr<MemoryBuffer>>
265MemoryBuffer::getFile(const Twine &Filename, bool IsText,
266 bool RequiresNullTerminator, bool IsVolatile,
267 std::optional<Align> Alignment) {
268 sys::sandbox::violationIfEnabled();
269
270 return getFileAux<MemoryBuffer>(Filename, /*MapSize=*/-1, /*Offset=*/0,
271 IsText, RequiresNullTerminator, IsVolatile,
272 Alignment);
273}
274
275template <typename MB>
276static ErrorOr<std::unique_ptr<MB>>
277getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
278 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
279 bool IsVolatile, std::optional<Align> Alignment);
280
281template <typename MB>
282static ErrorOr<std::unique_ptr<MB>>
283getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset,
284 bool IsText, bool RequiresNullTerminator, bool IsVolatile,
285 std::optional<Align> Alignment) {
286 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
287 Name: Filename, Flags: IsText ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None);
288 if (!FDOrErr)
289 return errorToErrorCode(Err: FDOrErr.takeError());
290 sys::fs::file_t FD = *FDOrErr;
291 auto Ret = getOpenFileImpl<MB>(FD, Filename, /*FileSize=*/-1, MapSize, Offset,
292 RequiresNullTerminator, IsVolatile, Alignment);
293 sys::fs::closeFile(F&: FD);
294 return Ret;
295}
296
297ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
298WritableMemoryBuffer::getFile(const Twine &Filename, bool IsVolatile,
299 std::optional<Align> Alignment) {
300 sys::sandbox::violationIfEnabled();
301
302 return getFileAux<WritableMemoryBuffer>(
303 Filename, /*MapSize=*/-1, /*Offset=*/0, /*IsText=*/false,
304 /*RequiresNullTerminator=*/false, IsVolatile, Alignment);
305}
306
307ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
308WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
309 uint64_t Offset, bool IsVolatile,
310 std::optional<Align> Alignment) {
311 sys::sandbox::violationIfEnabled();
312
313 return getFileAux<WritableMemoryBuffer>(
314 Filename, MapSize, Offset, /*IsText=*/false,
315 /*RequiresNullTerminator=*/false, IsVolatile, Alignment);
316}
317
318std::unique_ptr<WritableMemoryBuffer>
319WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size,
320 const Twine &BufferName,
321 std::optional<Align> Alignment) {
322 using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>;
323
324 // Use 16-byte alignment if no alignment is specified.
325 Align BufAlign = Alignment.value_or(u: Align(16));
326
327 // Allocate space for the MemoryBuffer, the data and the name. It is important
328 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
329 SmallString<256> NameBuf;
330 StringRef NameRef = BufferName.toStringRef(Out&: NameBuf);
331
332 size_t StringLen = sizeof(MemBuffer) + sizeof(size_t) + NameRef.size() + 1;
333 size_t RealLen = StringLen + Size + 1 + BufAlign.value();
334 if (RealLen <= Size) // Check for rollover.
335 return nullptr;
336 // We use a call to malloc() rather than a call to a non-throwing operator
337 // new() because LLVM unconditionally installs an out of memory new handler
338 // when exceptions are disabled. This new handler intentionally crashes to
339 // aid with debugging, but that makes non-throwing new calls unhelpful.
340 // See MemoryBufferMem::operator delete() for the paired call to free(), and
341 // llvm::install_out_of_memory_new_handler() for the installation of the
342 // custom new handler.
343 char *Mem = static_cast<char *>(std::malloc(size: RealLen));
344 if (!Mem)
345 return nullptr;
346
347 // The name is stored after the class itself.
348 *reinterpret_cast<size_t *>(Mem + sizeof(MemBuffer)) = NameRef.size();
349 CopyStringRef(Memory: Mem + sizeof(MemBuffer) + sizeof(size_t), Data: NameRef);
350
351 // The buffer begins after the name and must be aligned.
352 char *Buf = (char *)alignAddr(Addr: Mem + StringLen, Alignment: BufAlign);
353 Buf[Size] = 0; // Null terminate buffer.
354
355 auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true);
356 return std::unique_ptr<WritableMemoryBuffer>(Ret);
357}
358
359std::unique_ptr<WritableMemoryBuffer>
360WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) {
361 auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName);
362 if (!SB)
363 return nullptr;
364 memset(s: SB->getBufferStart(), c: 0, n: Size);
365 return SB;
366}
367
368static bool shouldUseMmap(sys::fs::file_t FD,
369 size_t FileSize,
370 size_t MapSize,
371 off_t Offset,
372 bool RequiresNullTerminator,
373 int PageSize,
374 bool IsVolatile) {
375 // mmap may leave the buffer without null terminator if the file size changed
376 // by the time the last page is mapped in, so avoid it if the file size is
377 // likely to change.
378 if (IsVolatile && RequiresNullTerminator)
379 return false;
380
381 // We don't use mmap for small files because this can severely fragment our
382 // address space.
383 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
384 return false;
385
386 if (!RequiresNullTerminator)
387 return true;
388
389 // If we don't know the file size, use fstat to find out. fstat on an open
390 // file descriptor is cheaper than stat on a random path.
391 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
392 // RequiresNullTerminator = false and MapSize != -1.
393 if (FileSize == size_t(-1)) {
394 ErrorOr<uint64_t> FS = sys::fs::file_size(FileHandle: FD);
395 if (!FS)
396 return false;
397 FileSize = *FS;
398 }
399
400 // If we need a null terminator and the end of the map is inside the file,
401 // we cannot use mmap.
402 size_t End = Offset + MapSize;
403 assert(End <= FileSize);
404 if (End != FileSize)
405 return false;
406
407 // Don't try to map files that are exactly a multiple of the system page size
408 // if we need a null terminator.
409 if ((FileSize & (PageSize -1)) == 0)
410 return false;
411
412#if defined(__CYGWIN__)
413 // Don't try to map files that are exactly a multiple of the physical page size
414 // if we need a null terminator.
415 // FIXME: We should reorganize again getPageSize() on Win32.
416 if ((FileSize & (4096 - 1)) == 0)
417 return false;
418#endif
419
420 return true;
421}
422
423static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
424getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize,
425 uint64_t Offset) {
426 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForReadWrite(
427 Name: Filename, Disp: sys::fs::CD_OpenExisting, Flags: sys::fs::OF_None);
428 if (!FDOrErr)
429 return errorToErrorCode(Err: FDOrErr.takeError());
430 sys::fs::file_t FD = *FDOrErr;
431
432 // Default is to map the full file.
433 if (MapSize == uint64_t(-1)) {
434 // If we don't know the file size, use fstat to find out. fstat on an open
435 // file descriptor is cheaper than stat on a random path.
436 if (FileSize == uint64_t(-1)) {
437 sys::fs::file_status Status;
438 std::error_code EC = sys::fs::status(F: FD, Result&: Status);
439 if (EC)
440 return EC;
441
442 // If this not a file or a block device (e.g. it's a named pipe
443 // or character device), we can't mmap it, so error out.
444 sys::fs::file_type Type = Status.type();
445 if (Type != sys::fs::file_type::regular_file &&
446 Type != sys::fs::file_type::block_file)
447 return make_error_code(E: errc::invalid_argument);
448
449 FileSize = Status.getSize();
450 }
451 MapSize = FileSize;
452 }
453
454 std::error_code EC;
455 std::unique_ptr<WriteThroughMemoryBuffer> Result(
456 new (NamedBufferAlloc(Filename))
457 MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize,
458 Offset, EC));
459 if (EC)
460 return EC;
461 return std::move(Result);
462}
463
464ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
465WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) {
466 sys::sandbox::violationIfEnabled();
467
468 return getReadWriteFile(Filename, FileSize, MapSize: FileSize, Offset: 0);
469}
470
471/// Map a subrange of the specified file as a WritableMemoryBuffer.
472ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
473WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
474 uint64_t Offset) {
475 sys::sandbox::violationIfEnabled();
476
477 return getReadWriteFile(Filename, FileSize: -1, MapSize, Offset);
478}
479
480template <typename MB>
481static ErrorOr<std::unique_ptr<MB>>
482getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
483 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
484 bool IsVolatile, std::optional<Align> Alignment) {
485 static int PageSize = sys::Process::getPageSizeEstimate();
486
487 // Default is to map the full file.
488 if (MapSize == uint64_t(-1)) {
489 // If we don't know the file size, use fstat to find out. fstat on an open
490 // file descriptor is cheaper than stat on a random path.
491 if (FileSize == uint64_t(-1)) {
492 sys::fs::file_status Status;
493 std::error_code EC = sys::fs::status(F: FD, Result&: Status);
494 if (EC)
495 return EC;
496
497 // If this not a file or a block device (e.g. it's a named pipe
498 // or character device), we can't trust the size. Create the memory
499 // buffer by copying off the stream.
500 sys::fs::file_type Type = Status.type();
501 if (Type != sys::fs::file_type::regular_file &&
502 Type != sys::fs::file_type::block_file)
503 return getMemoryBufferForStream(FD, BufferName: Filename);
504
505 FileSize = Status.getSize();
506 }
507 MapSize = FileSize;
508 }
509
510#ifdef __MVS__
511 ErrorOr<bool> NeedsConversion = needConversion(Filename, FD);
512 if (std::error_code EC = NeedsConversion.getError())
513 return EC;
514 // File size may increase due to EBCDIC -> UTF-8 conversion, therefore we
515 // cannot trust the file size and we create the memory buffer by copying
516 // off the stream.
517 // Note: This only works with the assumption of reading a full file (i.e,
518 // Offset == 0 and MapSize == FileSize). Reading a file slice does not work.
519 if (*NeedsConversion && Offset == 0 && MapSize == FileSize)
520 return getMemoryBufferForStream(FD, Filename);
521#endif
522
523 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
524 PageSize, IsVolatile)) {
525 std::error_code EC;
526 std::unique_ptr<MB> Result(
527 new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
528 RequiresNullTerminator, FD, MapSize, Offset, EC));
529 if (!EC) {
530 // On at least Linux, and possibly on other systems, mmap may return pages
531 // from the page cache that are not properly filled with trailing zeroes,
532 // if some prior user of the page wrote non-zero bytes. Detect this and
533 // don't use mmap in that case.
534 if (!RequiresNullTerminator || *Result->getBufferEnd() == '\0')
535 return std::move(Result);
536 }
537 }
538
539 auto Buf =
540 WritableMemoryBuffer::getNewUninitMemBuffer(Size: MapSize, BufferName: Filename, Alignment);
541 if (!Buf) {
542 // Failed to create a buffer. The only way it can fail is if
543 // new(std::nothrow) returns 0.
544 return make_error_code(E: errc::not_enough_memory);
545 }
546
547 // Read until EOF, zero-initialize the rest.
548 MutableArrayRef<char> ToRead = Buf->getBuffer();
549 while (!ToRead.empty()) {
550 Expected<size_t> ReadBytes =
551 sys::fs::readNativeFileSlice(FileHandle: FD, Buf: ToRead, Offset);
552 if (!ReadBytes)
553 return errorToErrorCode(Err: ReadBytes.takeError());
554 if (*ReadBytes == 0) {
555 std::memset(s: ToRead.data(), c: 0, n: ToRead.size());
556 break;
557 }
558 ToRead = ToRead.drop_front(N: *ReadBytes);
559 Offset += *ReadBytes;
560 }
561
562 return std::move(Buf);
563}
564
565ErrorOr<std::unique_ptr<MemoryBuffer>>
566MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename,
567 uint64_t FileSize, bool RequiresNullTerminator,
568 bool IsVolatile, std::optional<Align> Alignment) {
569 sys::sandbox::violationIfEnabled();
570
571 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, MapSize: FileSize, Offset: 0,
572 RequiresNullTerminator, IsVolatile,
573 Alignment);
574}
575
576ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getOpenFileSlice(
577 sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset,
578 bool IsVolatile, std::optional<Align> Alignment) {
579 assert(MapSize != uint64_t(-1));
580
581 sys::sandbox::violationIfEnabled();
582
583 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize: -1, MapSize, Offset, RequiresNullTerminator: false,
584 IsVolatile, Alignment);
585}
586
587ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
588 sys::sandbox::violationIfEnabled();
589
590 // Read in all of the data from stdin, we cannot mmap stdin.
591 //
592 // FIXME: That isn't necessarily true, we should try to mmap stdin and
593 // fallback if it fails.
594 sys::ChangeStdinMode(Flags: sys::fs::OF_Text);
595
596 return getMemoryBufferForStream(FD: sys::fs::getStdinHandle(), BufferName: "<stdin>");
597}
598
599ErrorOr<std::unique_ptr<MemoryBuffer>>
600MemoryBuffer::getFileAsStream(const Twine &Filename) {
601 sys::sandbox::violationIfEnabled();
602
603 Expected<sys::fs::file_t> FDOrErr =
604 sys::fs::openNativeFileForRead(Name: Filename, Flags: sys::fs::OF_None);
605 if (!FDOrErr)
606 return errorToErrorCode(Err: FDOrErr.takeError());
607 sys::fs::file_t FD = *FDOrErr;
608 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
609 getMemoryBufferForStream(FD, BufferName: Filename);
610 sys::fs::closeFile(F&: FD);
611 return Ret;
612}
613
614MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
615 StringRef Data = getBuffer();
616 StringRef Identifier = getBufferIdentifier();
617 return MemoryBufferRef(Data, Identifier);
618}
619
620SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() = default;
621