15#include "llvm/Config/config.h"
35#if defined(HAVE_UNISTD_H)
39#if defined(__CYGWIN__)
46# define STDIN_FILENO 0
49# define STDOUT_FILENO 1
52# define STDERR_FILENO 2
67 assert(OutBufCur == OutBufStart &&
68 "raw_ostream destructor called with non-empty buffer!");
70 if (BufferMode == BufferKind::InternalBuffer)
71 delete [] OutBufStart;
95void raw_ostream::SetBufferAndMode(
char *BufferStart,
size_t Size,
97 assert(((Mode == BufferKind::Unbuffered && !BufferStart &&
Size == 0) ||
98 (Mode != BufferKind::Unbuffered && BufferStart &&
Size != 0)) &&
99 "stream must be unbuffered or have at least one byte");
104 if (BufferMode == BufferKind::InternalBuffer)
105 delete [] OutBufStart;
106 OutBufStart = BufferStart;
107 OutBufEnd = OutBufStart+
Size;
108 OutBufCur = OutBufStart;
111 assert(OutBufStart <= OutBufEnd &&
"Invalid size!");
148 for (
int Idx = 0; Idx < 16; ++Idx) {
150 if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
158 bool UseHexEscapes) {
159 for (
unsigned char c : Str) {
162 *
this <<
'\\' <<
'\\';
165 *
this <<
'\\' <<
't';
168 *
this <<
'\\' <<
'n';
171 *
this <<
'\\' <<
'"';
181 *
this <<
'\\' <<
'x';
187 *
this <<
char(
'0' + ((c >> 6) & 7));
188 *
this <<
char(
'0' + ((c >> 3) & 7));
189 *
this <<
char(
'0' + ((c >> 0) & 7));
207void raw_ostream::flush_nonempty() {
208 assert(OutBufCur > OutBufStart &&
"Invalid call to flush_nonempty.");
209 size_t Length = OutBufCur - OutBufStart;
210 OutBufCur = OutBufStart;
211 write_impl(OutBufStart,
Length);
218 if (BufferMode == BufferKind::Unbuffered) {
219 write_impl(
reinterpret_cast<char *
>(&
C), 1);
238 if (BufferMode == BufferKind::Unbuffered) {
247 size_t NumBytes = OutBufEnd - OutBufCur;
253 assert(NumBytes != 0 &&
"undefined behavior");
254 size_t BytesToWrite =
Size - (
Size % NumBytes);
255 write_impl(
Ptr, BytesToWrite);
256 size_t BytesRemaining =
Size - BytesToWrite;
257 if (BytesRemaining >
size_t(OutBufEnd - OutBufCur)) {
259 return write(
Ptr + BytesToWrite, BytesRemaining);
261 copy_to_buffer(
Ptr + BytesToWrite, BytesRemaining);
267 copy_to_buffer(
Ptr, NumBytes);
277void raw_ostream::copy_to_buffer(
const char *
Ptr,
size_t Size) {
278 assert(
Size <=
size_t(OutBufEnd - OutBufCur) &&
"Buffer overrun!");
283 case 4: OutBufCur[3] =
Ptr[3]; [[fallthrough]];
284 case 3: OutBufCur[2] =
Ptr[2]; [[fallthrough]];
285 case 2: OutBufCur[1] =
Ptr[1]; [[fallthrough]];
286 case 1: OutBufCur[0] =
Ptr[0]; [[fallthrough]];
300 size_t NextBufferSize = 127;
301 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
302 if (BufferBytesLeft > 3) {
303 size_t BytesUsed = Fmt.
print(OutBufCur, BufferBytesLeft);
306 if (BytesUsed <= BufferBytesLeft) {
307 OutBufCur += BytesUsed;
313 NextBufferSize = BytesUsed;
322 V.resize(NextBufferSize);
325 size_t BytesUsed = Fmt.
print(V.data(), NextBufferSize);
328 if (BytesUsed <= NextBufferSize)
329 return write(V.data(), BytesUsed);
332 assert(BytesUsed > NextBufferSize &&
"Didn't grow buffer!?");
333 NextBufferSize = BytesUsed;
343 unsigned LeftIndent = 0;
344 unsigned RightIndent = 0;
345 const ssize_t Difference = FS.Width - FS.Str.size();
346 if (Difference > 0) {
347 switch (FS.Justify) {
351 RightIndent = Difference;
354 LeftIndent = Difference;
357 LeftIndent = Difference / 2;
358 RightIndent = Difference - LeftIndent;
371 if (FN.Upper && FN.HexPrefix)
373 else if (FN.Upper && !FN.HexPrefix)
375 else if (!FN.Upper && FN.HexPrefix)
384 if (Buffer.
size() < FN.Width)
392 if (FB.Bytes.
empty())
395 size_t LineIndex = 0;
396 auto Bytes = FB.Bytes;
397 const size_t Size = Bytes.size();
400 if (FB.FirstByteOffset) {
404 size_t Lines =
Size / FB.NumPerLine;
405 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
409 OffsetWidth = std::max<uint64_t>(4,
llvm::alignTo(Power, 4) / 4);
413 unsigned NumByteGroups =
414 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
415 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
417 while (!Bytes.empty()) {
420 if (FB.FirstByteOffset) {
426 auto Line = Bytes.take_front(FB.NumPerLine);
428 size_t CharsPrinted = 0;
430 for (
size_t I = 0;
I < Line.size(); ++
I, CharsPrinted += 2) {
431 if (
I && (
I % FB.ByteGroupSize) == 0) {
441 assert(BlockCharWidth >= CharsPrinted);
442 indent(BlockCharWidth - CharsPrinted + 2);
448 *this << static_cast<char>(Byte);
455 Bytes = Bytes.drop_front(Line.size());
456 LineIndex += Line.size();
457 if (LineIndex <
Size)
465 static const char Chars[] = {
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
466 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
467 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
468 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
469 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C};
472 if (NumChars < std::size(Chars))
473 return OS.
write(Chars, NumChars);
476 unsigned NumToWrite = std::min(NumChars, (
unsigned)std::size(Chars) - 1);
477 OS.
write(Chars, NumToWrite);
478 NumChars -= NumToWrite;
493bool raw_ostream::prepare_colors() {
510 if (!prepare_colors())
513 const char *colorcode =
518 write(colorcode, strlen(colorcode));
523 if (!prepare_colors())
527 write(colorcode, strlen(colorcode));
532 if (!prepare_colors())
536 write(colorcode, strlen(colorcode));
540void raw_ostream::anchor() {}
558 "Cannot make a raw_ostream from a read-only descriptor!");
562 if (Filename ==
"-") {
563 EC = std::error_code();
628 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
632 off_t loc = ::lseek(FD, 0, SEEK_CUR);
634 std::error_code EC = status(FD,
Status);
638 SupportsSeeking = !EC && IsRegularFile;
640 SupportsSeeking = !EC && loc != (off_t)-1;
642 if (!SupportsSeeking)
693 if (
auto EC = sys::windows::UTF8ToUTF16(
Data, WideText))
698 size_t MaxWriteSize = WideText.
size();
700 MaxWriteSize = 32767;
702 size_t WCharsWritten = 0;
704 size_t WCharsToWrite =
705 std::min(MaxWriteSize, WideText.
size() - WCharsWritten);
706 DWORD ActuallyWritten;
708 ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
709 WCharsToWrite, &ActuallyWritten,
718 WCharsWritten += ActuallyWritten;
719 }
while (WCharsWritten != WideText.
size());
724void raw_fd_ostream::write_impl(
const char *
Ptr,
size_t Size) {
728 assert(FD >= 0 &&
"File already closed.");
734 if (IsWindowsConsole)
735 if (write_console_impl(FD, StringRef(
Ptr,
Size)))
742 size_t MaxWriteSize = INT32_MAX;
744#if defined(__linux__)
747 MaxWriteSize = 1024 * 1024 * 1024;
751 size_t ChunkSize = std::min(
Size, MaxWriteSize);
763 if (errno == EINTR || errno == EAGAIN
765 || errno == EWOULDBLOCK
772 DWORD WinLastError = GetLastError();
773 if (WinLastError == ERROR_BROKEN_PIPE ||
774 (WinLastError == ERROR_NO_DATA && errno == EINVAL)) {
775 llvm::sys::CallOneShotPipeSignalHandler();
802 assert(SupportsSeeking &&
"Stream does not support seeking!");
805 pos = ::_lseeki64(FD, off, SEEK_SET);
807 pos = ::lseek(FD, off, SEEK_SET);
814void raw_fd_ostream::pwrite_impl(
const char *
Ptr,
size_t Size,
829 if (IsWindowsConsole)
832#elif defined(__MVS__)
837 assert(FD >= 0 &&
"File not yet open!");
839 if (fstat(FD, &statbuf) != 0)
848 return statbuf.st_blksize;
877void raw_fd_ostream::anchor() {}
888 static std::error_code EC1 = enableAutoConversion(
STDOUT_FILENO);
899 static std::error_code EC = enableAutoConversion(
STDERR_FILENO);
927 EC = std::make_error_code(std::errc::invalid_argument);
951void raw_string_ostream::write_impl(
const char *
Ptr,
size_t Size) {
959uint64_t raw_svector_ostream::current_pos()
const {
return OS.
size(); }
961void raw_svector_ostream::write_impl(
const char *
Ptr,
size_t Size) {
965void raw_svector_ostream::pwrite_impl(
const char *
Ptr,
size_t Size,
987void raw_null_ostream::write_impl(
const char *
Ptr,
size_t Size) {
990uint64_t raw_null_ostream::current_pos()
const {
994void raw_null_ostream::pwrite_impl(
const char *
Ptr,
size_t Size,
997void raw_pwrite_stream::anchor() {}
999void buffer_ostream::anchor() {}
1001void buffer_unique_ostream::anchor() {}
1005 if (OutputFileName ==
"-")
1008 if (OutputFileName ==
"/dev/null") {
1022 if (
Error DiscardError = Temp->discard())
1023 return joinErrors(std::move(E), std::move(DiscardError));
1028 return Temp->keep(OutputFileName);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_UNLIKELY(EXPR)
Provides a library for accessing information about this process and other processes on the operating ...
std::pair< llvm::MachO::Target, std::string > UUID
bool empty() const
empty - Check if the array is empty.
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A raw_ostream that writes to a file descriptor.
bool is_displayed() const override
This function determines if this stream is connected to a "tty" or "console" window.
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
std::error_code error() const
void close()
Manually flush the stream and close the file.
void inc_pos(uint64_t Delta)
Expected< sys::fs::FileLocker > lock()
Locks the underlying file.
~raw_fd_ostream() override
bool has_colors() const override
This function determines if this stream is displayed and supports colors.
bool isRegularFile() const
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
int get_fd() const
Return the file descriptor.
Expected< sys::fs::FileLocker > tryLockFor(Duration const &Timeout)
Tries to lock the underlying file within the specified period.
raw_fd_ostream(StringRef Filename, std::error_code &EC)
Open the specified file for writing.
void error_detected(std::error_code EC)
Set the flag indicating that an output error has been encountered.
static LLVM_ABI bool classof(const raw_ostream *OS)
Check if OS is a pointer of type raw_fd_stream*.
LLVM_ABI raw_fd_stream(StringRef Filename, std::error_code &EC)
Open the specified file for reading/writing/seeking.
LLVM_ABI ssize_t read(char *Ptr, size_t Size)
This reads the Size bytes into a buffer pointed by Ptr.
A raw_ostream that discards all output.
~raw_null_ostream() override
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
raw_ostream(bool unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
uint64_t tell() const
tell - Return the current offset with the file.
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
virtual raw_ostream & changeColor(enum Colors Color, bool Bold=false, bool BG=false)
Changes the foreground color of text that will be output from this point forward.
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
virtual raw_ostream & resetColor()
Resets the colors to terminal defaults.
raw_ostream & write_uuid(const uuid_t UUID)
raw_ostream & operator<<(char C)
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '\t', ' ', '"', and anything that doesn't satisfy llvm::isPrint into an esca...
virtual raw_ostream & reverseColor()
Reverses the foreground and background colors.
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
raw_ostream & write(unsigned char C)
void SetUnbuffered()
Set the stream to be unbuffered.
virtual bool is_displayed() const
This function determines if this stream is connected to a "tty" or "console" window.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static constexpr Colors SAVEDCOLOR
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
virtual void enable_colors(bool enable)
size_t GetNumBytesInBuffer() const
OStreamKind get_kind() const
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
raw_pwrite_stream(bool Unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
A raw_ostream that writes to an SmallVector or SmallString.
static bool classof(const raw_ostream *OS)
static LLVM_ABI std::error_code SafelyCloseFileDescriptor(int FD)
static LLVM_ABI bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
static LLVM_ABI const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
static LLVM_ABI bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window.
static LLVM_ABI const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
static LLVM_ABI const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
static LLVM_ABI bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
static LLVM_ABI const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
RAII class that facilitates file locking.
static LLVM_ABI Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Represents the result of a call to sys::fs::status().
@ C
The default llvm calling convention, compatible with C.
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
LLVM_ABI std::error_code lockFile(int FD, LockKind Kind=LockKind::Exclusive)
Lock the file.
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LLVM_ABI std::error_code ChangeStdoutMode(fs::OpenFlags Flags)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
LLVM_ABI void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
char hexdigit(unsigned X, bool LowerCase=false)
hexdigit - Return the hexadecimal character for the given number X (which should be less than 16).
LLVM_ABI Error writeToOutput(StringRef OutputFileName, std::function< Error(raw_ostream &)> Write)
This helper creates an output stream and then passes it to Write.
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
@ Success
The lock was released successfully.
@ Timeout
Reached timeout while waiting for the owner to release the lock.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
LLVM_ABI void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
LLVM_ABI void write_double(raw_ostream &S, double D, FloatStyle Style, std::optional< size_t > Precision=std::nullopt)
bool isPrint(char C)
Checks whether character C is printable.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
static int getFD(StringRef Filename, std::error_code &EC, sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, sys::fs::OpenFlags Flags)
static raw_ostream & write_padding(raw_ostream &OS, unsigned NumChars)