18 #include "llvm/Config/config.h" 34 #include <system_error> 37 #if defined(HAVE_FCNTL_H) 41 #if defined(HAVE_UNISTD_H) 45 #if defined(__CYGWIN__) 52 # define STDIN_FILENO 0 55 # define STDOUT_FILENO 1 58 # define STDERR_FILENO 2 72 assert(OutBufCur == OutBufStart &&
73 "raw_ostream destructor called with non-empty buffer!");
75 if (BufferMode == InternalBuffer)
76 delete [] OutBufStart;
93 void raw_ostream::SetBufferAndMode(
char *BufferStart,
size_t Size,
95 assert(((Mode == Unbuffered && !BufferStart &&
Size == 0) ||
96 (Mode != Unbuffered && BufferStart &&
Size != 0)) &&
97 "stream must be unbuffered or have at least one byte");
102 if (BufferMode == InternalBuffer)
103 delete [] OutBufStart;
104 OutBufStart = BufferStart;
105 OutBufEnd = OutBufStart+
Size;
106 OutBufCur = OutBufStart;
109 assert(OutBufStart <= OutBufEnd &&
"Invalid size!");
138 for (
int Idx = 0; Idx < 16; ++Idx) {
139 *
this <<
format(
"%02" PRIX32, UUID[Idx]);
140 if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
148 bool UseHexEscapes) {
149 for (
unsigned char c : Str) {
152 *
this <<
'\\' <<
'\\';
155 *
this <<
'\\' <<
't';
158 *
this <<
'\\' <<
'n';
161 *
this <<
'\\' <<
'"';
171 *
this <<
'\\' <<
'x';
172 *this << hexdigit((c >> 4 & 0xF));
173 *this << hexdigit((c >> 0) & 0xF);
177 *this << char('0' + ((c >> 6) & 7));
178 *this << char('0' + ((c >> 3) & 7));
179 *this << char('0' + ((c >> 0) & 7));
197 void raw_ostream::flush_nonempty() {
198 assert(OutBufCur > OutBufStart &&
"Invalid call to flush_nonempty.");
199 size_t Length = OutBufCur - OutBufStart;
200 OutBufCur = OutBufStart;
201 write_impl(OutBufStart, Length);
208 if (BufferMode == Unbuffered) {
209 write_impl(reinterpret_cast<char*>(&C), 1);
228 if (BufferMode == Unbuffered) {
229 write_impl(Ptr, Size);
234 return write(Ptr, Size);
237 size_t NumBytes = OutBufEnd - OutBufCur;
243 assert(NumBytes != 0 &&
"undefined behavior");
244 size_t BytesToWrite = Size - (Size % NumBytes);
245 write_impl(Ptr, BytesToWrite);
246 size_t BytesRemaining = Size - BytesToWrite;
247 if (BytesRemaining >
size_t(OutBufEnd - OutBufCur)) {
249 return write(Ptr + BytesToWrite, BytesRemaining);
251 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
257 copy_to_buffer(Ptr, NumBytes);
259 return write(Ptr + NumBytes, Size - NumBytes);
262 copy_to_buffer(Ptr, Size);
267 void raw_ostream::copy_to_buffer(
const char *Ptr,
size_t Size) {
268 assert(Size <=
size_t(OutBufEnd - OutBufCur) &&
"Buffer overrun!");
279 memcpy(OutBufCur, Ptr, Size);
290 size_t NextBufferSize = 127;
291 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
292 if (BufferBytesLeft > 3) {
293 size_t BytesUsed = Fmt.
print(OutBufCur, BufferBytesLeft);
296 if (BytesUsed <= BufferBytesLeft) {
297 OutBufCur += BytesUsed;
303 NextBufferSize = BytesUsed;
315 size_t BytesUsed = Fmt.
print(V.
data(), NextBufferSize);
318 if (BytesUsed <= NextBufferSize)
322 assert(BytesUsed > NextBufferSize &&
"Didn't grow buffer!?");
323 NextBufferSize = BytesUsed;
338 const size_t Difference = FS.Width - FS.Str.
size();
339 switch (FS.Justify) {
349 int PadAmount = Difference / 2;
352 this->
indent(Difference - PadAmount);
364 if (FN.Upper && FN.HexPrefix)
366 else if (FN.Upper && !FN.HexPrefix)
368 else if (!FN.Upper && FN.HexPrefix)
377 if (Buffer.
size() < FN.Width)
385 if (FB.Bytes.
empty())
388 size_t LineIndex = 0;
389 auto Bytes = FB.Bytes;
390 const size_t Size = Bytes.size();
392 uint64_t OffsetWidth = 0;
393 if (FB.FirstByteOffset.
hasValue()) {
397 size_t Lines = Size / FB.NumPerLine;
398 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
402 OffsetWidth = std::max<uint64_t>(4,
llvm::alignTo(Power, 4) / 4);
406 unsigned NumByteGroups =
407 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
408 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
410 while (!Bytes.empty()) {
413 if (FB.FirstByteOffset.
hasValue()) {
419 auto Line = Bytes.take_front(FB.NumPerLine);
421 size_t CharsPrinted = 0;
423 for (
size_t I = 0;
I < Line.size(); ++
I, CharsPrinted += 2) {
424 if (
I && (
I % FB.ByteGroupSize) == 0) {
434 assert(BlockCharWidth >= CharsPrinted);
435 indent(BlockCharWidth - CharsPrinted + 2);
439 for (uint8_t Byte : Line) {
441 *this << static_cast<char>(Byte);
448 Bytes = Bytes.drop_front(Line.size());
449 LineIndex += Line.size();
450 if (LineIndex < Size)
458 static const char Chars[] = {
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
459 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
460 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
461 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
462 C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C, C};
466 return OS.
write(Chars, NumChars);
469 unsigned NumToWrite = std::min(NumChars,
471 OS.
write(Chars, NumToWrite);
472 NumChars -= NumToWrite;
479 return write_padding<' '>(*
this, NumSpaces);
484 return write_padding<'\0'>(*
this, NumZeros);
487 void raw_ostream::anchor() {}
505 "Cannot make a raw_ostream from a read-only descriptor!");
509 if (Filename ==
"-") {
510 EC = std::error_code();
515 return STDOUT_FILENO;
568 if (FD <= STDERR_FILENO)
574 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
578 off_t loc = ::lseek(FD, 0, SEEK_CUR);
582 std::error_code EC =
status(FD, Status);
585 SupportsSeeking = loc != (off_t)-1;
587 if (!SupportsSeeking)
590 pos =
static_cast<uint64_t
>(loc);
638 if (
auto EC = sys::windows::UTF8ToUTF16(Data, WideText))
643 size_t MaxWriteSize = WideText.
size();
645 MaxWriteSize = 32767;
647 size_t WCharsWritten = 0;
649 size_t WCharsToWrite =
650 std::min(MaxWriteSize, WideText.
size() - WCharsWritten);
651 DWORD ActuallyWritten;
653 ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
654 WCharsToWrite, &ActuallyWritten,
663 WCharsWritten += ActuallyWritten;
664 }
while (WCharsWritten != WideText.
size());
669 void raw_fd_ostream::write_impl(
const char *Ptr,
size_t Size) {
670 assert(FD >= 0 &&
"File already closed.");
676 if (IsWindowsConsole)
677 if (write_console_impl(FD,
StringRef(Ptr, Size)))
684 size_t MaxWriteSize = INT32_MAX;
686 #if defined(__linux__) 689 MaxWriteSize = 1024 * 1024 * 1024;
693 size_t ChunkSize = std::min(Size, MaxWriteSize);
694 ssize_t ret =
::write(FD, Ptr, ChunkSize);
705 if (errno == EINTR || errno == EAGAIN
707 || errno == EWOULDBLOCK
713 error_detected(std::error_code(errno, std::generic_category()));
735 assert(SupportsSeeking &&
"Stream does not support seeking!");
738 pos = ::_lseeki64(FD, off, SEEK_SET);
739 #elif defined(HAVE_LSEEK64) 740 pos = ::lseek64(FD, off, SEEK_SET);
742 pos = ::lseek(FD, off, SEEK_SET);
744 if (pos == (uint64_t)-1)
745 error_detected(std::error_code(errno, std::generic_category()));
749 void raw_fd_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
751 uint64_t Pos =
tell();
757 size_t raw_fd_ostream::preferred_buffer_size()
const {
764 if (IsWindowsConsole)
767 #elif !defined(__minix) 769 assert(FD >= 0 &&
"File not yet open!");
771 if (fstat(FD, &statbuf) != 0)
777 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
780 return statbuf.st_blksize;
790 const char *colorcode =
794 size_t len = strlen(colorcode);
795 write(colorcode, len);
807 size_t len = strlen(colorcode);
808 write(colorcode, len);
820 size_t len = strlen(colorcode);
821 write(colorcode, len);
836 void raw_fd_ostream::anchor() {}
874 void raw_string_ostream::write_impl(
const char *Ptr,
size_t Size) {
875 OS.append(Ptr, Size);
882 uint64_t raw_svector_ostream::current_pos()
const {
return OS.size(); }
884 void raw_svector_ostream::write_impl(
const char *Ptr,
size_t Size) {
885 OS.append(Ptr, Ptr + Size);
888 void raw_svector_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
906 void raw_null_ostream::write_impl(
const char *Ptr,
size_t Size) {
909 uint64_t raw_null_ostream::current_pos()
const {
913 void raw_null_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
916 void raw_pwrite_stream::anchor() {}
918 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.
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.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
~raw_string_ostream() override
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...
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
block Block Frequency true
Represents the result of a call to sys::fs::status().
std::error_code error() const
#define LLVM_UNLIKELY(EXPR)
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.
~raw_fd_ostream() override
The file should be opened in text mode on platforms that make this distinction.
raw_ostream & operator<<(char C)
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.
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.
~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.
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.
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().
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())
CD_CreateAlways - When opening a file:
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)
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...
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.
bool empty() const
empty - Check if the array is empty.