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