17 #include "llvm/Config/config.h" 33 #include <system_error> 36 #if defined(HAVE_FCNTL_H) 40 #if defined(HAVE_UNISTD_H) 44 #if defined(__CYGWIN__) 51 # define STDIN_FILENO 0 54 # define STDOUT_FILENO 1 57 # define STDERR_FILENO 2 82 assert(OutBufCur == OutBufStart &&
83 "raw_ostream destructor called with non-empty buffer!");
85 if (BufferMode == BufferKind::InternalBuffer)
86 delete [] OutBufStart;
103 void raw_ostream::SetBufferAndMode(
char *BufferStart,
size_t Size,
105 assert(((Mode == BufferKind::Unbuffered && !BufferStart &&
Size == 0) ||
106 (Mode != BufferKind::Unbuffered && BufferStart &&
Size != 0)) &&
107 "stream must be unbuffered or have at least one byte");
112 if (BufferMode == BufferKind::InternalBuffer)
113 delete [] OutBufStart;
114 OutBufStart = BufferStart;
115 OutBufEnd = OutBufStart+
Size;
116 OutBufCur = OutBufStart;
119 assert(OutBufStart <= OutBufEnd &&
"Invalid size!");
156 for (
int Idx = 0; Idx < 16; ++Idx) {
157 *
this <<
format(
"%02" PRIX32, UUID[Idx]);
158 if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
166 bool UseHexEscapes) {
167 for (
unsigned char c : Str) {
170 *
this <<
'\\' <<
'\\';
173 *
this <<
'\\' <<
't';
176 *
this <<
'\\' <<
'n';
179 *
this <<
'\\' <<
'"';
189 *
this <<
'\\' <<
'x';
190 *this << hexdigit((c >> 4 & 0xF));
191 *this << hexdigit((c >> 0) & 0xF);
195 *this << char('0' + ((c >> 6) & 7));
196 *this << char('0' + ((c >> 3) & 7));
197 *this << char('0' + ((c >> 0) & 7));
215 void raw_ostream::flush_nonempty() {
216 assert(OutBufCur > OutBufStart &&
"Invalid call to flush_nonempty.");
217 size_t Length = OutBufCur - OutBufStart;
218 OutBufCur = OutBufStart;
219 write_impl(OutBufStart, Length);
226 if (BufferMode == BufferKind::Unbuffered) {
227 write_impl(reinterpret_cast<char*>(&C), 1);
246 if (BufferMode == BufferKind::Unbuffered) {
247 write_impl(Ptr, Size);
252 return write(Ptr, Size);
255 size_t NumBytes = OutBufEnd - OutBufCur;
261 assert(NumBytes != 0 &&
"undefined behavior");
262 size_t BytesToWrite = Size - (Size % NumBytes);
263 write_impl(Ptr, BytesToWrite);
264 size_t BytesRemaining = Size - BytesToWrite;
265 if (BytesRemaining >
size_t(OutBufEnd - OutBufCur)) {
267 return write(Ptr + BytesToWrite, BytesRemaining);
269 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
275 copy_to_buffer(Ptr, NumBytes);
277 return write(Ptr + NumBytes, Size - NumBytes);
280 copy_to_buffer(Ptr, Size);
285 void raw_ostream::copy_to_buffer(
const char *Ptr,
size_t Size) {
286 assert(Size <=
size_t(OutBufEnd - OutBufCur) &&
"Buffer overrun!");
297 memcpy(OutBufCur, Ptr, Size);
308 size_t NextBufferSize = 127;
309 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
310 if (BufferBytesLeft > 3) {
311 size_t BytesUsed = Fmt.
print(OutBufCur, BufferBytesLeft);
314 if (BytesUsed <= BufferBytesLeft) {
315 OutBufCur += BytesUsed;
321 NextBufferSize = BytesUsed;
333 size_t BytesUsed = Fmt.
print(V.
data(), NextBufferSize);
336 if (BytesUsed <= NextBufferSize)
340 assert(BytesUsed > NextBufferSize &&
"Didn't grow buffer!?");
341 NextBufferSize = BytesUsed;
356 const size_t Difference = FS.Width - FS.Str.
size();
357 switch (FS.Justify) {
367 int PadAmount = Difference / 2;
370 this->
indent(Difference - PadAmount);
382 if (FN.Upper && FN.HexPrefix)
384 else if (FN.Upper && !FN.HexPrefix)
386 else if (!FN.Upper && FN.HexPrefix)
395 if (Buffer.
size() < FN.Width)
403 if (FB.Bytes.
empty())
406 size_t LineIndex = 0;
407 auto Bytes = FB.Bytes;
408 const size_t Size = Bytes.size();
410 uint64_t OffsetWidth = 0;
411 if (FB.FirstByteOffset.
hasValue()) {
415 size_t Lines = Size / FB.NumPerLine;
416 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
420 OffsetWidth = std::max<uint64_t>(4,
llvm::alignTo(Power, 4) / 4);
424 unsigned NumByteGroups =
425 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
426 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
428 while (!Bytes.empty()) {
431 if (FB.FirstByteOffset.
hasValue()) {
437 auto Line = Bytes.take_front(FB.NumPerLine);
439 size_t CharsPrinted = 0;
441 for (
size_t I = 0;
I < Line.size(); ++
I, CharsPrinted += 2) {
442 if (
I && (
I % FB.ByteGroupSize) == 0) {
452 assert(BlockCharWidth >= CharsPrinted);
453 indent(BlockCharWidth - CharsPrinted + 2);
457 for (uint8_t Byte : Line) {
459 *this << static_cast<char>(Byte);
466 Bytes = Bytes.drop_front(Line.size());
467 LineIndex += Line.size();
468 if (LineIndex < Size)
476 static const char Chars[] = {
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
477 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
478 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
479 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
480 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C, C};
484 return OS.
write(Chars, NumChars);
487 unsigned NumToWrite = std::min(NumChars,
489 OS.
write(Chars, NumToWrite);
490 NumChars -= NumToWrite;
497 return write_padding<' '>(*
this, NumSpaces);
502 return write_padding<'\0'>(*
this, NumZeros);
505 void raw_ostream::anchor() {}
523 "Cannot make a raw_ostream from a read-only descriptor!");
527 if (Filename ==
"-") {
528 EC = std::error_code();
533 return STDOUT_FILENO;
586 if (FD <= STDERR_FILENO)
592 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
596 off_t loc = ::lseek(FD, 0, SEEK_CUR);
600 std::error_code EC =
status(FD, Status);
603 SupportsSeeking = loc != (off_t)-1;
605 if (!SupportsSeeking)
608 pos =
static_cast<uint64_t
>(loc);
656 if (
auto EC = sys::windows::UTF8ToUTF16(Data, WideText))
661 size_t MaxWriteSize = WideText.
size();
663 MaxWriteSize = 32767;
665 size_t WCharsWritten = 0;
667 size_t WCharsToWrite =
668 std::min(MaxWriteSize, WideText.
size() - WCharsWritten);
669 DWORD ActuallyWritten;
671 ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
672 WCharsToWrite, &ActuallyWritten,
681 WCharsWritten += ActuallyWritten;
682 }
while (WCharsWritten != WideText.
size());
687 void raw_fd_ostream::write_impl(
const char *Ptr,
size_t Size) {
688 assert(FD >= 0 &&
"File already closed.");
694 if (IsWindowsConsole)
695 if (write_console_impl(FD,
StringRef(Ptr, Size)))
702 size_t MaxWriteSize = INT32_MAX;
704 #if defined(__linux__) 707 MaxWriteSize = 1024 * 1024 * 1024;
711 size_t ChunkSize = std::min(Size, MaxWriteSize);
712 ssize_t ret =
::write(FD, Ptr, ChunkSize);
723 if (errno == EINTR || errno == EAGAIN
725 || errno == EWOULDBLOCK
731 error_detected(std::error_code(errno, std::generic_category()));
753 assert(SupportsSeeking &&
"Stream does not support seeking!");
756 pos = ::_lseeki64(FD, off, SEEK_SET);
757 #elif defined(HAVE_LSEEK64) 758 pos = ::lseek64(FD, off, SEEK_SET);
760 pos = ::lseek(FD, off, SEEK_SET);
762 if (pos == (uint64_t)-1)
763 error_detected(std::error_code(errno, std::generic_category()));
767 void raw_fd_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
769 uint64_t Pos =
tell();
775 size_t raw_fd_ostream::preferred_buffer_size()
const {
782 if (IsWindowsConsole)
785 #elif !defined(__minix) 787 assert(FD >= 0 &&
"File not yet open!");
789 if (fstat(FD, &statbuf) != 0)
795 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
798 return statbuf.st_blksize;
811 const char *colorcode =
816 size_t len = strlen(colorcode);
817 write(colorcode, len);
832 size_t len = strlen(colorcode);
833 write(colorcode, len);
848 size_t len = strlen(colorcode);
849 write(colorcode, len);
864 void raw_fd_ostream::anchor() {}
902 void raw_string_ostream::write_impl(
const char *Ptr,
size_t Size) {
903 OS.append(Ptr, Size);
910 uint64_t raw_svector_ostream::current_pos()
const {
return OS.size(); }
912 void raw_svector_ostream::write_impl(
const char *Ptr,
size_t Size) {
913 OS.append(Ptr, Ptr + Size);
916 void raw_svector_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
934 void raw_null_ostream::write_impl(
const char *Ptr,
size_t Size) {
937 uint64_t raw_null_ostream::current_pos()
const {
941 void raw_null_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
944 void raw_pwrite_stream::anchor() {}
946 void buffer_ostream::anchor() {}
bool has_colors() const override
This function determines if this stream is displayed and supports colors.
bool is_displayed() const override
This function determines if this stream is connected to a "tty" or "console" window.
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...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
bool isPrint(char C)
Checks whether character C is printable.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
static const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
#define LLVM_UNLIKELY(EXPR)
static const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
std::error_code ChangeStdoutToBinary()
A raw_ostream that discards all output.
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
~raw_string_ostream() override
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. ...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
A raw_ostream that writes to an SmallVector or SmallString.
raw_fd_ostream(StringRef Filename, std::error_code &EC)
Open the specified file for writing.
static bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window...
block Block Frequency true
Represents the result of a call to sys::fs::status().
std::error_code error() const
raw_ostream & write_uuid(const uuid_t UUID)
void write_double(raw_ostream &S, double D, FloatStyle Style, Optional< size_t > Precision=None)
static bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
const T & getValue() const LLVM_LVALUE_FUNCTION
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
LLVM_NODISCARD size_t size() const
size - Get the string size.
~raw_fd_ostream() override
The file should be opened in text mode on platforms that make this distinction.
raw_ostream & operator<<(char C)
static const Colors YELLOW
static raw_ostream & write_padding(raw_ostream &OS, unsigned NumChars)
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
raw_ostream & resetColor() override
Resets the colors to terminal defaults.
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
static const Colors GREEN
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
void SetUnbuffered()
Set the stream to be unbuffered.
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...
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static const Colors RESET
~raw_null_ostream() override
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
raw_ostream & write(unsigned char C)
static int getFD(StringRef Filename, std::error_code &EC, sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, sys::fs::OpenFlags Flags)
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '', ' ', '"', and anything that doesn't satisfy llvm::isPrint into an escape...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
std::pair< llvm::MachO::Target, std::string > UUID
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
size_t GetNumBytesInBuffer() const
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Provides a library for accessing information about this process and other processes on the operating ...
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, Optional< size_t > Width=None)
A raw_ostream that writes to a file descriptor.
pointer data()
Return a pointer to the vector's buffer, even if empty().
static const Colors BLACK
void close()
Manually flush the stream and close the file.
An abstract base class for streams implementations that also support a pwrite operation.
static const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual raw_ostream & resetColor()
Resets the colors to terminal defaults.
CD_CreateAlways - When opening a file:
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
raw_ostream & changeColor(enum Colors colors, bool bold=false, bool bg=false) override
Changes the foreground color of text that will be output from this point forward. ...
static std::error_code SafelyCloseFileDescriptor(int FD)
static const Colors SAVEDCOLOR
uint64_t tell() const
tell - Return the current offset with the file.
This class implements an extremely fast bulk output stream that can only output to a stream...
static const Colors MAGENTA
StringRef - Represent a constant reference to a string, i.e.
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
raw_ostream & reverseColor() override
Reverses the foreground and background colors.
static const Colors WHITE
bool empty() const
empty - Check if the array is empty.