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};
253} // namespace
254
255static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
256getMemoryBufferForStream(sys::fs::file_t FD, const Twine &BufferName) {
257 SmallString<sys::fs::DefaultReadChunkSize> Buffer;
258 if (Error E = sys::fs::readNativeFileToEOF(FileHandle: FD, Buffer))
259 return errorToErrorCode(Err: std::move(E));
260 return getMemBufferCopyImpl(InputData: Buffer, BufferName);
261}
262
263ErrorOr<std::unique_ptr<MemoryBuffer>>
264MemoryBuffer::getFile(const Twine &Filename, bool IsText,
265 bool RequiresNullTerminator, bool IsVolatile,
266 std::optional<Align> Alignment) {
267 sys::sandbox::violationIfEnabled();
268
269 return getFileAux<MemoryBuffer>(Filename, /*MapSize=*/-1, /*Offset=*/0,
270 IsText, RequiresNullTerminator, IsVolatile,
271 Alignment);
272}
273
274template <typename MB>
275static ErrorOr<std::unique_ptr<MB>>
276getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
277 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
278 bool IsVolatile, std::optional<Align> Alignment);
279
280template <typename MB>
281static ErrorOr<std::unique_ptr<MB>>
282getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset,
283 bool IsText, bool RequiresNullTerminator, bool IsVolatile,
284 std::optional<Align> Alignment) {
285 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
286 Name: Filename, Flags: IsText ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None);
287 if (!FDOrErr)
288 return errorToErrorCode(Err: FDOrErr.takeError());
289 sys::fs::file_t FD = *FDOrErr;
290 auto Ret = getOpenFileImpl<MB>(FD, Filename, /*FileSize=*/-1, MapSize, Offset,
291 RequiresNullTerminator, IsVolatile, Alignment);
292 sys::fs::closeFile(F&: FD);
293 return Ret;
294}
295
296ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
297WritableMemoryBuffer::getFile(const Twine &Filename, bool IsVolatile,
298 std::optional<Align> Alignment) {
299 sys::sandbox::violationIfEnabled();
300
301 return getFileAux<WritableMemoryBuffer>(
302 Filename, /*MapSize=*/-1, /*Offset=*/0, /*IsText=*/false,
303 /*RequiresNullTerminator=*/false, IsVolatile, Alignment);
304}
305
306ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
307WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
308 uint64_t Offset, bool IsVolatile,
309 std::optional<Align> Alignment) {
310 sys::sandbox::violationIfEnabled();
311
312 return getFileAux<WritableMemoryBuffer>(
313 Filename, MapSize, Offset, /*IsText=*/false,
314 /*RequiresNullTerminator=*/false, IsVolatile, Alignment);
315}
316
317std::unique_ptr<WritableMemoryBuffer>
318WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size,
319 const Twine &BufferName,
320 std::optional<Align> Alignment) {
321 using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>;
322
323 // Use 16-byte alignment if no alignment is specified.
324 Align BufAlign = Alignment.value_or(u: Align(16));
325
326 // Allocate space for the MemoryBuffer, the data and the name. It is important
327 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
328 SmallString<256> NameBuf;
329 StringRef NameRef = BufferName.toStringRef(Out&: NameBuf);
330
331 size_t StringLen = sizeof(MemBuffer) + sizeof(size_t) + NameRef.size() + 1;
332 size_t RealLen = StringLen + Size + 1 + BufAlign.value();
333 if (RealLen <= Size) // Check for rollover.
334 return nullptr;
335 // We use a call to malloc() rather than a call to a non-throwing operator
336 // new() because LLVM unconditionally installs an out of memory new handler
337 // when exceptions are disabled. This new handler intentionally crashes to
338 // aid with debugging, but that makes non-throwing new calls unhelpful.
339 // See MemoryBufferMem::operator delete() for the paired call to free(), and
340 // llvm::install_out_of_memory_new_handler() for the installation of the
341 // custom new handler.
342 char *Mem = static_cast<char *>(std::malloc(size: RealLen));
343 if (!Mem)
344 return nullptr;
345
346 // The name is stored after the class itself.
347 *reinterpret_cast<size_t *>(Mem + sizeof(MemBuffer)) = NameRef.size();
348 CopyStringRef(Memory: Mem + sizeof(MemBuffer) + sizeof(size_t), Data: NameRef);
349
350 // The buffer begins after the name and must be aligned.
351 char *Buf = (char *)alignAddr(Addr: Mem + StringLen, Alignment: BufAlign);
352 Buf[Size] = 0; // Null terminate buffer.
353
354 auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true);
355 return std::unique_ptr<WritableMemoryBuffer>(Ret);
356}
357
358std::unique_ptr<WritableMemoryBuffer>
359WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) {
360 auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName);
361 if (!SB)
362 return nullptr;
363 memset(s: SB->getBufferStart(), c: 0, n: Size);
364 return SB;
365}
366
367static bool shouldUseMmap(sys::fs::file_t FD,
368 size_t FileSize,
369 size_t MapSize,
370 off_t Offset,
371 bool RequiresNullTerminator,
372 int PageSize,
373 bool IsVolatile) {
374#if defined(__MVS__)
375 // zOS Enhanced ASCII auto convert does not support mmap.
376 return false;
377#endif
378
379 // mmap may leave the buffer without null terminator if the file size changed
380 // by the time the last page is mapped in, so avoid it if the file size is
381 // likely to change.
382 if (IsVolatile && RequiresNullTerminator)
383 return false;
384
385 // We don't use mmap for small files because this can severely fragment our
386 // address space.
387 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
388 return false;
389
390 if (!RequiresNullTerminator)
391 return true;
392
393 // If we don't know the file size, use fstat to find out. fstat on an open
394 // file descriptor is cheaper than stat on a random path.
395 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
396 // RequiresNullTerminator = false and MapSize != -1.
397 if (FileSize == size_t(-1)) {
398 sys::fs::file_status Status;
399 if (sys::fs::status(FD, Result&: Status))
400 return false;
401 FileSize = Status.getSize();
402 }
403
404 // If we need a null terminator and the end of the map is inside the file,
405 // we cannot use mmap.
406 size_t End = Offset + MapSize;
407 assert(End <= FileSize);
408 if (End != FileSize)
409 return false;
410
411 // Don't try to map files that are exactly a multiple of the system page size
412 // if we need a null terminator.
413 if ((FileSize & (PageSize -1)) == 0)
414 return false;
415
416#if defined(__CYGWIN__)
417 // Don't try to map files that are exactly a multiple of the physical page size
418 // if we need a null terminator.
419 // FIXME: We should reorganize again getPageSize() on Win32.
420 if ((FileSize & (4096 - 1)) == 0)
421 return false;
422#endif
423
424 return true;
425}
426
427static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
428getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize,
429 uint64_t Offset) {
430 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForReadWrite(
431 Name: Filename, Disp: sys::fs::CD_OpenExisting, Flags: sys::fs::OF_None);
432 if (!FDOrErr)
433 return errorToErrorCode(Err: FDOrErr.takeError());
434 sys::fs::file_t FD = *FDOrErr;
435
436 // Default is to map the full file.
437 if (MapSize == uint64_t(-1)) {
438 // If we don't know the file size, use fstat to find out. fstat on an open
439 // file descriptor is cheaper than stat on a random path.
440 if (FileSize == uint64_t(-1)) {
441 sys::fs::file_status Status;
442 std::error_code EC = sys::fs::status(FD, Result&: Status);
443 if (EC)
444 return EC;
445
446 // If this not a file or a block device (e.g. it's a named pipe
447 // or character device), we can't mmap it, so error out.
448 sys::fs::file_type Type = Status.type();
449 if (Type != sys::fs::file_type::regular_file &&
450 Type != sys::fs::file_type::block_file)
451 return make_error_code(E: errc::invalid_argument);
452
453 FileSize = Status.getSize();
454 }
455 MapSize = FileSize;
456 }
457
458 std::error_code EC;
459 std::unique_ptr<WriteThroughMemoryBuffer> Result(
460 new (NamedBufferAlloc(Filename))
461 MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize,
462 Offset, EC));
463 if (EC)
464 return EC;
465 return std::move(Result);
466}
467
468ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
469WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) {
470 sys::sandbox::violationIfEnabled();
471
472 return getReadWriteFile(Filename, FileSize, MapSize: FileSize, Offset: 0);
473}
474
475/// Map a subrange of the specified file as a WritableMemoryBuffer.
476ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
477WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
478 uint64_t Offset) {
479 sys::sandbox::violationIfEnabled();
480
481 return getReadWriteFile(Filename, FileSize: -1, MapSize, Offset);
482}
483
484template <typename MB>
485static ErrorOr<std::unique_ptr<MB>>
486getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize,
487 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
488 bool IsVolatile, std::optional<Align> Alignment) {
489 static int PageSize = sys::Process::getPageSizeEstimate();
490
491 // Default is to map the full file.
492 if (MapSize == uint64_t(-1)) {
493 // If we don't know the file size, use fstat to find out. fstat on an open
494 // file descriptor is cheaper than stat on a random path.
495 if (FileSize == uint64_t(-1)) {
496 sys::fs::file_status Status;
497 std::error_code EC = sys::fs::status(FD, Result&: Status);
498 if (EC)
499 return EC;
500
501 // If this not a file or a block device (e.g. it's a named pipe
502 // or character device), we can't trust the size. Create the memory
503 // buffer by copying off the stream.
504 sys::fs::file_type Type = Status.type();
505 if (Type != sys::fs::file_type::regular_file &&
506 Type != sys::fs::file_type::block_file)
507 return getMemoryBufferForStream(FD, BufferName: Filename);
508
509 FileSize = Status.getSize();
510 }
511 MapSize = FileSize;
512 }
513
514 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
515 PageSize, IsVolatile)) {
516 std::error_code EC;
517 std::unique_ptr<MB> Result(
518 new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
519 RequiresNullTerminator, FD, MapSize, Offset, EC));
520 if (!EC) {
521 // On at least Linux, and possibly on other systems, mmap may return pages
522 // from the page cache that are not properly filled with trailing zeroes,
523 // if some prior user of the page wrote non-zero bytes. Detect this and
524 // don't use mmap in that case.
525 if (!RequiresNullTerminator || *Result->getBufferEnd() == '\0')
526 return std::move(Result);
527 }
528 }
529
530#ifdef __MVS__
531 ErrorOr<bool> NeedsConversion = needConversion(Filename, FD);
532 if (std::error_code EC = NeedsConversion.getError())
533 return EC;
534 // File size may increase due to EBCDIC -> UTF-8 conversion, therefore we
535 // cannot trust the file size and we create the memory buffer by copying
536 // off the stream.
537 // Note: This only works with the assumption of reading a full file (i.e,
538 // Offset == 0 and MapSize == FileSize). Reading a file slice does not work.
539 if (*NeedsConversion && Offset == 0 && MapSize == FileSize)
540 return getMemoryBufferForStream(FD, Filename);
541#endif
542
543 auto Buf =
544 WritableMemoryBuffer::getNewUninitMemBuffer(Size: MapSize, BufferName: Filename, Alignment);
545 if (!Buf) {
546 // Failed to create a buffer. The only way it can fail is if
547 // new(std::nothrow) returns 0.
548 return make_error_code(E: errc::not_enough_memory);
549 }
550
551 // Read until EOF, zero-initialize the rest.
552 MutableArrayRef<char> ToRead = Buf->getBuffer();
553 while (!ToRead.empty()) {
554 Expected<size_t> ReadBytes =
555 sys::fs::readNativeFileSlice(FileHandle: FD, Buf: ToRead, Offset);
556 if (!ReadBytes)
557 return errorToErrorCode(Err: ReadBytes.takeError());
558 if (*ReadBytes == 0) {
559 std::memset(s: ToRead.data(), c: 0, n: ToRead.size());
560 break;
561 }
562 ToRead = ToRead.drop_front(N: *ReadBytes);
563 Offset += *ReadBytes;
564 }
565
566 return std::move(Buf);
567}
568
569ErrorOr<std::unique_ptr<MemoryBuffer>>
570MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename,
571 uint64_t FileSize, bool RequiresNullTerminator,
572 bool IsVolatile, std::optional<Align> Alignment) {
573 sys::sandbox::violationIfEnabled();
574
575 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, MapSize: FileSize, Offset: 0,
576 RequiresNullTerminator, IsVolatile,
577 Alignment);
578}
579
580ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getOpenFileSlice(
581 sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, int64_t Offset,
582 bool IsVolatile, std::optional<Align> Alignment) {
583 assert(MapSize != uint64_t(-1));
584
585 sys::sandbox::violationIfEnabled();
586
587 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize: -1, MapSize, Offset, RequiresNullTerminator: false,
588 IsVolatile, Alignment);
589}
590
591ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
592 sys::sandbox::violationIfEnabled();
593
594 // Read in all of the data from stdin, we cannot mmap stdin.
595 //
596 // FIXME: That isn't necessarily true, we should try to mmap stdin and
597 // fallback if it fails.
598 sys::ChangeStdinMode(Flags: sys::fs::OF_Text);
599
600 return getMemoryBufferForStream(FD: sys::fs::getStdinHandle(), BufferName: "<stdin>");
601}
602
603ErrorOr<std::unique_ptr<MemoryBuffer>>
604MemoryBuffer::getFileAsStream(const Twine &Filename) {
605 sys::sandbox::violationIfEnabled();
606
607 Expected<sys::fs::file_t> FDOrErr =
608 sys::fs::openNativeFileForRead(Name: Filename, Flags: sys::fs::OF_None);
609 if (!FDOrErr)
610 return errorToErrorCode(Err: FDOrErr.takeError());
611 sys::fs::file_t FD = *FDOrErr;
612 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
613 getMemoryBufferForStream(FD, BufferName: Filename);
614 sys::fs::closeFile(F&: FD);
615 return Ret;
616}
617
618MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
619 StringRef Data = getBuffer();
620 StringRef Identifier = getBufferIdentifier();
621 return MemoryBufferRef(Data, Identifier);
622}
623
624SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() = default;
625