18 #include "llvm/Config/config.h"
34 #include <system_error>
37 #if defined(HAVE_FCNTL_H)
41 #if defined(HAVE_UNISTD_H)
44 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
48 #if defined(__CYGWIN__)
55 # define STDIN_FILENO 0
58 # define STDOUT_FILENO 1
61 # define STDERR_FILENO 2
74 assert(OutBufCur == OutBufStart &&
75 "raw_ostream destructor called with non-empty buffer!");
77 if (BufferMode == InternalBuffer)
78 delete [] OutBufStart;
82 void raw_ostream::handle() {}
98 void raw_ostream::SetBufferAndMode(
char *BufferStart,
size_t Size,
100 assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
101 (Mode != Unbuffered && BufferStart && Size != 0)) &&
102 "stream must be unbuffered or have at least one byte");
107 if (BufferMode == InternalBuffer)
108 delete [] OutBufStart;
109 OutBufStart = BufferStart;
110 OutBufEnd = OutBufStart+
Size;
111 OutBufCur = OutBufStart;
114 assert(OutBufStart <= OutBufEnd &&
"Invalid size!");
143 bool UseHexEscapes) {
144 for (
unsigned char c : Str) {
147 *
this <<
'\\' <<
'\\';
150 *
this <<
'\\' <<
't';
153 *
this <<
'\\' <<
'n';
156 *
this <<
'\\' <<
'"';
159 if (std::isprint(c)) {
166 *
this <<
'\\' <<
'x';
167 *this << hexdigit((c >> 4 & 0xF));
168 *this << hexdigit((c >> 0) & 0xF);
172 *this << char('0' + ((c >> 6) & 7));
173 *this << char('0' + ((c >> 3) & 7));
174 *this << char('0' + ((c >> 0) & 7));
192 void raw_ostream::flush_nonempty() {
193 assert(OutBufCur > OutBufStart &&
"Invalid call to flush_nonempty.");
194 size_t Length = OutBufCur - OutBufStart;
195 OutBufCur = OutBufStart;
196 write_impl(OutBufStart, Length);
203 if (BufferMode == Unbuffered) {
204 write_impl(reinterpret_cast<char*>(&C), 1);
223 if (BufferMode == Unbuffered) {
224 write_impl(Ptr, Size);
229 return write(Ptr, Size);
232 size_t NumBytes = OutBufEnd - OutBufCur;
238 assert(NumBytes != 0 &&
"undefined behavior");
239 size_t BytesToWrite = Size - (Size % NumBytes);
240 write_impl(Ptr, BytesToWrite);
241 size_t BytesRemaining = Size - BytesToWrite;
242 if (BytesRemaining >
size_t(OutBufEnd - OutBufCur)) {
244 return write(Ptr + BytesToWrite, BytesRemaining);
246 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
252 copy_to_buffer(Ptr, NumBytes);
254 return write(Ptr + NumBytes, Size - NumBytes);
257 copy_to_buffer(Ptr, Size);
262 void raw_ostream::copy_to_buffer(
const char *
Ptr,
size_t Size) {
263 assert(Size <=
size_t(OutBufEnd - OutBufCur) &&
"Buffer overrun!");
274 memcpy(OutBufCur, Ptr, Size);
285 size_t NextBufferSize = 127;
286 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
287 if (BufferBytesLeft > 3) {
288 size_t BytesUsed = Fmt.
print(OutBufCur, BufferBytesLeft);
291 if (BytesUsed <= BufferBytesLeft) {
292 OutBufCur += BytesUsed;
298 NextBufferSize = BytesUsed;
310 size_t BytesUsed = Fmt.
print(V.
data(), NextBufferSize);
313 if (BytesUsed <= NextBufferSize)
317 assert(BytesUsed > NextBufferSize &&
"Didn't grow buffer!?");
318 NextBufferSize = BytesUsed;
333 const size_t Difference = FS.Width - FS.Str.
size();
334 switch (FS.Justify) {
344 int PadAmount = Difference / 2;
347 this->
indent(Difference - PadAmount);
359 if (FN.Upper && FN.HexPrefix)
361 else if (FN.Upper && !FN.HexPrefix)
363 else if (!FN.Upper && FN.HexPrefix)
372 if (Buffer.
size() < FN.Width)
380 if (FB.Bytes.
empty())
383 size_t LineIndex = 0;
384 auto Bytes = FB.Bytes;
385 const size_t Size = Bytes.
size();
387 uint64_t OffsetWidth = 0;
388 if (FB.FirstByteOffset.
hasValue()) {
392 size_t Lines = Size / FB.NumPerLine;
393 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
397 OffsetWidth = std::max<uint64_t>(4,
llvm::alignTo(Power, 4) / 4);
401 unsigned NumByteGroups =
402 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
403 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
405 while (!Bytes.empty()) {
408 if (FB.FirstByteOffset.
hasValue()) {
414 auto Line = Bytes.take_front(FB.NumPerLine);
416 size_t CharsPrinted = 0;
418 for (
size_t I = 0;
I < Line.size(); ++
I, CharsPrinted += 2) {
419 if (
I && (
I % FB.ByteGroupSize) == 0) {
429 assert(BlockCharWidth >= CharsPrinted);
430 indent(BlockCharWidth - CharsPrinted + 2);
434 for (uint8_t Byte : Line) {
436 *this << static_cast<char>(Byte);
443 Bytes = Bytes.drop_front(Line.size());
444 LineIndex += Line.size();
445 if (LineIndex < Size)
453 static const char Spaces[] =
" "
459 return write(Spaces, NumSpaces);
462 unsigned NumToWrite =
std::min(NumSpaces,
464 write(Spaces, NumToWrite);
465 NumSpaces -= NumToWrite;
486 if (Filename ==
"-") {
487 EC = std::error_code();
492 return STDOUT_FILENO;
521 if (FD <= STDERR_FILENO)
525 off_t loc = ::lseek(FD, 0, SEEK_CUR);
529 std::error_code EC =
status(FD, Status);
532 SupportsSeeking = loc != (off_t)-1;
534 if (!SupportsSeeking)
537 pos =
static_cast<uint64_t
>(loc);
563 void raw_fd_ostream::write_impl(
const char *Ptr,
size_t Size) {
564 assert(FD >= 0 &&
"File already closed.");
567 #ifndef LLVM_ON_WIN32
568 #if defined(__linux__)
569 bool ShouldWriteInChunks =
true;
571 bool ShouldWriteInChunks =
false;
581 size_t ChunkSize =
Size;
582 if (ChunkSize > 32767 && ShouldWriteInChunks)
585 ssize_t ret =
::write(FD, Ptr, ChunkSize);
596 if (errno == EINTR || errno == EAGAIN
598 || errno == EWOULDBLOCK
626 assert(SupportsSeeking &&
"Stream does not support seeking!");
629 pos = ::_lseeki64(FD, off, SEEK_SET);
630 #elif defined(HAVE_LSEEK64)
631 pos = ::lseek64(FD, off, SEEK_SET);
633 pos = ::lseek(FD, off, SEEK_SET);
635 if (pos == (uint64_t)-1)
640 void raw_fd_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
642 uint64_t Pos =
tell();
648 size_t raw_fd_ostream::preferred_buffer_size()
const {
649 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
651 assert(FD >= 0 &&
"File not yet open!");
653 if (fstat(FD, &statbuf) != 0)
659 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
662 return statbuf.st_blksize;
672 const char *colorcode =
676 size_t len = strlen(colorcode);
677 write(colorcode, len);
689 size_t len = strlen(colorcode);
690 write(colorcode, len);
702 size_t len = strlen(colorcode);
703 write(colorcode, len);
757 void raw_string_ostream::write_impl(
const char *Ptr,
size_t Size) {
758 OS.append(Ptr, Size);
765 uint64_t raw_svector_ostream::current_pos()
const {
return OS.
size(); }
767 void raw_svector_ostream::write_impl(
const char *Ptr,
size_t Size) {
768 OS.
append(Ptr, Ptr + Size);
771 void raw_svector_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
789 void raw_null_ostream::write_impl(
const char *Ptr,
size_t Size) {
792 uint64_t raw_null_ostream::current_pos()
const {
796 void raw_null_ostream::pwrite_impl(
const char *Ptr,
size_t Size,
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.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
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()
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
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_string_ostream() override
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.
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...
file_status - Represents the result of a call to stat and friends.
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.
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
uint64_t tell() const
tell - Return the current offset with the file.
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
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
size_t size() const
size - Get the array size.
raw_ostream & operator<<(char C)
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
Function Alias Analysis false
static int getFD(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags)
raw_ostream & resetColor() override
Resets the colors to terminal defaults.
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.
bool empty() const
empty - Check if the array is empty.
raw_fd_ostream(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags)
Open the specified file for writing.
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
~raw_null_ostream() override
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
raw_ostream & write(unsigned char C)
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '', ' ', '"', and anything that doesn't satisfy std::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.
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
The file should be opened in text mode on platforms that make this distinction.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
static std::vector< std::string > Flags
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().
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
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())
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Lightweight error class with error context and mandatory checking.
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)
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.
size_t GetNumBytesInBuffer() const
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)