1 /* Output generating routines for GDB.
2 
3    Copyright (C) 1999-2024 Free Software Foundation, Inc.
4 
5    Contributed by Cygnus Solutions.
6    Written by Fernando Nasser for Cygnus.
7 
8    This file is part of GDB.
9 
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22 
23 #ifndef UI_OUT_H
24 #define UI_OUT_H 1
25 
26 #include <vector>
27 
28 #include "gdbsupport/enum-flags.h"
29 #include "ui-style.h"
30 
31 class ui_out_level;
32 class ui_out_table;
33 struct ui_file;
34 
35 /* the current ui_out */
36 
37 /* FIXME: This should not be a global but something passed down from main.c
38    or top.c.  */
39 extern struct ui_out **current_ui_current_uiout_ptr (void);
40 #define current_uiout (*current_ui_current_uiout_ptr ())
41 
42 /* alignment enum */
43 enum ui_align
44   {
45     ui_left = -1,
46     ui_center,
47     ui_right,
48     ui_noalign
49   };
50 
51 /* flags enum */
52 enum ui_out_flag
53 {
54   ui_source_list = (1 << 0),
55   fix_multi_location_breakpoint_output = (1 << 1),
56   /* This indicates that %pF should be disallowed in a printf format
57      string.  */
58   disallow_ui_out_field = (1 << 2),
59   fix_breakpoint_script_output = (1 << 3),
60 };
61 
62 DEF_ENUM_FLAGS_TYPE (ui_out_flag, ui_out_flags);
63 
64 /* Prototypes for ui-out API.  */
65 
66 /* A result is a recursive data structure consisting of lists and
67    tuples.  */
68 
69 enum ui_out_type
70   {
71     ui_out_type_tuple,
72     ui_out_type_list
73   };
74 
75 /* The possible kinds of fields.  */
76 enum class field_kind
77   {
78     /* "FIELD_STRING" needs a funny name to avoid clashes with tokens
79        named "STRING".  See PR build/25250.  FIELD_SIGNED is given a
80        similar name for consistency.  */
81     FIELD_SIGNED,
82     FIELD_STRING,
83   };
84 
85 /* The base type of all fields that can be emitted using %pF.  */
86 
87 struct base_field_s
88 {
89   const char *name;
90   field_kind kind;
91 };
92 
93 /* A signed integer field, to be passed to %pF in format strings.  */
94 
95 struct signed_field_s : base_field_s
96 {
97   LONGEST val;
98 };
99 
100 /* Construct a temporary signed_field_s on the caller's stack and
101    return a pointer to the constructed object.  We use this because
102    it's not possible to pass a reference via va_args.  */
103 
104 static inline signed_field_s *
105 signed_field (const char *name, LONGEST val,
106                 signed_field_s &&tmp = {})
107 {
108   tmp.name = name;
109   tmp.kind = field_kind::FIELD_SIGNED;
110   tmp.val = val;
111   return &tmp;
112 }
113 
114 /* A string field, to be passed to %pF in format strings.  */
115 
116 struct string_field_s : base_field_s
117 {
118   const char *str;
119 };
120 
121 /* Construct a temporary string_field_s on the caller's stack and
122    return a pointer to the constructed object.  We use this because
123    it's not possible to pass a reference via va_args.  */
124 
125 static inline string_field_s *
126 string_field (const char *name, const char *str,
127                 string_field_s &&tmp = {})
128 {
129   tmp.name = name;
130   tmp.kind = field_kind::FIELD_STRING;
131   tmp.str = str;
132   return &tmp;
133 }
134 
135 /* A styled string.  */
136 
137 struct styled_string_s
138 {
139   /* The style.  */
140   ui_file_style style;
141 
142   /* The string.  */
143   const char *str;
144 };
145 
146 /* Construct a temporary styled_string_s on the caller's stack and
147    return a pointer to the constructed object.  We use this because
148    it's not possible to pass a reference via va_args.  */
149 
150 static inline styled_string_s *
151 styled_string (const ui_file_style &style, const char *str,
152                  styled_string_s &&tmp = {})
153 {
154   tmp.style = style;
155   tmp.str = str;
156   return &tmp;
157 }
158 
159 class ui_out
160 {
161  public:
162 
163   explicit ui_out (ui_out_flags flags = 0);
164   virtual ~ui_out ();
165 
166   DISABLE_COPY_AND_ASSIGN (ui_out);
167 
168   void push_level (ui_out_type type);
169   void pop_level (ui_out_type type);
170 
171   /* A table can be considered a special tuple/list combination with the
172      implied structure: ``table = { hdr = { header, ... } , body = [ {
173      field, ... }, ... ] }''.  If NR_ROWS is negative then there is at
174      least one row.  */
175 
176   void table_begin (int nr_cols, int nr_rows, const std::string &tblid);
177   void table_header (int width, ui_align align, const std::string &col_name,
178                          const std::string &col_hdr);
179   void table_body ();
180   void table_end ();
181 
182   void begin (ui_out_type type, const char *id);
183   void end (ui_out_type type);
184 
185   void field_signed (const char *fldname, LONGEST value);
186   void field_fmt_signed (int width, ui_align align, const char *fldname,
187                                LONGEST value);
188   /* Like field_signed, but print an unsigned value.  */
189   void field_unsigned (const char *fldname, ULONGEST value);
190   void field_core_addr (const char *fldname, struct gdbarch *gdbarch,
191                               CORE_ADDR address);
192   void field_string (const char *fldname, const char *string,
193                          const ui_file_style &style = ui_file_style ());
194   void field_string (const char *fldname, const std::string &string,
195                          const ui_file_style &style = ui_file_style ())
196   {
197     field_string (fldname, string.c_str (), style);
198   }
199   void field_stream (const char *fldname, string_file &stream,
200                          const ui_file_style &style = ui_file_style ());
201   void field_skip (const char *fldname);
202   void field_fmt (const char *fldname, const char *format, ...)
203     ATTRIBUTE_PRINTF (3, 4);
204   void field_fmt (const char *fldname, const ui_file_style &style,
205                       const char *format, ...)
206     ATTRIBUTE_PRINTF (4, 5);
207 
spaces(int numspaces)208   void spaces (int numspaces) { do_spaces (numspaces); }
text(const char * string)209   void text (const char *string) { do_text (string); }
text(const std::string & string)210   void text (const std::string &string) { text (string.c_str ()); }
211 
212   /* Output a printf-style formatted string.  In addition to the usual
213      printf format specs, this supports a few GDB-specific
214      formatters:
215 
216      - '%pF' - output a field.
217 
218        The argument is a field, wrapped in any of the base_field_s
219        subclasses.  signed_field for integer fields, string_field for
220        string fields.  This is preferred over separate
221        uiout->field_signed(), uiout_>field_string() etc. calls when
222        the formatted message is translatable.  E.g.:
223 
224            uiout->message (_("\nWatchpoint %pF deleted because the program has "
225                                "left the block in\n"
226                                "which its expression is valid.\n"),
227                                signed_field ("wpnum", b->number));
228 
229      - '%p[' - output the following text in a specified style.
230        '%p]' - output the following text in the default style.
231 
232        The argument to '%p[' is a ui_file_style pointer.  The argument
233        to '%p]' must be nullptr.
234 
235        This is useful when you want to output some portion of a string
236        literal in some style.  E.g.:
237 
238            uiout->message (_(" %p[<repeats %u times>%p]"),
239                                metadata_style.style ().ptr (),
240                                reps, repeats, nullptr);
241 
242      - '%ps' - output a styled string.
243 
244        The argument is the result of a call to styled_string.  This is
245        useful when you want to output some runtime-generated string in
246        some style.  E.g.:
247 
248            uiout->message (_("this is a target address %ps.\n"),
249                                styled_string (address_style.style (),
250                                                   paddress (gdbarch, pc)));
251 
252      Note that these all "abuse" the %p printf format spec, in order
253      to be compatible with GCC's printf format checking.  This is OK
254      because code in GDB that wants to print a host address should use
255      host_address_to_string instead of %p.  */
256   void message (const char *format, ...) ATTRIBUTE_PRINTF (2, 3);
257   void vmessage (const ui_file_style &in_style,
258                      const char *format, va_list args) ATTRIBUTE_PRINTF (3, 0);
259 
wrap_hint(int indent)260   void wrap_hint (int indent) { do_wrap_hint (indent); }
261 
flush()262   void flush () { do_flush (); }
263 
264   /* Redirect the output of a ui_out object temporarily.  */
redirect(ui_file * outstream)265   void redirect (ui_file *outstream) { do_redirect (outstream); }
266 
test_flags(ui_out_flags mask)267   ui_out_flags test_flags (ui_out_flags mask)
268   { return m_flags & mask; }
269 
270   /* HACK: Code in GDB is currently checking to see the type of ui_out
271      builder when determining which output to produce.  This function is
272      a hack to encapsulate that test.  Once GDB manages to separate the
273      CLI/MI from the core of GDB the problem should just go away ....  */
274 
is_mi_like_p()275   bool is_mi_like_p () const { return do_is_mi_like_p (); }
276 
277   bool query_table_field (int colno, int *width, int *alignment,
278                                 const char **col_name);
279 
280   /* Return true if this stream is prepared to handle style
281      escapes.  */
282   virtual bool can_emit_style_escape () const = 0;
283 
284   /* Return the ui_file currently used for output.  */
285   virtual ui_file *current_stream () const = 0;
286 
287   /* An object that starts and finishes displaying progress updates.  */
288   class progress_update
289   {
290   public:
291     /* Represents the printing state of a progress update.  */
292     enum state
293     {
294       /* Printing will start with the next update.  */
295       START,
296       /* Printing has already started.  */
297       WORKING,
298       /* Progress bar printing has already started.  */
299       BAR
300     };
301 
302     /* SHOULD_PRINT indicates whether something should be printed for a tty.  */
progress_update()303     progress_update ()
304     {
305       m_uiout = current_uiout;
306       m_uiout->do_progress_start ();
307     }
308 
~progress_update()309     ~progress_update ()
310     {
311       m_uiout->do_progress_end ();
312     }
313 
314     progress_update (const progress_update &) = delete;
315     progress_update &operator= (const progress_update &) = delete;
316 
317     /* Emit some progress for this progress meter.  Includes current
318        amount of progress made and total amount in the display.  */
update_progress(const std::string & msg,const char * unit,double cur,double total)319     void update_progress (const std::string& msg, const char *unit,
320                                 double cur, double total)
321     {
322       m_uiout->do_progress_notify (msg, unit, cur, total);
323     }
324 
325     /* Emit some progress for this progress meter.  */
update_progress(const std::string & msg)326     void update_progress (const std::string& msg)
327     {
328       m_uiout->do_progress_notify (msg, "", -1, -1);
329     }
330 
331   private:
332 
333     struct ui_out *m_uiout;
334   };
335 
336 protected:
337 
338   virtual void do_table_begin (int nbrofcols, int nr_rows, const char *tblid)
339     = 0;
340   virtual void do_table_body () = 0;
341   virtual void do_table_end () = 0;
342   virtual void do_table_header (int width, ui_align align,
343                                         const std::string &col_name,
344                                         const std::string &col_hdr) = 0;
345 
346   virtual void do_begin (ui_out_type type, const char *id) = 0;
347   virtual void do_end (ui_out_type type) = 0;
348   virtual void do_field_signed (int fldno, int width, ui_align align,
349                                         const char *fldname, LONGEST value) = 0;
350   virtual void do_field_unsigned (int fldno, int width, ui_align align,
351                                           const char *fldname, ULONGEST value) = 0;
352   virtual void do_field_skip (int fldno, int width, ui_align align,
353                                     const char *fldname) = 0;
354   virtual void do_field_string (int fldno, int width, ui_align align,
355                                         const char *fldname, const char *string,
356                                         const ui_file_style &style) = 0;
357   virtual void do_field_fmt (int fldno, int width, ui_align align,
358                                    const char *fldname, const ui_file_style &style,
359                                    const char *format, va_list args)
360     ATTRIBUTE_PRINTF (7, 0) = 0;
361   virtual void do_spaces (int numspaces) = 0;
362   virtual void do_text (const char *string) = 0;
363   virtual void do_message (const ui_file_style &style,
364                                  const char *format, va_list args)
365     ATTRIBUTE_PRINTF (3,0) = 0;
366   virtual void do_wrap_hint (int indent) = 0;
367   virtual void do_flush () = 0;
368   virtual void do_redirect (struct ui_file *outstream) = 0;
369 
370   virtual void do_progress_start () = 0;
371   virtual void do_progress_notify (const std::string &, const char *,
372                                            double, double) = 0;
373   virtual void do_progress_end () = 0;
374 
375   /* Set as not MI-like by default.  It is overridden in subclasses if
376      necessary.  */
377 
do_is_mi_like_p()378   virtual bool do_is_mi_like_p () const
379   { return false; }
380 
381  private:
382   void call_do_message (const ui_file_style &style, const char *format,
383                               ...);
384 
385   ui_out_flags m_flags;
386 
387   /* Vector to store and track the ui-out levels.  */
388   std::vector<std::unique_ptr<ui_out_level>> m_levels;
389 
390   /* A table, if any.  At present only a single table is supported.  */
391   std::unique_ptr<ui_out_table> m_table_up;
392 
393   void verify_field (int *fldno, int *width, ui_align *align);
394 
395   int level () const;
396   ui_out_level *current_level () const;
397 };
398 
399 /* Start a new tuple or list on construction, and end it on
400    destruction.  Normally this is used via the typedefs
401    ui_out_emit_tuple and ui_out_emit_list.  */
402 template<ui_out_type Type>
403 class ui_out_emit_type
404 {
405 public:
406 
ui_out_emit_type(struct ui_out * uiout,const char * id)407   ui_out_emit_type (struct ui_out *uiout, const char *id)
408     : m_uiout (uiout)
409   {
410     uiout->begin (Type, id);
411   }
412 
~ui_out_emit_type()413   ~ui_out_emit_type ()
414   {
415     m_uiout->end (Type);
416   }
417 
418   DISABLE_COPY_AND_ASSIGN (ui_out_emit_type);
419 
420 private:
421 
422   struct ui_out *m_uiout;
423 };
424 
425 typedef ui_out_emit_type<ui_out_type_tuple> ui_out_emit_tuple;
426 typedef ui_out_emit_type<ui_out_type_list> ui_out_emit_list;
427 
428 /* Start a new table on construction, and end the table on
429    destruction.  */
430 class ui_out_emit_table
431 {
432 public:
433 
ui_out_emit_table(struct ui_out * uiout,int nr_cols,int nr_rows,const char * tblid)434   ui_out_emit_table (struct ui_out *uiout, int nr_cols, int nr_rows,
435                          const char *tblid)
436     : m_uiout (uiout)
437   {
438     m_uiout->table_begin (nr_cols, nr_rows, tblid);
439   }
440 
~ui_out_emit_table()441   ~ui_out_emit_table ()
442   {
443     m_uiout->table_end ();
444   }
445 
446   ui_out_emit_table (const ui_out_emit_table &) = delete;
447   ui_out_emit_table &operator= (const ui_out_emit_table &) = delete;
448 
449 private:
450 
451   struct ui_out *m_uiout;
452 };
453 
454 /* On construction, redirect a uiout to a given stream.  On
455    destruction, pop the last redirection by calling the uiout's
456    redirect method with a NULL parameter.  */
457 class ui_out_redirect_pop
458 {
459 public:
460 
ui_out_redirect_pop(ui_out * uiout,ui_file * stream)461   ui_out_redirect_pop (ui_out *uiout, ui_file *stream)
462     : m_uiout (uiout)
463   {
464     m_uiout->redirect (stream);
465   }
466 
~ui_out_redirect_pop()467   ~ui_out_redirect_pop ()
468   {
469     m_uiout->redirect (NULL);
470   }
471 
472   ui_out_redirect_pop (const ui_out_redirect_pop &) = delete;
473   ui_out_redirect_pop &operator= (const ui_out_redirect_pop &) = delete;
474 
475 private:
476   struct ui_out *m_uiout;
477 };
478 
479 struct buffered_streams;
480 
481 /* Organizes writes to a collection of buffered output streams
482    so that when flushed, output is written to all streams in
483    chronological order.  */
484 
485 struct buffer_group
486 {
487   buffer_group (ui_out *uiout);
488 
489   /* Flush all buffered writes to the underlying output streams.  */
490   void flush () const;
491 
492   /* Record contents of BUF and associate it with STREAM.  */
493   void write (const char *buf, long length_buf, ui_file *stream);
494 
495   /* Record a wrap_here and associate it with STREAM.  */
496   void wrap_here (int indent, ui_file *stream);
497 
498   /* Record a call to flush and associate it with STREAM.  */
499   void flush_here (ui_file *stream);
500 
501 private:
502 
503   struct output_unit
504   {
505     output_unit (std::string msg, int wrap_hint = -1, bool flush = false)
m_msgbuffer_group::output_unit506       : m_msg (msg), m_wrap_hint (wrap_hint), m_flush (flush)
507     {}
508 
509     /* Write contents of this output_unit to the underlying stream.  */
510     void flush () const;
511 
512     /* Underlying stream for which this output unit will be written to.  */
513     ui_file *m_stream;
514 
515     /* String to be written to underlying buffer.  */
516     std::string m_msg;
517 
518     /* Argument to wrap_here.  -1 indicates no wrap.  Used to call wrap_here
519        during buffer flush.  */
520     int m_wrap_hint;
521 
522     /* Indicate that the underlying output stream's flush should be called.  */
523     bool m_flush;
524   };
525 
526   /* Output_units to be written to buffered output streams.  */
527   std::vector<output_unit> m_buffered_output;
528 
529   /* Buffered output streams.  */
530   std::unique_ptr<buffered_streams> m_buffered_streams;
531 };
532 
533 /* If FILE is a buffering_file, return it's underlying stream.  */
534 
535 extern ui_file *get_unbuffered (ui_file *file);
536 
537 /* Buffer output to gdb_stdout and gdb_stderr for the duration of FUNC.  */
538 
539 template<typename F, typename... Arg>
540 void
do_with_buffered_output(F func,ui_out * uiout,Arg...args)541 do_with_buffered_output (F func, ui_out *uiout, Arg... args)
542 {
543   buffer_group g (uiout);
544 
545   try
546     {
547       func (uiout, std::forward<Arg> (args)...);
548     }
549   catch (gdb_exception &ex)
550     {
551       /* Ideally flush would be called in the destructor of buffer_group,
552            however flushing might cause an exception to be thrown.  Catch it
553            and ensure the first exception propagates.  */
554       try
555           {
556             g.flush ();
557           }
558       catch (const gdb_exception &)
559           {
560           }
561 
562       throw_exception (std::move (ex));
563     }
564 
565   /* Try was successful.  Let any further exceptions propagate.  */
566   g.flush ();
567 }
568 
569 /* Accumulate writes to an underlying ui_file.  Output to the
570    underlying file is deferred until required.  */
571 
572 struct buffering_file : public ui_file
573 {
buffering_filebuffering_file574   buffering_file (buffer_group *group, ui_file *stream)
575     : m_group (group),
576       m_stream (stream)
577   { /* Nothing.  */ }
578 
579   /* Return the underlying output stream.  */
streambuffering_file580   ui_file *stream () const
581   {
582     return m_stream;
583   }
584 
585   /* Record the contents of BUF.  */
writebuffering_file586   void write (const char *buf, long length_buf) override
587   {
588     m_group->write (buf, length_buf, m_stream);
589   }
590 
591   /* Record a wrap_here call with argument INDENT.  */
wrap_herebuffering_file592   void wrap_here (int indent) override
593   {
594     m_group->wrap_here (indent, m_stream);
595   }
596 
597   /* Return true if the underlying stream is a tty.  */
isattybuffering_file598   bool isatty () override
599   {
600     return m_stream->isatty ();
601   }
602 
603   /* Return true if ANSI escapes can be used on the underlying stream.  */
can_emit_style_escapebuffering_file604   bool can_emit_style_escape () override
605   {
606     return m_stream->can_emit_style_escape ();
607   }
608 
609   /* Flush the underlying output stream.  */
flushbuffering_file610   void flush () override
611   {
612     return m_group->flush_here (m_stream);
613   }
614 
615 private:
616 
617   /* Coordinates buffering across multiple buffering_files.  */
618   buffer_group *m_group;
619 
620   /* The underlying output stream.  */
621   ui_file *m_stream;
622 };
623 
624 /* Attaches and detaches buffers for each of the gdb_std* streams.  */
625 
626 struct buffered_streams
627 {
628   buffered_streams (buffer_group *group, ui_out *uiout);
629 
~buffered_streamsbuffered_streams630   ~buffered_streams ()
631   {
632     this->remove_buffers ();
633   }
634 
635   /* Remove buffering_files from all underlying streams.  */
636   void remove_buffers ();
637 
638 private:
639 
640   /* True if buffers are still attached to each underlying output stream.  */
641   bool m_buffers_in_place;
642 
643   /* Buffers for each gdb_std* output stream.  */
644   buffering_file m_buffered_stdout;
645   buffering_file m_buffered_stderr;
646   buffering_file m_buffered_stdlog;
647   buffering_file m_buffered_stdtarg;
648 
649   /* Buffer for current_uiout's output stream.  */
650   std::optional<buffering_file> m_buffered_current_uiout;
651 
652   /* Additional ui_out being buffered.  */
653   ui_out *m_uiout;
654 
655   /* Buffer for m_uiout's output stream.  */
656   std::optional<buffering_file> m_buffered_uiout;
657 };
658 
659 #endif /* UI_OUT_H */
660