1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===// 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 defines the raw_ostream class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H 14 #define LLVM_SUPPORT_RAW_OSTREAM_H 15 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include <cassert> 19 #include <cstddef> 20 #include <cstdint> 21 #include <cstring> 22 #include <string> 23 #include <system_error> 24 25 namespace llvm { 26 27 class formatv_object_base; 28 class format_object_base; 29 class FormattedString; 30 class FormattedNumber; 31 class FormattedBytes; 32 33 namespace sys { 34 namespace fs { 35 enum FileAccess : unsigned; 36 enum OpenFlags : unsigned; 37 enum CreationDisposition : unsigned; 38 } // end namespace fs 39 } // end namespace sys 40 41 /// This class implements an extremely fast bulk output stream that can *only* 42 /// output to a stream. It does not support seeking, reopening, rewinding, line 43 /// buffered disciplines etc. It is a simple buffer that outputs 44 /// a chunk at a time. 45 class raw_ostream { 46 private: 47 /// The buffer is handled in such a way that the buffer is 48 /// uninitialized, unbuffered, or out of space when OutBufCur >= 49 /// OutBufEnd. Thus a single comparison suffices to determine if we 50 /// need to take the slow path to write a single character. 51 /// 52 /// The buffer is in one of three states: 53 /// 1. Unbuffered (BufferMode == Unbuffered) 54 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0). 55 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 && 56 /// OutBufEnd - OutBufStart >= 1). 57 /// 58 /// If buffered, then the raw_ostream owns the buffer if (BufferMode == 59 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is 60 /// managed by the subclass. 61 /// 62 /// If a subclass installs an external buffer using SetBuffer then it can wait 63 /// for a \see write_impl() call to handle the data which has been put into 64 /// this buffer. 65 char *OutBufStart, *OutBufEnd, *OutBufCur; 66 67 enum BufferKind { 68 Unbuffered = 0, 69 InternalBuffer, 70 ExternalBuffer 71 } BufferMode; 72 73 public: 74 // color order matches ANSI escape sequence, don't change 75 enum Colors { 76 BLACK = 0, 77 RED, 78 GREEN, 79 YELLOW, 80 BLUE, 81 MAGENTA, 82 CYAN, 83 WHITE, 84 SAVEDCOLOR 85 }; 86 87 explicit raw_ostream(bool unbuffered = false) 88 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) { 89 // Start out ready to flush. 90 OutBufStart = OutBufEnd = OutBufCur = nullptr; 91 } 92 93 raw_ostream(const raw_ostream &) = delete; 94 void operator=(const raw_ostream &) = delete; 95 96 virtual ~raw_ostream(); 97 98 /// tell - Return the current offset with the file. 99 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); } 100 101 //===--------------------------------------------------------------------===// 102 // Configuration Interface 103 //===--------------------------------------------------------------------===// 104 105 /// Set the stream to be buffered, with an automatically determined buffer 106 /// size. 107 void SetBuffered(); 108 109 /// Set the stream to be buffered, using the specified buffer size. 110 void SetBufferSize(size_t Size) { 111 flush(); 112 SetBufferAndMode(new char[Size], Size, InternalBuffer); 113 } 114 115 size_t GetBufferSize() const { 116 // If we're supposed to be buffered but haven't actually gotten around 117 // to allocating the buffer yet, return the value that would be used. 118 if (BufferMode != Unbuffered && OutBufStart == nullptr) 119 return preferred_buffer_size(); 120 121 // Otherwise just return the size of the allocated buffer. 122 return OutBufEnd - OutBufStart; 123 } 124 125 /// Set the stream to be unbuffered. When unbuffered, the stream will flush 126 /// after every write. This routine will also flush the buffer immediately 127 /// when the stream is being set to unbuffered. 128 void SetUnbuffered() { 129 flush(); 130 SetBufferAndMode(nullptr, 0, Unbuffered); 131 } 132 133 size_t GetNumBytesInBuffer() const { 134 return OutBufCur - OutBufStart; 135 } 136 137 //===--------------------------------------------------------------------===// 138 // Data Output Interface 139 //===--------------------------------------------------------------------===// 140 141 void flush() { 142 if (OutBufCur != OutBufStart) 143 flush_nonempty(); 144 } 145 146 raw_ostream &operator<<(char C) { 147 if (OutBufCur >= OutBufEnd) 148 return write(C); 149 *OutBufCur++ = C; 150 return *this; 151 } 152 153 raw_ostream &operator<<(unsigned char C) { 154 if (OutBufCur >= OutBufEnd) 155 return write(C); 156 *OutBufCur++ = C; 157 return *this; 158 } 159 160 raw_ostream &operator<<(signed char C) { 161 if (OutBufCur >= OutBufEnd) 162 return write(C); 163 *OutBufCur++ = C; 164 return *this; 165 } 166 167 raw_ostream &operator<<(StringRef Str) { 168 // Inline fast path, particularly for strings with a known length. 169 size_t Size = Str.size(); 170 171 // Make sure we can use the fast path. 172 if (Size > (size_t)(OutBufEnd - OutBufCur)) 173 return write(Str.data(), Size); 174 175 if (Size) { 176 memcpy(OutBufCur, Str.data(), Size); 177 OutBufCur += Size; 178 } 179 return *this; 180 } 181 182 raw_ostream &operator<<(const char *Str) { 183 // Inline fast path, particularly for constant strings where a sufficiently 184 // smart compiler will simplify strlen. 185 186 return this->operator<<(StringRef(Str)); 187 } 188 189 raw_ostream &operator<<(const std::string &Str) { 190 // Avoid the fast path, it would only increase code size for a marginal win. 191 return write(Str.data(), Str.length()); 192 } 193 194 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) { 195 return write(Str.data(), Str.size()); 196 } 197 198 raw_ostream &operator<<(unsigned long N); 199 raw_ostream &operator<<(long N); 200 raw_ostream &operator<<(unsigned long long N); 201 raw_ostream &operator<<(long long N); 202 raw_ostream &operator<<(const void *P); 203 204 raw_ostream &operator<<(unsigned int N) { 205 return this->operator<<(static_cast<unsigned long>(N)); 206 } 207 208 raw_ostream &operator<<(int N) { 209 return this->operator<<(static_cast<long>(N)); 210 } 211 212 raw_ostream &operator<<(double N); 213 214 /// Output \p N in hexadecimal, without any prefix or padding. 215 raw_ostream &write_hex(unsigned long long N); 216 217 /// Output a formatted UUID with dash separators. 218 using uuid_t = uint8_t[16]; 219 raw_ostream &write_uuid(const uuid_t UUID); 220 221 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't 222 /// satisfy llvm::isPrint into an escape sequence. 223 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false); 224 225 raw_ostream &write(unsigned char C); 226 raw_ostream &write(const char *Ptr, size_t Size); 227 228 // Formatted output, see the format() function in Support/Format.h. 229 raw_ostream &operator<<(const format_object_base &Fmt); 230 231 // Formatted output, see the leftJustify() function in Support/Format.h. 232 raw_ostream &operator<<(const FormattedString &); 233 234 // Formatted output, see the formatHex() function in Support/Format.h. 235 raw_ostream &operator<<(const FormattedNumber &); 236 237 // Formatted output, see the formatv() function in Support/FormatVariadic.h. 238 raw_ostream &operator<<(const formatv_object_base &); 239 240 // Formatted output, see the format_bytes() function in Support/Format.h. 241 raw_ostream &operator<<(const FormattedBytes &); 242 243 /// indent - Insert 'NumSpaces' spaces. 244 raw_ostream &indent(unsigned NumSpaces); 245 246 /// write_zeros - Insert 'NumZeros' nulls. 247 raw_ostream &write_zeros(unsigned NumZeros); 248 249 /// Changes the foreground color of text that will be output from this point 250 /// forward. 251 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to 252 /// change only the bold attribute, and keep colors untouched 253 /// @param Bold bold/brighter text, default false 254 /// @param BG if true change the background, default: change foreground 255 /// @returns itself so it can be used within << invocations 256 virtual raw_ostream &changeColor(enum Colors Color, 257 bool Bold = false, 258 bool BG = false) { 259 (void)Color; 260 (void)Bold; 261 (void)BG; 262 return *this; 263 } 264 265 /// Resets the colors to terminal defaults. Call this when you are done 266 /// outputting colored text, or before program exit. 267 virtual raw_ostream &resetColor() { return *this; } 268 269 /// Reverses the foreground and background colors. 270 virtual raw_ostream &reverseColor() { return *this; } 271 272 /// This function determines if this stream is connected to a "tty" or 273 /// "console" window. That is, the output would be displayed to the user 274 /// rather than being put on a pipe or stored in a file. 275 virtual bool is_displayed() const { return false; } 276 277 /// This function determines if this stream is displayed and supports colors. 278 virtual bool has_colors() const { return is_displayed(); } 279 280 //===--------------------------------------------------------------------===// 281 // Subclass Interface 282 //===--------------------------------------------------------------------===// 283 284 private: 285 /// The is the piece of the class that is implemented by subclasses. This 286 /// writes the \p Size bytes starting at 287 /// \p Ptr to the underlying stream. 288 /// 289 /// This function is guaranteed to only be called at a point at which it is 290 /// safe for the subclass to install a new buffer via SetBuffer. 291 /// 292 /// \param Ptr The start of the data to be written. For buffered streams this 293 /// is guaranteed to be the start of the buffer. 294 /// 295 /// \param Size The number of bytes to be written. 296 /// 297 /// \invariant { Size > 0 } 298 virtual void write_impl(const char *Ptr, size_t Size) = 0; 299 300 /// Return the current position within the stream, not counting the bytes 301 /// currently in the buffer. 302 virtual uint64_t current_pos() const = 0; 303 304 protected: 305 /// Use the provided buffer as the raw_ostream buffer. This is intended for 306 /// use only by subclasses which can arrange for the output to go directly 307 /// into the desired output buffer, instead of being copied on each flush. 308 void SetBuffer(char *BufferStart, size_t Size) { 309 SetBufferAndMode(BufferStart, Size, ExternalBuffer); 310 } 311 312 /// Return an efficient buffer size for the underlying output mechanism. 313 virtual size_t preferred_buffer_size() const; 314 315 /// Return the beginning of the current stream buffer, or 0 if the stream is 316 /// unbuffered. 317 const char *getBufferStart() const { return OutBufStart; } 318 319 //===--------------------------------------------------------------------===// 320 // Private Interface 321 //===--------------------------------------------------------------------===// 322 private: 323 /// Install the given buffer and mode. 324 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode); 325 326 /// Flush the current buffer, which is known to be non-empty. This outputs the 327 /// currently buffered data and resets the buffer to empty. 328 void flush_nonempty(); 329 330 /// Copy data into the buffer. Size must not be greater than the number of 331 /// unused bytes in the buffer. 332 void copy_to_buffer(const char *Ptr, size_t Size); 333 334 virtual void anchor(); 335 }; 336 337 /// An abstract base class for streams implementations that also support a 338 /// pwrite operation. This is useful for code that can mostly stream out data, 339 /// but needs to patch in a header that needs to know the output size. 340 class raw_pwrite_stream : public raw_ostream { 341 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0; 342 void anchor() override; 343 344 public: 345 explicit raw_pwrite_stream(bool Unbuffered = false) 346 : raw_ostream(Unbuffered) {} 347 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) { 348 #ifndef NDEBUG 349 uint64_t Pos = tell(); 350 // /dev/null always reports a pos of 0, so we cannot perform this check 351 // in that case. 352 if (Pos) 353 assert(Size + Offset <= Pos && "We don't support extending the stream"); 354 #endif 355 pwrite_impl(Ptr, Size, Offset); 356 } 357 }; 358 359 //===----------------------------------------------------------------------===// 360 // File Output Streams 361 //===----------------------------------------------------------------------===// 362 363 /// A raw_ostream that writes to a file descriptor. 364 /// 365 class raw_fd_ostream : public raw_pwrite_stream { 366 int FD; 367 bool ShouldClose; 368 369 bool SupportsSeeking; 370 371 #ifdef _WIN32 372 /// True if this fd refers to a Windows console device. Mintty and other 373 /// terminal emulators are TTYs, but they are not consoles. 374 bool IsWindowsConsole = false; 375 #endif 376 377 std::error_code EC; 378 379 uint64_t pos; 380 381 /// See raw_ostream::write_impl. 382 void write_impl(const char *Ptr, size_t Size) override; 383 384 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 385 386 /// Return the current position within the stream, not counting the bytes 387 /// currently in the buffer. 388 uint64_t current_pos() const override { return pos; } 389 390 /// Determine an efficient buffer size. 391 size_t preferred_buffer_size() const override; 392 393 /// Set the flag indicating that an output error has been encountered. 394 void error_detected(std::error_code EC) { this->EC = EC; } 395 396 void anchor() override; 397 398 public: 399 /// Open the specified file for writing. If an error occurs, information 400 /// about the error is put into EC, and the stream should be immediately 401 /// destroyed; 402 /// \p Flags allows optional flags to control how the file will be opened. 403 /// 404 /// As a special case, if Filename is "-", then the stream will use 405 /// STDOUT_FILENO instead of opening a file. This will not close the stdout 406 /// descriptor. 407 raw_fd_ostream(StringRef Filename, std::error_code &EC); 408 raw_fd_ostream(StringRef Filename, std::error_code &EC, 409 sys::fs::CreationDisposition Disp); 410 raw_fd_ostream(StringRef Filename, std::error_code &EC, 411 sys::fs::FileAccess Access); 412 raw_fd_ostream(StringRef Filename, std::error_code &EC, 413 sys::fs::OpenFlags Flags); 414 raw_fd_ostream(StringRef Filename, std::error_code &EC, 415 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, 416 sys::fs::OpenFlags Flags); 417 418 /// FD is the file descriptor that this writes to. If ShouldClose is true, 419 /// this closes the file when the stream is destroyed. If FD is for stdout or 420 /// stderr, it will not be closed. 421 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false); 422 423 ~raw_fd_ostream() override; 424 425 /// Manually flush the stream and close the file. Note that this does not call 426 /// fsync. 427 void close(); 428 429 bool supportsSeeking() { return SupportsSeeking; } 430 431 /// Flushes the stream and repositions the underlying file descriptor position 432 /// to the offset specified from the beginning of the file. 433 uint64_t seek(uint64_t off); 434 435 raw_ostream &changeColor(enum Colors colors, bool bold=false, 436 bool bg=false) override; 437 raw_ostream &resetColor() override; 438 439 raw_ostream &reverseColor() override; 440 441 bool is_displayed() const override; 442 443 bool has_colors() const override; 444 445 std::error_code error() const { return EC; } 446 447 /// Return the value of the flag in this raw_fd_ostream indicating whether an 448 /// output error has been encountered. 449 /// This doesn't implicitly flush any pending output. Also, it doesn't 450 /// guarantee to detect all errors unless the stream has been closed. 451 bool has_error() const { return bool(EC); } 452 453 /// Set the flag read by has_error() to false. If the error flag is set at the 454 /// time when this raw_ostream's destructor is called, report_fatal_error is 455 /// called to report the error. Use clear_error() after handling the error to 456 /// avoid this behavior. 457 /// 458 /// "Errors should never pass silently. 459 /// Unless explicitly silenced." 460 /// - from The Zen of Python, by Tim Peters 461 /// 462 void clear_error() { EC = std::error_code(); } 463 }; 464 465 /// This returns a reference to a raw_ostream for standard output. Use it like: 466 /// outs() << "foo" << "bar"; 467 raw_ostream &outs(); 468 469 /// This returns a reference to a raw_ostream for standard error. Use it like: 470 /// errs() << "foo" << "bar"; 471 raw_ostream &errs(); 472 473 /// This returns a reference to a raw_ostream which simply discards output. 474 raw_ostream &nulls(); 475 476 //===----------------------------------------------------------------------===// 477 // Output Stream Adaptors 478 //===----------------------------------------------------------------------===// 479 480 /// A raw_ostream that writes to an std::string. This is a simple adaptor 481 /// class. This class does not encounter output errors. 482 class raw_string_ostream : public raw_ostream { 483 std::string &OS; 484 485 /// See raw_ostream::write_impl. 486 void write_impl(const char *Ptr, size_t Size) override; 487 488 /// Return the current position within the stream, not counting the bytes 489 /// currently in the buffer. 490 uint64_t current_pos() const override { return OS.size(); } 491 492 public: 493 explicit raw_string_ostream(std::string &O) : OS(O) {} 494 ~raw_string_ostream() override; 495 496 /// Flushes the stream contents to the target string and returns the string's 497 /// reference. 498 std::string& str() { 499 flush(); 500 return OS; 501 } 502 }; 503 504 /// A raw_ostream that writes to an SmallVector or SmallString. This is a 505 /// simple adaptor class. This class does not encounter output errors. 506 /// raw_svector_ostream operates without a buffer, delegating all memory 507 /// management to the SmallString. Thus the SmallString is always up-to-date, 508 /// may be used directly and there is no need to call flush(). 509 class raw_svector_ostream : public raw_pwrite_stream { 510 SmallVectorImpl<char> &OS; 511 512 /// See raw_ostream::write_impl. 513 void write_impl(const char *Ptr, size_t Size) override; 514 515 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 516 517 /// Return the current position within the stream. 518 uint64_t current_pos() const override; 519 520 public: 521 /// Construct a new raw_svector_ostream. 522 /// 523 /// \param O The vector to write to; this should generally have at least 128 524 /// bytes free to avoid any extraneous memory overhead. 525 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) { 526 SetUnbuffered(); 527 } 528 529 ~raw_svector_ostream() override = default; 530 531 void flush() = delete; 532 533 /// Return a StringRef for the vector contents. 534 StringRef str() { return StringRef(OS.data(), OS.size()); } 535 }; 536 537 /// A raw_ostream that discards all output. 538 class raw_null_ostream : public raw_pwrite_stream { 539 /// See raw_ostream::write_impl. 540 void write_impl(const char *Ptr, size_t size) override; 541 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 542 543 /// Return the current position within the stream, not counting the bytes 544 /// currently in the buffer. 545 uint64_t current_pos() const override; 546 547 public: 548 explicit raw_null_ostream() = default; 549 ~raw_null_ostream() override; 550 }; 551 552 class buffer_ostream : public raw_svector_ostream { 553 raw_ostream &OS; 554 SmallVector<char, 0> Buffer; 555 556 virtual void anchor() override; 557 558 public: 559 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {} 560 ~buffer_ostream() override { OS << str(); } 561 }; 562 563 } // end namespace llvm 564 565 #endif // LLVM_SUPPORT_RAW_OSTREAM_H 566