1 /* UI_FILE - a generic STDIO like output stream.
2    Copyright (C) 1999-2024 Free Software Foundation, Inc.
3 
4    This file is part of GDB.
5 
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18 
19 #ifndef UI_FILE_H
20 #define UI_FILE_H
21 
22 #include <string>
23 #include "ui-style.h"
24 
25 /* The abstract ui_file base class.  */
26 
27 class ui_file
28 {
29 public:
30   ui_file ();
31   virtual ~ui_file () = 0;
32 
33   ui_file (ui_file &&other) = default;
34 
35   /* Public non-virtual API.  */
36 
37   void printf (const char *, ...) ATTRIBUTE_PRINTF (2, 3);
38 
39   /* Print a NUL-terminated string whose delimiter is QUOTER.  Note
40      that these routines should only be called for printing things
41      which are independent of the language of the program being
42      debugged.
43 
44      This will normally escape backslashes and instances of QUOTER.
45      If QUOTER is 0, it won't escape backslashes or any quoting
46      character.  As a side effect, if you pass the backslash character
47      as the QUOTER, this will escape backslashes as usual, but not any
48      other quoting character.  */
49   void putstr (const char *str, int quoter);
50 
51   /* Like putstr, but only print the first N characters of STR.  If
52      ASYNC_SAFE is true, then the output is done via the
53      write_async_safe method.  */
54   void putstrn (const char *str, int n, int quoter, bool async_safe = false);
55 
56   void putc (int c);
57 
58   void vprintf (const char *, va_list) ATTRIBUTE_PRINTF (2, 0);
59 
60   /* Methods below are both public, and overridable by ui_file
61      subclasses.  */
62 
63   virtual void write (const char *buf, long length_buf) = 0;
64 
65   /* This version of "write" is safe for use in signal handlers.  It's
66      not guaranteed that all existing output will have been flushed
67      first.  Implementations are also free to ignore some or all of
68      the request.  puts_async is not provided as the async versions
69      are rarely used, no point in having both for a rarely used
70      interface.  */
write_async_safe(const char * buf,long length_buf)71   virtual void write_async_safe (const char *buf, long length_buf)
72   { gdb_assert_not_reached ("write_async_safe"); }
73 
74   /* Some ui_files override this to provide a efficient implementation
75      that avoids a strlen.  */
puts(const char * str)76   virtual void puts (const char *str)
77   { this->write (str, strlen (str)); }
78 
read(char * buf,long length_buf)79   virtual long read (char *buf, long length_buf)
80   { gdb_assert_not_reached ("can't read from this file type"); }
81 
isatty()82   virtual bool isatty ()
83   { return false; }
84 
85   /* true indicates terminal output behaviour such as cli_styling.
86      This default implementation indicates to do terminal output
87      behaviour if the UI_FILE is a tty.  A derived class can override
88      TERM_OUT to have cli_styling behaviour without being a tty.  */
term_out()89   virtual bool term_out ()
90   { return isatty (); }
91 
92   /* true if ANSI escapes can be used on STREAM.  */
can_emit_style_escape()93   virtual bool can_emit_style_escape ()
94   { return false; }
95 
flush()96   virtual void flush ()
97   {}
98 
99   /* If this object has an underlying file descriptor, then return it.
100      Otherwise, return -1.  */
fd()101   virtual int fd () const
102   { return -1; }
103 
104   /* Indicate that if the next sequence of characters overflows the
105      line, a newline should be inserted here rather than when it hits
106      the end.  If INDENT is non-zero, it is a number of spaces to be
107      printed to indent the wrapped part on the next line.
108 
109      If the line is already overfull, we immediately print a newline and
110      the indentation, and disable further wrapping.
111 
112      If we don't know the width of lines, but we know the page height,
113      we must not wrap words, but should still keep track of newlines
114      that were explicitly printed.
115 
116      This routine is guaranteed to force out any output which has been
117      squirreled away in the wrap_buffer, so wrap_here (0) can be
118      used to force out output from the wrap_buffer.  */
wrap_here(int indent)119   virtual void wrap_here (int indent)
120   {
121   }
122 
123   /* Emit an ANSI style escape for STYLE.  */
124   virtual void emit_style_escape (const ui_file_style &style);
125 
126   /* Rest the current output style to the empty style.  */
127   virtual void reset_style ();
128 
129   /* Print STR, bypassing any paging that might be done by this
130      ui_file.  Note that nearly no code should call this -- it's
131      intended for use by gdb_printf, but nothing else.  */
puts_unfiltered(const char * str)132   virtual void puts_unfiltered (const char *str)
133   {
134     this->puts (str);
135   }
136 
137 protected:
138 
139   /* The currently applied style.  */
140   ui_file_style m_applied_style;
141 
142 private:
143 
144   /* Helper function for putstr and putstrn.  Print the character C on
145      this stream as part of the contents of a literal string whose
146      delimiter is QUOTER.  */
147   void printchar (int c, int quoter, bool async_safe);
148 };
149 
150 typedef std::unique_ptr<ui_file> ui_file_up;
151 
152 /* A ui_file that writes to nowhere.  */
153 
154 class null_file : public ui_file
155 {
156 public:
157   void write (const char *buf, long length_buf) override;
158   void write_async_safe (const char *buf, long sizeof_buf) override;
159   void puts (const char *str) override;
160 };
161 
162 /* A preallocated null_file stream.  */
163 extern null_file null_stream;
164 
165 extern int gdb_console_fputs (const char *, FILE *);
166 
167 /* A std::string-based ui_file.  Can be used as a scratch buffer for
168    collecting output.  */
169 
170 class string_file : public ui_file
171 {
172 public:
173   /* Construct a string_file to collect 'raw' output, i.e. without
174      'terminal' behaviour such as cli_styling.  */
string_file()175   string_file () : m_term_out (false) {};
176   /* If TERM_OUT, construct a string_file with terminal output behaviour
177      such as cli_styling)
178      else collect 'raw' output like the previous constructor.  */
string_file(bool term_out)179   explicit string_file (bool term_out) : m_term_out (term_out) {};
180   ~string_file () override;
181 
182   string_file (string_file &&other) = default;
183 
184   /* Override ui_file methods.  */
185 
186   void write (const char *buf, long length_buf) override;
187 
read(char * buf,long length_buf)188   long read (char *buf, long length_buf) override
189   { gdb_assert_not_reached ("a string_file is not readable"); }
190 
191   bool term_out () override;
192   bool can_emit_style_escape () override;
193 
194   /* string_file-specific public API.  */
195 
196   /* Accesses the std::string containing the entire output collected
197      so far.  */
string()198   const std::string &string () { return m_string; }
199 
200   /* Return an std::string containing the entire output collected so far.
201 
202      The internal buffer is cleared, such that it's ready to build a new
203      string.  */
release()204   std::string release ()
205   {
206     std::string ret = std::move (m_string);
207     m_string.clear ();
208     return ret;
209   }
210 
211   /* Set the internal buffer contents to STR.  Any existing contents are
212      discarded.  */
213   string_file &operator= (std::string &&str)
214   {
215     m_string = std::move (str);
216     return *this;
217   }
218 
219   /* Provide a few convenience methods with the same API as the
220      underlying std::string.  */
data()221   const char *data () const { return m_string.data (); }
c_str()222   const char *c_str () const { return m_string.c_str (); }
size()223   size_t size () const { return m_string.size (); }
empty()224   bool empty () const { return m_string.empty (); }
clear()225   void clear () { return m_string.clear (); }
226 
227 private:
228   /* The internal buffer.  */
229   std::string m_string;
230 
231   bool m_term_out;
232 };
233 
234 /* A ui_file implementation that maps directly onto <stdio.h>'s FILE.
235    A stdio_file can either own its underlying file, or not.  If it
236    owns the file, then destroying the stdio_file closes the underlying
237    file, otherwise it is left open.  */
238 
239 class stdio_file : public ui_file
240 {
241 public:
242   /* Create a ui_file from a previously opened FILE.  CLOSE_P
243      indicates whether the underlying file should be closed when the
244      stdio_file is destroyed.  */
245   explicit stdio_file (FILE *file, bool close_p = false);
246 
247   /* Create an stdio_file that is not managing any file yet.  Call
248      open to actually open something.  */
249   stdio_file ();
250 
251   ~stdio_file () override;
252 
253   /* Open NAME in mode MODE, and own the resulting file.  Returns true
254      on success, false otherwise.  If the stdio_file previously owned
255      a file, it is closed.  */
256   bool open (const char *name, const char *mode);
257 
258   void flush () override;
259 
260   void write (const char *buf, long length_buf) override;
261 
262   void write_async_safe (const char *buf, long length_buf) override;
263 
264   void puts (const char *) override;
265 
266   long read (char *buf, long length_buf) override;
267 
268   bool isatty () override;
269 
270   bool can_emit_style_escape () override;
271 
272   /* Return the underlying file descriptor.  */
fd()273   int fd () const override
274   { return m_fd; }
275 
276 private:
277   /* Sets the internal stream to FILE, and saves the FILE's file
278      descriptor in M_FD.  */
279   void set_stream (FILE *file);
280 
281   /* The file.  */
282   FILE *m_file;
283 
284   /* The associated file descriptor is extracted ahead of time for
285      stdio_file::write_async_safe's benefit, in case fileno isn't
286      async-safe.  */
287   int m_fd;
288 
289   /* If true, M_FILE is closed on destruction.  */
290   bool m_close_p;
291 };
292 
293 typedef std::unique_ptr<stdio_file> stdio_file_up;
294 
295 /* Like stdio_file, but specifically for stderr.
296 
297    This exists because there is no real line-buffering on Windows, see
298    <http://msdn.microsoft.com/en-us/library/86cebhfs%28v=vs.71%29.aspx>
299    so the stdout is either fully-buffered or non-buffered.  We can't
300    make stdout non-buffered, because of two concerns:
301 
302     1. Non-buffering hurts performance.
303     2. Non-buffering may change GDB's behavior when it is interacting
304        with a front-end, such as Emacs.
305 
306    We leave stdout as fully buffered, but flush it first when
307    something is written to stderr.
308 
309    Note that the 'write_async_safe' method is not overridden, because
310    there's no way to flush a stream in an async-safe manner.
311    Fortunately, it doesn't really matter, because:
312 
313     1. That method is only used for printing internal debug output
314        from signal handlers.
315 
316     2. Windows hosts don't have a concept of async-safeness.  Signal
317        handlers run in a separate thread, so they can call the regular
318        non-async-safe output routines freely.
319 */
320 class stderr_file : public stdio_file
321 {
322 public:
323   explicit stderr_file (FILE *stream);
324 
325   /* Override the output routines to flush gdb_stdout before deferring
326      to stdio_file for the actual outputting.  */
327   void write (const char *buf, long length_buf) override;
328   void puts (const char *linebuffer) override;
329 };
330 
331 /* A ui_file implementation that maps onto two ui-file objects.  */
332 
333 class tee_file : public ui_file
334 {
335 public:
336   /* Create a file which writes to both ONE and TWO.  Ownership of
337      both files is up to the user.  */
338   tee_file (ui_file *one, ui_file *two);
339   ~tee_file () override;
340 
341   void write (const char *buf, long length_buf) override;
342   void write_async_safe (const char *buf, long length_buf) override;
343   void puts (const char *) override;
344 
345   bool isatty () override;
346   bool term_out () override;
347   bool can_emit_style_escape () override;
348   void flush () override;
349 
emit_style_escape(const ui_file_style & style)350   void emit_style_escape (const ui_file_style &style) override
351   {
352     m_one->emit_style_escape (style);
353     m_two->emit_style_escape (style);
354   }
355 
reset_style()356   void reset_style () override
357   {
358     m_one->reset_style ();
359     m_two->reset_style ();
360   }
361 
puts_unfiltered(const char * str)362   void puts_unfiltered (const char *str) override
363   {
364     m_one->puts_unfiltered (str);
365     m_two->puts_unfiltered (str);
366   }
367 
368 private:
369   /* The two underlying ui_files.  */
370   ui_file *m_one;
371   ui_file *m_two;
372 };
373 
374 /* A ui_file implementation that filters out terminal escape
375    sequences.  */
376 
377 class no_terminal_escape_file : public stdio_file
378 {
379 public:
no_terminal_escape_file()380   no_terminal_escape_file ()
381   {
382   }
383 
384   /* Like the stdio_file methods, but these filter out terminal escape
385      sequences.  */
386   void write (const char *buf, long length_buf) override;
387   void puts (const char *linebuffer) override;
388 
emit_style_escape(const ui_file_style & style)389   void emit_style_escape (const ui_file_style &style) override
390   {
391   }
392 
reset_style()393   void reset_style () override
394   {
395   }
396 };
397 
398 /* A base class for ui_file types that wrap another ui_file.  */
399 
400 class wrapped_file : public ui_file
401 {
402 public:
403 
isatty()404   bool isatty () override
405   { return m_stream->isatty (); }
406 
term_out()407   bool term_out () override
408   { return m_stream->term_out (); }
409 
can_emit_style_escape()410   bool can_emit_style_escape () override
411   { return m_stream->can_emit_style_escape (); }
412 
flush()413   void flush () override
414   { m_stream->flush (); }
415 
wrap_here(int indent)416   void wrap_here (int indent) override
417   { m_stream->wrap_here (indent); }
418 
emit_style_escape(const ui_file_style & style)419   void emit_style_escape (const ui_file_style &style) override
420   { m_stream->emit_style_escape (style); }
421 
422   /* Rest the current output style to the empty style.  */
reset_style()423   void reset_style () override
424   { m_stream->reset_style (); }
425 
fd()426   int fd () const override
427   { return m_stream->fd (); }
428 
puts_unfiltered(const char * str)429   void puts_unfiltered (const char *str) override
430   { m_stream->puts_unfiltered (str); }
431 
write_async_safe(const char * buf,long length_buf)432   void write_async_safe (const char *buf, long length_buf) override
433   { return m_stream->write_async_safe (buf, length_buf); }
434 
435 protected:
436 
437   /* Note that this class does not assume ownership of the stream.
438      However, a subclass may choose to, by adding a 'delete' to its
439      destructor.  */
wrapped_file(ui_file * stream)440   explicit wrapped_file (ui_file *stream)
441     : m_stream (stream)
442   {
443   }
444 
445   /* The underlying stream.  */
446   ui_file *m_stream;
447 };
448 
449 /* A ui_file that optionally puts a timestamp at the start of each
450    line of output.  */
451 
452 class timestamped_file : public wrapped_file
453 {
454 public:
timestamped_file(ui_file * stream)455   explicit timestamped_file (ui_file *stream)
456     : wrapped_file (stream)
457   {
458   }
459 
460   DISABLE_COPY_AND_ASSIGN (timestamped_file);
461 
462   void write (const char *buf, long len) override;
463 
464 private:
465 
466   /* True if the next output should be timestamped.  */
467   bool m_needs_timestamp = true;
468 };
469 
470 #endif
471