Fix colors in TUI mode in MS-Windows build with ncurses
[external/binutils.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2019 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include <ctype.h>
22 #include "common/gdb_wait.h"
23 #include "event-top.h"
24 #include "gdbthread.h"
25 #include "fnmatch.h"
26 #include "gdb_bfd.h"
27 #ifdef HAVE_SYS_RESOURCE_H
28 #include <sys/resource.h>
29 #endif /* HAVE_SYS_RESOURCE_H */
30
31 #ifdef TUI
32 #include "tui/tui.h"            /* For tui_get_command_dimension.   */
33 #endif
34
35 #ifdef __GO32__
36 #include <pc.h>
37 #endif
38
39 #include <signal.h>
40 #include "gdbcmd.h"
41 #include "serial.h"
42 #include "bfd.h"
43 #include "target.h"
44 #include "gdb-demangle.h"
45 #include "expression.h"
46 #include "language.h"
47 #include "charset.h"
48 #include "annotate.h"
49 #include "filenames.h"
50 #include "symfile.h"
51 #include "gdb_obstack.h"
52 #include "gdbcore.h"
53 #include "top.h"
54 #include "main.h"
55 #include "solist.h"
56
57 #include "inferior.h"           /* for signed_pointer_to_address */
58
59 #include "gdb_curses.h"
60
61 #include "readline/readline.h"
62
63 #include <chrono>
64
65 #include "gdb_usleep.h"
66 #include "interps.h"
67 #include "gdb_regex.h"
68 #include "common/job-control.h"
69 #include "common/selftest.h"
70 #include "common/gdb_optional.h"
71 #include "cp-support.h"
72 #include <algorithm>
73 #include "common/pathstuff.h"
74 #include "cli/cli-style.h"
75 #include "common/scope-exit.h"
76
77 void (*deprecated_error_begin_hook) (void);
78
79 /* Prototypes for local functions */
80
81 static void vfprintf_maybe_filtered (struct ui_file *, const char *,
82                                      va_list, int) ATTRIBUTE_PRINTF (2, 0);
83
84 static void fputs_maybe_filtered (const char *, struct ui_file *, int);
85
86 static void prompt_for_continue (void);
87
88 static void set_screen_size (void);
89 static void set_width (void);
90
91 /* Time spent in prompt_for_continue in the currently executing command
92    waiting for user to respond.
93    Initialized in make_command_stats_cleanup.
94    Modified in prompt_for_continue and defaulted_query.
95    Used in report_command_stats.  */
96
97 static std::chrono::steady_clock::duration prompt_for_continue_wait_time;
98
99 /* A flag indicating whether to timestamp debugging messages.  */
100
101 static int debug_timestamp = 0;
102
103 /* Nonzero means that strings with character values >0x7F should be printed
104    as octal escapes.  Zero means just print the value (e.g. it's an
105    international character, and the terminal or window can cope.)  */
106
107 int sevenbit_strings = 0;
108 static void
109 show_sevenbit_strings (struct ui_file *file, int from_tty,
110                        struct cmd_list_element *c, const char *value)
111 {
112   fprintf_filtered (file, _("Printing of 8-bit characters "
113                             "in strings as \\nnn is %s.\n"),
114                     value);
115 }
116
117 /* String to be printed before warning messages, if any.  */
118
119 const char *warning_pre_print = "\nwarning: ";
120
121 int pagination_enabled = 1;
122 static void
123 show_pagination_enabled (struct ui_file *file, int from_tty,
124                          struct cmd_list_element *c, const char *value)
125 {
126   fprintf_filtered (file, _("State of pagination is %s.\n"), value);
127 }
128
129 \f
130 /* Cleanup utilities.
131
132    These are not defined in cleanups.c (nor declared in cleanups.h)
133    because while they use the "cleanup API" they are not part of the
134    "cleanup API".  */
135
136 /* This function is useful for cleanups.
137    Do
138
139    foo = xmalloc (...);
140    old_chain = make_cleanup (free_current_contents, &foo);
141
142    to arrange to free the object thus allocated.  */
143
144 void
145 free_current_contents (void *ptr)
146 {
147   void **location = (void **) ptr;
148
149   if (location == NULL)
150     internal_error (__FILE__, __LINE__,
151                     _("free_current_contents: NULL pointer"));
152   if (*location != NULL)
153     {
154       xfree (*location);
155       *location = NULL;
156     }
157 }
158 \f
159
160
161 /* Print a warning message.  The first argument STRING is the warning
162    message, used as an fprintf format string, the second is the
163    va_list of arguments for that string.  A warning is unfiltered (not
164    paginated) so that the user does not need to page through each
165    screen full of warnings when there are lots of them.  */
166
167 void
168 vwarning (const char *string, va_list args)
169 {
170   if (deprecated_warning_hook)
171     (*deprecated_warning_hook) (string, args);
172   else
173     {
174       gdb::optional<target_terminal::scoped_restore_terminal_state> term_state;
175       if (target_supports_terminal_ours ())
176         {
177           term_state.emplace ();
178           target_terminal::ours_for_output ();
179         }
180       if (filtered_printing_initialized ())
181         wrap_here ("");         /* Force out any buffered output.  */
182       gdb_flush (gdb_stdout);
183       if (warning_pre_print)
184         fputs_unfiltered (warning_pre_print, gdb_stderr);
185       vfprintf_unfiltered (gdb_stderr, string, args);
186       fprintf_unfiltered (gdb_stderr, "\n");
187     }
188 }
189
190 /* Print an error message and return to command level.
191    The first argument STRING is the error message, used as a fprintf string,
192    and the remaining args are passed as arguments to it.  */
193
194 void
195 verror (const char *string, va_list args)
196 {
197   throw_verror (GENERIC_ERROR, string, args);
198 }
199
200 void
201 error_stream (const string_file &stream)
202 {
203   error (("%s"), stream.c_str ());
204 }
205
206 /* Emit a message and abort.  */
207
208 static void ATTRIBUTE_NORETURN
209 abort_with_message (const char *msg)
210 {
211   if (current_ui == NULL)
212     fputs (msg, stderr);
213   else
214     fputs_unfiltered (msg, gdb_stderr);
215
216   abort ();             /* NOTE: GDB has only three calls to abort().  */
217 }
218
219 /* Dump core trying to increase the core soft limit to hard limit first.  */
220
221 void
222 dump_core (void)
223 {
224 #ifdef HAVE_SETRLIMIT
225   struct rlimit rlim = { (rlim_t) RLIM_INFINITY, (rlim_t) RLIM_INFINITY };
226
227   setrlimit (RLIMIT_CORE, &rlim);
228 #endif /* HAVE_SETRLIMIT */
229
230   abort ();             /* NOTE: GDB has only three calls to abort().  */
231 }
232
233 /* Check whether GDB will be able to dump core using the dump_core
234    function.  Returns zero if GDB cannot or should not dump core.
235    If LIMIT_KIND is LIMIT_CUR the user's soft limit will be respected.
236    If LIMIT_KIND is LIMIT_MAX only the hard limit will be respected.  */
237
238 int
239 can_dump_core (enum resource_limit_kind limit_kind)
240 {
241 #ifdef HAVE_GETRLIMIT
242   struct rlimit rlim;
243
244   /* Be quiet and assume we can dump if an error is returned.  */
245   if (getrlimit (RLIMIT_CORE, &rlim) != 0)
246     return 1;
247
248   switch (limit_kind)
249     {
250     case LIMIT_CUR:
251       if (rlim.rlim_cur == 0)
252         return 0;
253       /* Fall through.  */
254
255     case LIMIT_MAX:
256       if (rlim.rlim_max == 0)
257         return 0;
258     }
259 #endif /* HAVE_GETRLIMIT */
260
261   return 1;
262 }
263
264 /* Print a warning that we cannot dump core.  */
265
266 void
267 warn_cant_dump_core (const char *reason)
268 {
269   fprintf_unfiltered (gdb_stderr,
270                       _("%s\nUnable to dump core, use `ulimit -c"
271                         " unlimited' before executing GDB next time.\n"),
272                       reason);
273 }
274
275 /* Check whether GDB will be able to dump core using the dump_core
276    function, and print a warning if we cannot.  */
277
278 static int
279 can_dump_core_warn (enum resource_limit_kind limit_kind,
280                     const char *reason)
281 {
282   int core_dump_allowed = can_dump_core (limit_kind);
283
284   if (!core_dump_allowed)
285     warn_cant_dump_core (reason);
286
287   return core_dump_allowed;
288 }
289
290 /* Allow the user to configure the debugger behavior with respect to
291    what to do when an internal problem is detected.  */
292
293 const char internal_problem_ask[] = "ask";
294 const char internal_problem_yes[] = "yes";
295 const char internal_problem_no[] = "no";
296 static const char *const internal_problem_modes[] =
297 {
298   internal_problem_ask,
299   internal_problem_yes,
300   internal_problem_no,
301   NULL
302 };
303
304 /* Print a message reporting an internal error/warning.  Ask the user
305    if they want to continue, dump core, or just exit.  Return
306    something to indicate a quit.  */
307
308 struct internal_problem
309 {
310   const char *name;
311   int user_settable_should_quit;
312   const char *should_quit;
313   int user_settable_should_dump_core;
314   const char *should_dump_core;
315 };
316
317 /* Report a problem, internal to GDB, to the user.  Once the problem
318    has been reported, and assuming GDB didn't quit, the caller can
319    either allow execution to resume or throw an error.  */
320
321 static void ATTRIBUTE_PRINTF (4, 0)
322 internal_vproblem (struct internal_problem *problem,
323                    const char *file, int line, const char *fmt, va_list ap)
324 {
325   static int dejavu;
326   int quit_p;
327   int dump_core_p;
328   std::string reason;
329
330   /* Don't allow infinite error/warning recursion.  */
331   {
332     static char msg[] = "Recursive internal problem.\n";
333
334     switch (dejavu)
335       {
336       case 0:
337         dejavu = 1;
338         break;
339       case 1:
340         dejavu = 2;
341         abort_with_message (msg);
342       default:
343         dejavu = 3;
344         /* Newer GLIBC versions put the warn_unused_result attribute
345            on write, but this is one of those rare cases where
346            ignoring the return value is correct.  Casting to (void)
347            does not fix this problem.  This is the solution suggested
348            at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509.  */
349         if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
350           abort (); /* NOTE: GDB has only three calls to abort().  */
351         exit (1);
352       }
353   }
354
355   /* Create a string containing the full error/warning message.  Need
356      to call query with this full string, as otherwize the reason
357      (error/warning) and question become separated.  Format using a
358      style similar to a compiler error message.  Include extra detail
359      so that the user knows that they are living on the edge.  */
360   {
361     std::string msg = string_vprintf (fmt, ap);
362     reason = string_printf ("%s:%d: %s: %s\n"
363                             "A problem internal to GDB has been detected,\n"
364                             "further debugging may prove unreliable.",
365                             file, line, problem->name, msg.c_str ());
366   }
367
368   /* Fall back to abort_with_message if gdb_stderr is not set up.  */
369   if (current_ui == NULL)
370     {
371       fputs (reason.c_str (), stderr);
372       abort_with_message ("\n");
373     }
374
375   /* Try to get the message out and at the start of a new line.  */
376   gdb::optional<target_terminal::scoped_restore_terminal_state> term_state;
377   if (target_supports_terminal_ours ())
378     {
379       term_state.emplace ();
380       target_terminal::ours_for_output ();
381     }
382   if (filtered_printing_initialized ())
383     begin_line ();
384
385   /* Emit the message unless query will emit it below.  */
386   if (problem->should_quit != internal_problem_ask
387       || !confirm
388       || !filtered_printing_initialized ())
389     fprintf_unfiltered (gdb_stderr, "%s\n", reason.c_str ());
390
391   if (problem->should_quit == internal_problem_ask)
392     {
393       /* Default (yes/batch case) is to quit GDB.  When in batch mode
394          this lessens the likelihood of GDB going into an infinite
395          loop.  */
396       if (!confirm || !filtered_printing_initialized ())
397         quit_p = 1;
398       else
399         quit_p = query (_("%s\nQuit this debugging session? "),
400                         reason.c_str ());
401     }
402   else if (problem->should_quit == internal_problem_yes)
403     quit_p = 1;
404   else if (problem->should_quit == internal_problem_no)
405     quit_p = 0;
406   else
407     internal_error (__FILE__, __LINE__, _("bad switch"));
408
409   fputs_unfiltered (_("\nThis is a bug, please report it."), gdb_stderr);
410   if (REPORT_BUGS_TO[0])
411     fprintf_unfiltered (gdb_stderr, _("  For instructions, see:\n%s."),
412                         REPORT_BUGS_TO);
413   fputs_unfiltered ("\n\n", gdb_stderr);
414
415   if (problem->should_dump_core == internal_problem_ask)
416     {
417       if (!can_dump_core_warn (LIMIT_MAX, reason.c_str ()))
418         dump_core_p = 0;
419       else if (!filtered_printing_initialized ())
420         dump_core_p = 1;
421       else
422         {
423           /* Default (yes/batch case) is to dump core.  This leaves a GDB
424              `dropping' so that it is easier to see that something went
425              wrong in GDB.  */
426           dump_core_p = query (_("%s\nCreate a core file of GDB? "),
427                                reason.c_str ());
428         }
429     }
430   else if (problem->should_dump_core == internal_problem_yes)
431     dump_core_p = can_dump_core_warn (LIMIT_MAX, reason.c_str ());
432   else if (problem->should_dump_core == internal_problem_no)
433     dump_core_p = 0;
434   else
435     internal_error (__FILE__, __LINE__, _("bad switch"));
436
437   if (quit_p)
438     {
439       if (dump_core_p)
440         dump_core ();
441       else
442         exit (1);
443     }
444   else
445     {
446       if (dump_core_p)
447         {
448 #ifdef HAVE_WORKING_FORK
449           if (fork () == 0)
450             dump_core ();
451 #endif
452         }
453     }
454
455   dejavu = 0;
456 }
457
458 static struct internal_problem internal_error_problem = {
459   "internal-error", 1, internal_problem_ask, 1, internal_problem_ask
460 };
461
462 void
463 internal_verror (const char *file, int line, const char *fmt, va_list ap)
464 {
465   internal_vproblem (&internal_error_problem, file, line, fmt, ap);
466   throw_quit (_("Command aborted."));
467 }
468
469 static struct internal_problem internal_warning_problem = {
470   "internal-warning", 1, internal_problem_ask, 1, internal_problem_ask
471 };
472
473 void
474 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
475 {
476   internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
477 }
478
479 static struct internal_problem demangler_warning_problem = {
480   "demangler-warning", 1, internal_problem_ask, 0, internal_problem_no
481 };
482
483 void
484 demangler_vwarning (const char *file, int line, const char *fmt, va_list ap)
485 {
486   internal_vproblem (&demangler_warning_problem, file, line, fmt, ap);
487 }
488
489 void
490 demangler_warning (const char *file, int line, const char *string, ...)
491 {
492   va_list ap;
493
494   va_start (ap, string);
495   demangler_vwarning (file, line, string, ap);
496   va_end (ap);
497 }
498
499 /* Dummy functions to keep add_prefix_cmd happy.  */
500
501 static void
502 set_internal_problem_cmd (const char *args, int from_tty)
503 {
504 }
505
506 static void
507 show_internal_problem_cmd (const char *args, int from_tty)
508 {
509 }
510
511 /* When GDB reports an internal problem (error or warning) it gives
512    the user the opportunity to quit GDB and/or create a core file of
513    the current debug session.  This function registers a few commands
514    that make it possible to specify that GDB should always or never
515    quit or create a core file, without asking.  The commands look
516    like:
517
518    maint set PROBLEM-NAME quit ask|yes|no
519    maint show PROBLEM-NAME quit
520    maint set PROBLEM-NAME corefile ask|yes|no
521    maint show PROBLEM-NAME corefile
522
523    Where PROBLEM-NAME is currently "internal-error" or
524    "internal-warning".  */
525
526 static void
527 add_internal_problem_command (struct internal_problem *problem)
528 {
529   struct cmd_list_element **set_cmd_list;
530   struct cmd_list_element **show_cmd_list;
531   char *set_doc;
532   char *show_doc;
533
534   set_cmd_list = XNEW (struct cmd_list_element *);
535   show_cmd_list = XNEW (struct cmd_list_element *);
536   *set_cmd_list = NULL;
537   *show_cmd_list = NULL;
538
539   set_doc = xstrprintf (_("Configure what GDB does when %s is detected."),
540                         problem->name);
541
542   show_doc = xstrprintf (_("Show what GDB does when %s is detected."),
543                          problem->name);
544
545   add_prefix_cmd (problem->name,
546                   class_maintenance, set_internal_problem_cmd, set_doc,
547                   set_cmd_list,
548                   concat ("maintenance set ", problem->name, " ",
549                           (char *) NULL),
550                   0/*allow-unknown*/, &maintenance_set_cmdlist);
551
552   add_prefix_cmd (problem->name,
553                   class_maintenance, show_internal_problem_cmd, show_doc,
554                   show_cmd_list,
555                   concat ("maintenance show ", problem->name, " ",
556                           (char *) NULL),
557                   0/*allow-unknown*/, &maintenance_show_cmdlist);
558
559   if (problem->user_settable_should_quit)
560     {
561       set_doc = xstrprintf (_("Set whether GDB should quit "
562                               "when an %s is detected"),
563                             problem->name);
564       show_doc = xstrprintf (_("Show whether GDB will quit "
565                                "when an %s is detected"),
566                              problem->name);
567       add_setshow_enum_cmd ("quit", class_maintenance,
568                             internal_problem_modes,
569                             &problem->should_quit,
570                             set_doc,
571                             show_doc,
572                             NULL, /* help_doc */
573                             NULL, /* setfunc */
574                             NULL, /* showfunc */
575                             set_cmd_list,
576                             show_cmd_list);
577
578       xfree (set_doc);
579       xfree (show_doc);
580     }
581
582   if (problem->user_settable_should_dump_core)
583     {
584       set_doc = xstrprintf (_("Set whether GDB should create a core "
585                               "file of GDB when %s is detected"),
586                             problem->name);
587       show_doc = xstrprintf (_("Show whether GDB will create a core "
588                                "file of GDB when %s is detected"),
589                              problem->name);
590       add_setshow_enum_cmd ("corefile", class_maintenance,
591                             internal_problem_modes,
592                             &problem->should_dump_core,
593                             set_doc,
594                             show_doc,
595                             NULL, /* help_doc */
596                             NULL, /* setfunc */
597                             NULL, /* showfunc */
598                             set_cmd_list,
599                             show_cmd_list);
600
601       xfree (set_doc);
602       xfree (show_doc);
603     }
604 }
605
606 /* Return a newly allocated string, containing the PREFIX followed
607    by the system error message for errno (separated by a colon).  */
608
609 static std::string
610 perror_string (const char *prefix)
611 {
612   char *err;
613
614   err = safe_strerror (errno);
615   return std::string (prefix) + ": " + err;
616 }
617
618 /* Print the system error message for errno, and also mention STRING
619    as the file name for which the error was encountered.  Use ERRCODE
620    for the thrown exception.  Then return to command level.  */
621
622 void
623 throw_perror_with_name (enum errors errcode, const char *string)
624 {
625   std::string combined = perror_string (string);
626
627   /* I understand setting these is a matter of taste.  Still, some people
628      may clear errno but not know about bfd_error.  Doing this here is not
629      unreasonable.  */
630   bfd_set_error (bfd_error_no_error);
631   errno = 0;
632
633   throw_error (errcode, _("%s."), combined.c_str ());
634 }
635
636 /* See throw_perror_with_name, ERRCODE defaults here to GENERIC_ERROR.  */
637
638 void
639 perror_with_name (const char *string)
640 {
641   throw_perror_with_name (GENERIC_ERROR, string);
642 }
643
644 /* Same as perror_with_name except that it prints a warning instead
645    of throwing an error.  */
646
647 void
648 perror_warning_with_name (const char *string)
649 {
650   std::string combined = perror_string (string);
651   warning (_("%s"), combined.c_str ());
652 }
653
654 /* Print the system error message for ERRCODE, and also mention STRING
655    as the file name for which the error was encountered.  */
656
657 void
658 print_sys_errmsg (const char *string, int errcode)
659 {
660   char *err;
661   char *combined;
662
663   err = safe_strerror (errcode);
664   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
665   strcpy (combined, string);
666   strcat (combined, ": ");
667   strcat (combined, err);
668
669   /* We want anything which was printed on stdout to come out first, before
670      this message.  */
671   gdb_flush (gdb_stdout);
672   fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
673 }
674
675 /* Control C eventually causes this to be called, at a convenient time.  */
676
677 void
678 quit (void)
679 {
680   if (sync_quit_force_run)
681     {
682       sync_quit_force_run = 0;
683       quit_force (NULL, 0);
684     }
685
686 #ifdef __MSDOS__
687   /* No steenking SIGINT will ever be coming our way when the
688      program is resumed.  Don't lie.  */
689   throw_quit ("Quit");
690 #else
691   if (job_control
692       /* If there is no terminal switching for this target, then we can't
693          possibly get screwed by the lack of job control.  */
694       || !target_supports_terminal_ours ())
695     throw_quit ("Quit");
696   else
697     throw_quit ("Quit (expect signal SIGINT when the program is resumed)");
698 #endif
699 }
700
701 /* See defs.h.  */
702
703 void
704 maybe_quit (void)
705 {
706   if (sync_quit_force_run)
707     quit ();
708
709   quit_handler ();
710
711   if (deprecated_interactive_hook)
712     deprecated_interactive_hook ();
713 }
714
715 \f
716 /* Called when a memory allocation fails, with the number of bytes of
717    memory requested in SIZE.  */
718
719 void
720 malloc_failure (long size)
721 {
722   if (size > 0)
723     {
724       internal_error (__FILE__, __LINE__,
725                       _("virtual memory exhausted: can't allocate %ld bytes."),
726                       size);
727     }
728   else
729     {
730       internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
731     }
732 }
733
734 /* My replacement for the read system call.
735    Used like `read' but keeps going if `read' returns too soon.  */
736
737 int
738 myread (int desc, char *addr, int len)
739 {
740   int val;
741   int orglen = len;
742
743   while (len > 0)
744     {
745       val = read (desc, addr, len);
746       if (val < 0)
747         return val;
748       if (val == 0)
749         return orglen - len;
750       len -= val;
751       addr += val;
752     }
753   return orglen;
754 }
755
756 void
757 print_spaces (int n, struct ui_file *file)
758 {
759   fputs_unfiltered (n_spaces (n), file);
760 }
761
762 /* Print a host address.  */
763
764 void
765 gdb_print_host_address_1 (const void *addr, struct ui_file *stream)
766 {
767   fprintf_filtered (stream, "%s", host_address_to_string (addr));
768 }
769
770 /* See utils.h.  */
771
772 char *
773 make_hex_string (const gdb_byte *data, size_t length)
774 {
775   char *result = (char *) xmalloc (length * 2 + 1);
776   char *p;
777   size_t i;
778
779   p = result;
780   for (i = 0; i < length; ++i)
781     p += xsnprintf (p, 3, "%02x", data[i]);
782   *p = '\0';
783   return result;
784 }
785
786 \f
787
788 /* An RAII class that sets up to handle input and then tears down
789    during destruction.  */
790
791 class scoped_input_handler
792 {
793 public:
794
795   scoped_input_handler ()
796     : m_quit_handler (&quit_handler, default_quit_handler),
797       m_ui (NULL)
798   {
799     target_terminal::ours ();
800     ui_register_input_event_handler (current_ui);
801     if (current_ui->prompt_state == PROMPT_BLOCKED)
802       m_ui = current_ui;
803   }
804
805   ~scoped_input_handler ()
806   {
807     if (m_ui != NULL)
808       ui_unregister_input_event_handler (m_ui);
809   }
810
811   DISABLE_COPY_AND_ASSIGN (scoped_input_handler);
812
813 private:
814
815   /* Save and restore the terminal state.  */
816   target_terminal::scoped_restore_terminal_state m_term_state;
817
818   /* Save and restore the quit handler.  */
819   scoped_restore_tmpl<quit_handler_ftype *> m_quit_handler;
820
821   /* The saved UI, if non-NULL.  */
822   struct ui *m_ui;
823 };
824
825 \f
826
827 /* This function supports the query, nquery, and yquery functions.
828    Ask user a y-or-n question and return 0 if answer is no, 1 if
829    answer is yes, or default the answer to the specified default
830    (for yquery or nquery).  DEFCHAR may be 'y' or 'n' to provide a
831    default answer, or '\0' for no default.
832    CTLSTR is the control string and should end in "? ".  It should
833    not say how to answer, because we do that.
834    ARGS are the arguments passed along with the CTLSTR argument to
835    printf.  */
836
837 static int ATTRIBUTE_PRINTF (1, 0)
838 defaulted_query (const char *ctlstr, const char defchar, va_list args)
839 {
840   int retval;
841   int def_value;
842   char def_answer, not_def_answer;
843   const char *y_string, *n_string;
844
845   /* Set up according to which answer is the default.  */
846   if (defchar == '\0')
847     {
848       def_value = 1;
849       def_answer = 'Y';
850       not_def_answer = 'N';
851       y_string = "y";
852       n_string = "n";
853     }
854   else if (defchar == 'y')
855     {
856       def_value = 1;
857       def_answer = 'Y';
858       not_def_answer = 'N';
859       y_string = "[y]";
860       n_string = "n";
861     }
862   else
863     {
864       def_value = 0;
865       def_answer = 'N';
866       not_def_answer = 'Y';
867       y_string = "y";
868       n_string = "[n]";
869     }
870
871   /* Automatically answer the default value if the user did not want
872      prompts or the command was issued with the server prefix.  */
873   if (!confirm || server_command)
874     return def_value;
875
876   /* If input isn't coming from the user directly, just say what
877      question we're asking, and then answer the default automatically.  This
878      way, important error messages don't get lost when talking to GDB
879      over a pipe.  */
880   if (current_ui->instream != current_ui->stdin_stream
881       || !input_interactive_p (current_ui)
882       /* Restrict queries to the main UI.  */
883       || current_ui != main_ui)
884     {
885       target_terminal::scoped_restore_terminal_state term_state;
886       target_terminal::ours_for_output ();
887       wrap_here ("");
888       vfprintf_filtered (gdb_stdout, ctlstr, args);
889
890       printf_filtered (_("(%s or %s) [answered %c; "
891                          "input not from terminal]\n"),
892                        y_string, n_string, def_answer);
893       gdb_flush (gdb_stdout);
894
895       return def_value;
896     }
897
898   if (deprecated_query_hook)
899     {
900       target_terminal::scoped_restore_terminal_state term_state;
901       return deprecated_query_hook (ctlstr, args);
902     }
903
904   /* Format the question outside of the loop, to avoid reusing args.  */
905   std::string question = string_vprintf (ctlstr, args);
906   std::string prompt
907     = string_printf (_("%s%s(%s or %s) %s"),
908                      annotation_level > 1 ? "\n\032\032pre-query\n" : "",
909                      question.c_str (), y_string, n_string,
910                      annotation_level > 1 ? "\n\032\032query\n" : "");
911
912   /* Used to add duration we waited for user to respond to
913      prompt_for_continue_wait_time.  */
914   using namespace std::chrono;
915   steady_clock::time_point prompt_started = steady_clock::now ();
916
917   scoped_input_handler prepare_input;
918
919   while (1)
920     {
921       char *response, answer;
922
923       gdb_flush (gdb_stdout);
924       response = gdb_readline_wrapper (prompt.c_str ());
925
926       if (response == NULL)     /* C-d  */
927         {
928           printf_filtered ("EOF [assumed %c]\n", def_answer);
929           retval = def_value;
930           break;
931         }
932
933       answer = response[0];
934       xfree (response);
935
936       if (answer >= 'a')
937         answer -= 040;
938       /* Check answer.  For the non-default, the user must specify
939          the non-default explicitly.  */
940       if (answer == not_def_answer)
941         {
942           retval = !def_value;
943           break;
944         }
945       /* Otherwise, if a default was specified, the user may either
946          specify the required input or have it default by entering
947          nothing.  */
948       if (answer == def_answer
949           || (defchar != '\0' && answer == '\0'))
950         {
951           retval = def_value;
952           break;
953         }
954       /* Invalid entries are not defaulted and require another selection.  */
955       printf_filtered (_("Please answer %s or %s.\n"),
956                        y_string, n_string);
957     }
958
959   /* Add time spend in this routine to prompt_for_continue_wait_time.  */
960   prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
961
962   if (annotation_level > 1)
963     printf_filtered (("\n\032\032post-query\n"));
964   return retval;
965 }
966 \f
967
968 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
969    answer is yes, or 0 if answer is defaulted.
970    Takes three args which are given to printf to print the question.
971    The first, a control string, should end in "? ".
972    It should not say how to answer, because we do that.  */
973
974 int
975 nquery (const char *ctlstr, ...)
976 {
977   va_list args;
978   int ret;
979
980   va_start (args, ctlstr);
981   ret = defaulted_query (ctlstr, 'n', args);
982   va_end (args);
983   return ret;
984 }
985
986 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
987    answer is yes, or 1 if answer is defaulted.
988    Takes three args which are given to printf to print the question.
989    The first, a control string, should end in "? ".
990    It should not say how to answer, because we do that.  */
991
992 int
993 yquery (const char *ctlstr, ...)
994 {
995   va_list args;
996   int ret;
997
998   va_start (args, ctlstr);
999   ret = defaulted_query (ctlstr, 'y', args);
1000   va_end (args);
1001   return ret;
1002 }
1003
1004 /* Ask user a y-or-n question and return 1 iff answer is yes.
1005    Takes three args which are given to printf to print the question.
1006    The first, a control string, should end in "? ".
1007    It should not say how to answer, because we do that.  */
1008
1009 int
1010 query (const char *ctlstr, ...)
1011 {
1012   va_list args;
1013   int ret;
1014
1015   va_start (args, ctlstr);
1016   ret = defaulted_query (ctlstr, '\0', args);
1017   va_end (args);
1018   return ret;
1019 }
1020
1021 /* A helper for parse_escape that converts a host character to a
1022    target character.  C is the host character.  If conversion is
1023    possible, then the target character is stored in *TARGET_C and the
1024    function returns 1.  Otherwise, the function returns 0.  */
1025
1026 static int
1027 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
1028 {
1029   char the_char = c;
1030   int result = 0;
1031
1032   auto_obstack host_data;
1033
1034   convert_between_encodings (target_charset (gdbarch), host_charset (),
1035                              (gdb_byte *) &the_char, 1, 1,
1036                              &host_data, translit_none);
1037
1038   if (obstack_object_size (&host_data) == 1)
1039     {
1040       result = 1;
1041       *target_c = *(char *) obstack_base (&host_data);
1042     }
1043
1044   return result;
1045 }
1046
1047 /* Parse a C escape sequence.  STRING_PTR points to a variable
1048    containing a pointer to the string to parse.  That pointer
1049    should point to the character after the \.  That pointer
1050    is updated past the characters we use.  The value of the
1051    escape sequence is returned.
1052
1053    A negative value means the sequence \ newline was seen,
1054    which is supposed to be equivalent to nothing at all.
1055
1056    If \ is followed by a null character, we return a negative
1057    value and leave the string pointer pointing at the null character.
1058
1059    If \ is followed by 000, we return 0 and leave the string pointer
1060    after the zeros.  A value of 0 does not mean end of string.  */
1061
1062 int
1063 parse_escape (struct gdbarch *gdbarch, const char **string_ptr)
1064 {
1065   int target_char = -2; /* Initialize to avoid GCC warnings.  */
1066   int c = *(*string_ptr)++;
1067
1068   switch (c)
1069     {
1070       case '\n':
1071         return -2;
1072       case 0:
1073         (*string_ptr)--;
1074         return 0;
1075
1076       case '0':
1077       case '1':
1078       case '2':
1079       case '3':
1080       case '4':
1081       case '5':
1082       case '6':
1083       case '7':
1084         {
1085           int i = host_hex_value (c);
1086           int count = 0;
1087           while (++count < 3)
1088             {
1089               c = (**string_ptr);
1090               if (isdigit (c) && c != '8' && c != '9')
1091                 {
1092                   (*string_ptr)++;
1093                   i *= 8;
1094                   i += host_hex_value (c);
1095                 }
1096               else
1097                 {
1098                   break;
1099                 }
1100             }
1101           return i;
1102         }
1103
1104     case 'a':
1105       c = '\a';
1106       break;
1107     case 'b':
1108       c = '\b';
1109       break;
1110     case 'f':
1111       c = '\f';
1112       break;
1113     case 'n':
1114       c = '\n';
1115       break;
1116     case 'r':
1117       c = '\r';
1118       break;
1119     case 't':
1120       c = '\t';
1121       break;
1122     case 'v':
1123       c = '\v';
1124       break;
1125
1126     default:
1127       break;
1128     }
1129
1130   if (!host_char_to_target (gdbarch, c, &target_char))
1131     error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1132              " which has no equivalent\nin the `%s' character set."),
1133            c, c, target_charset (gdbarch));
1134   return target_char;
1135 }
1136 \f
1137 /* Print the character C on STREAM as part of the contents of a literal
1138    string whose delimiter is QUOTER.  Note that this routine should only
1139    be called for printing things which are independent of the language
1140    of the program being debugged.
1141
1142    printchar will normally escape backslashes and instances of QUOTER. If
1143    QUOTER is 0, printchar won't escape backslashes or any quoting character.
1144    As a side effect, if you pass the backslash character as the QUOTER,
1145    printchar will escape backslashes as usual, but not any other quoting
1146    character. */
1147
1148 static void
1149 printchar (int c, do_fputc_ftype do_fputc, ui_file *stream, int quoter)
1150 {
1151   c &= 0xFF;                    /* Avoid sign bit follies */
1152
1153   if (c < 0x20 ||               /* Low control chars */
1154       (c >= 0x7F && c < 0xA0) ||        /* DEL, High controls */
1155       (sevenbit_strings && c >= 0x80))
1156     {                           /* high order bit set */
1157       do_fputc ('\\', stream);
1158
1159       switch (c)
1160         {
1161         case '\n':
1162           do_fputc ('n', stream);
1163           break;
1164         case '\b':
1165           do_fputc ('b', stream);
1166           break;
1167         case '\t':
1168           do_fputc ('t', stream);
1169           break;
1170         case '\f':
1171           do_fputc ('f', stream);
1172           break;
1173         case '\r':
1174           do_fputc ('r', stream);
1175           break;
1176         case '\033':
1177           do_fputc ('e', stream);
1178           break;
1179         case '\007':
1180           do_fputc ('a', stream);
1181           break;
1182         default:
1183           {
1184             do_fputc ('0' + ((c >> 6) & 0x7), stream);
1185             do_fputc ('0' + ((c >> 3) & 0x7), stream);
1186             do_fputc ('0' + ((c >> 0) & 0x7), stream);
1187             break;
1188           }
1189         }
1190     }
1191   else
1192     {
1193       if (quoter != 0 && (c == '\\' || c == quoter))
1194         do_fputc ('\\', stream);
1195       do_fputc (c, stream);
1196     }
1197 }
1198
1199 /* Print the character C on STREAM as part of the contents of a
1200    literal string whose delimiter is QUOTER.  Note that these routines
1201    should only be call for printing things which are independent of
1202    the language of the program being debugged.  */
1203
1204 void
1205 fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
1206 {
1207   while (*str)
1208     printchar (*str++, fputc_filtered, stream, quoter);
1209 }
1210
1211 void
1212 fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
1213 {
1214   while (*str)
1215     printchar (*str++, fputc_unfiltered, stream, quoter);
1216 }
1217
1218 void
1219 fputstrn_filtered (const char *str, int n, int quoter,
1220                    struct ui_file *stream)
1221 {
1222   for (int i = 0; i < n; i++)
1223     printchar (str[i], fputc_filtered, stream, quoter);
1224 }
1225
1226 void
1227 fputstrn_unfiltered (const char *str, int n, int quoter,
1228                      do_fputc_ftype do_fputc, struct ui_file *stream)
1229 {
1230   for (int i = 0; i < n; i++)
1231     printchar (str[i], do_fputc, stream, quoter);
1232 }
1233 \f
1234
1235 /* Number of lines per page or UINT_MAX if paging is disabled.  */
1236 static unsigned int lines_per_page;
1237 static void
1238 show_lines_per_page (struct ui_file *file, int from_tty,
1239                      struct cmd_list_element *c, const char *value)
1240 {
1241   fprintf_filtered (file,
1242                     _("Number of lines gdb thinks are in a page is %s.\n"),
1243                     value);
1244 }
1245
1246 /* Number of chars per line or UINT_MAX if line folding is disabled.  */
1247 static unsigned int chars_per_line;
1248 static void
1249 show_chars_per_line (struct ui_file *file, int from_tty,
1250                      struct cmd_list_element *c, const char *value)
1251 {
1252   fprintf_filtered (file,
1253                     _("Number of characters gdb thinks "
1254                       "are in a line is %s.\n"),
1255                     value);
1256 }
1257
1258 /* Current count of lines printed on this page, chars on this line.  */
1259 static unsigned int lines_printed, chars_printed;
1260
1261 /* True if pagination is disabled for just one command.  */
1262
1263 static bool pagination_disabled_for_command;
1264
1265 /* Buffer and start column of buffered text, for doing smarter word-
1266    wrapping.  When someone calls wrap_here(), we start buffering output
1267    that comes through fputs_filtered().  If we see a newline, we just
1268    spit it out and forget about the wrap_here().  If we see another
1269    wrap_here(), we spit it out and remember the newer one.  If we see
1270    the end of the line, we spit out a newline, the indent, and then
1271    the buffered output.  */
1272
1273 static bool filter_initialized = false;
1274
1275 /* Contains characters which are waiting to be output (they have
1276    already been counted in chars_printed).  */
1277 static std::string wrap_buffer;
1278
1279 /* String to indent by if the wrap occurs.  Must not be NULL if wrap_column
1280    is non-zero.  */
1281 static const char *wrap_indent;
1282
1283 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1284    is not in effect.  */
1285 static int wrap_column;
1286
1287 /* The style applied at the time that wrap_here was called.  */
1288 static ui_file_style wrap_style;
1289 \f
1290
1291 /* Initialize the number of lines per page and chars per line.  */
1292
1293 void
1294 init_page_info (void)
1295 {
1296   if (batch_flag)
1297     {
1298       lines_per_page = UINT_MAX;
1299       chars_per_line = UINT_MAX;
1300     }
1301   else
1302 #if defined(TUI)
1303   if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1304 #endif
1305     {
1306       int rows, cols;
1307
1308 #if defined(__GO32__)
1309       rows = ScreenRows ();
1310       cols = ScreenCols ();
1311       lines_per_page = rows;
1312       chars_per_line = cols;
1313 #else
1314       /* Make sure Readline has initialized its terminal settings.  */
1315       rl_reset_terminal (NULL);
1316
1317       /* Get the screen size from Readline.  */
1318       rl_get_screen_size (&rows, &cols);
1319       lines_per_page = rows;
1320       chars_per_line = cols;
1321
1322       /* Readline should have fetched the termcap entry for us.
1323          Only try to use tgetnum function if rl_get_screen_size
1324          did not return a useful value. */
1325       if (((rows <= 0) && (tgetnum ((char *) "li") < 0))
1326         /* Also disable paging if inside Emacs.  $EMACS was used
1327            before Emacs v25.1, $INSIDE_EMACS is used since then.  */
1328           || getenv ("EMACS") || getenv ("INSIDE_EMACS"))
1329         {
1330           /* The number of lines per page is not mentioned in the terminal
1331              description or EMACS evironment variable is set.  This probably
1332              means that paging is not useful, so disable paging.  */
1333           lines_per_page = UINT_MAX;
1334         }
1335
1336       /* If the output is not a terminal, don't paginate it.  */
1337       if (!ui_file_isatty (gdb_stdout))
1338         lines_per_page = UINT_MAX;
1339 #endif
1340     }
1341
1342   /* We handle SIGWINCH ourselves.  */
1343   rl_catch_sigwinch = 0;
1344
1345   set_screen_size ();
1346   set_width ();
1347 }
1348
1349 /* Return nonzero if filtered printing is initialized.  */
1350 int
1351 filtered_printing_initialized (void)
1352 {
1353   return filter_initialized;
1354 }
1355
1356 set_batch_flag_and_restore_page_info::set_batch_flag_and_restore_page_info ()
1357   : m_save_lines_per_page (lines_per_page),
1358     m_save_chars_per_line (chars_per_line),
1359     m_save_batch_flag (batch_flag)
1360 {
1361   batch_flag = 1;
1362   init_page_info ();
1363 }
1364
1365 set_batch_flag_and_restore_page_info::~set_batch_flag_and_restore_page_info ()
1366 {
1367   batch_flag = m_save_batch_flag;
1368   chars_per_line = m_save_chars_per_line;
1369   lines_per_page = m_save_lines_per_page;
1370
1371   set_screen_size ();
1372   set_width ();
1373 }
1374
1375 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE.  */
1376
1377 static void
1378 set_screen_size (void)
1379 {
1380   int rows = lines_per_page;
1381   int cols = chars_per_line;
1382
1383   if (rows <= 0)
1384     rows = INT_MAX;
1385
1386   if (cols <= 0)
1387     cols = INT_MAX;
1388
1389   /* Update Readline's idea of the terminal size.  */
1390   rl_set_screen_size (rows, cols);
1391 }
1392
1393 /* Reinitialize WRAP_BUFFER.  */
1394
1395 static void
1396 set_width (void)
1397 {
1398   if (chars_per_line == 0)
1399     init_page_info ();
1400
1401   wrap_buffer.clear ();
1402   filter_initialized = true;
1403 }
1404
1405 static void
1406 set_width_command (const char *args, int from_tty, struct cmd_list_element *c)
1407 {
1408   set_screen_size ();
1409   set_width ();
1410 }
1411
1412 static void
1413 set_height_command (const char *args, int from_tty, struct cmd_list_element *c)
1414 {
1415   set_screen_size ();
1416 }
1417
1418 /* See utils.h.  */
1419
1420 void
1421 set_screen_width_and_height (int width, int height)
1422 {
1423   lines_per_page = height;
1424   chars_per_line = width;
1425
1426   set_screen_size ();
1427   set_width ();
1428 }
1429
1430 /* The currently applied style.  */
1431
1432 static ui_file_style applied_style;
1433
1434 /* Emit an ANSI style escape for STYLE.  If STREAM is nullptr, emit to
1435    the wrap buffer; otherwise emit to STREAM.  */
1436
1437 static void
1438 emit_style_escape (const ui_file_style &style,
1439                    struct ui_file *stream = nullptr)
1440 {
1441   applied_style = style;
1442
1443   if (stream == nullptr)
1444     wrap_buffer.append (style.to_ansi ());
1445   else
1446     fputs_unfiltered (style.to_ansi ().c_str (), stream);
1447 }
1448
1449 /* See utils.h.  */
1450
1451 bool
1452 can_emit_style_escape (struct ui_file *stream)
1453 {
1454   if (stream != gdb_stdout
1455       || !cli_styling
1456       || !ui_file_isatty (stream))
1457     return false;
1458   const char *term = getenv ("TERM");
1459   /* Windows doesn't by default define $TERM, but can support styles
1460      regardless.  */
1461 #ifndef _WIN32
1462   if (term == nullptr || !strcmp (term, "dumb"))
1463     return false;
1464 #else
1465   /* But if they do define $TERM, let us behave the same as on Posix
1466      platforms, for the benefit of programs which invoke GDB as their
1467      back-end.  */
1468   if (term && !strcmp (term, "dumb"))
1469     return false;
1470 #endif
1471   return true;
1472 }
1473
1474 /* Set the current output style.  This will affect future uses of the
1475    _filtered output functions.  */
1476
1477 static void
1478 set_output_style (struct ui_file *stream, const ui_file_style &style)
1479 {
1480   if (!can_emit_style_escape (stream))
1481     return;
1482
1483   /* Note that we don't pass STREAM here, because we want to emit to
1484      the wrap buffer, not directly to STREAM.  */
1485   emit_style_escape (style);
1486 }
1487
1488 /* See utils.h.  */
1489
1490 void
1491 reset_terminal_style (struct ui_file *stream)
1492 {
1493   if (can_emit_style_escape (stream))
1494     {
1495       /* Force the setting, regardless of what we think the setting
1496          might already be.  */
1497       applied_style = ui_file_style ();
1498       wrap_buffer.append (applied_style.to_ansi ());
1499     }
1500 }
1501
1502 /* Wait, so the user can read what's on the screen.  Prompt the user
1503    to continue by pressing RETURN.  'q' is also provided because
1504    telling users what to do in the prompt is more user-friendly than
1505    expecting them to think of Ctrl-C/SIGINT.  */
1506
1507 static void
1508 prompt_for_continue (void)
1509 {
1510   char cont_prompt[120];
1511   /* Used to add duration we waited for user to respond to
1512      prompt_for_continue_wait_time.  */
1513   using namespace std::chrono;
1514   steady_clock::time_point prompt_started = steady_clock::now ();
1515   bool disable_pagination = pagination_disabled_for_command;
1516
1517   /* Clear the current styling.  */
1518   if (can_emit_style_escape (gdb_stdout))
1519     emit_style_escape (ui_file_style (), gdb_stdout);
1520
1521   if (annotation_level > 1)
1522     printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));
1523
1524   strcpy (cont_prompt,
1525           "--Type <RET> for more, q to quit, "
1526           "c to continue without paging--");
1527   if (annotation_level > 1)
1528     strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1529
1530   /* We must do this *before* we call gdb_readline_wrapper, else it
1531      will eventually call us -- thinking that we're trying to print
1532      beyond the end of the screen.  */
1533   reinitialize_more_filter ();
1534
1535   scoped_input_handler prepare_input;
1536
1537   /* Call gdb_readline_wrapper, not readline, in order to keep an
1538      event loop running.  */
1539   gdb::unique_xmalloc_ptr<char> ignore (gdb_readline_wrapper (cont_prompt));
1540
1541   /* Add time spend in this routine to prompt_for_continue_wait_time.  */
1542   prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
1543
1544   if (annotation_level > 1)
1545     printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));
1546
1547   if (ignore != NULL)
1548     {
1549       char *p = ignore.get ();
1550
1551       while (*p == ' ' || *p == '\t')
1552         ++p;
1553       if (p[0] == 'q')
1554         /* Do not call quit here; there is no possibility of SIGINT.  */
1555         throw_quit ("Quit");
1556       if (p[0] == 'c')
1557         disable_pagination = true;
1558     }
1559
1560   /* Now we have to do this again, so that GDB will know that it doesn't
1561      need to save the ---Type <return>--- line at the top of the screen.  */
1562   reinitialize_more_filter ();
1563   pagination_disabled_for_command = disable_pagination;
1564
1565   /* Restore the current styling.  */
1566   if (can_emit_style_escape (gdb_stdout))
1567     emit_style_escape (applied_style);
1568
1569   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it.  */
1570 }
1571
1572 /* Initialize timer to keep track of how long we waited for the user.  */
1573
1574 void
1575 reset_prompt_for_continue_wait_time (void)
1576 {
1577   using namespace std::chrono;
1578
1579   prompt_for_continue_wait_time = steady_clock::duration::zero ();
1580 }
1581
1582 /* Fetch the cumulative time spent in prompt_for_continue.  */
1583
1584 std::chrono::steady_clock::duration
1585 get_prompt_for_continue_wait_time ()
1586 {
1587   return prompt_for_continue_wait_time;
1588 }
1589
1590 /* Reinitialize filter; ie. tell it to reset to original values.  */
1591
1592 void
1593 reinitialize_more_filter (void)
1594 {
1595   lines_printed = 0;
1596   chars_printed = 0;
1597   pagination_disabled_for_command = false;
1598 }
1599
1600 /* Flush the wrap buffer to STREAM, if necessary.  */
1601
1602 static void
1603 flush_wrap_buffer (struct ui_file *stream)
1604 {
1605   if (stream == gdb_stdout && !wrap_buffer.empty ())
1606     {
1607       fputs_unfiltered (wrap_buffer.c_str (), stream);
1608       wrap_buffer.clear ();
1609     }
1610 }
1611
1612 /* Indicate that if the next sequence of characters overflows the line,
1613    a newline should be inserted here rather than when it hits the end.
1614    If INDENT is non-null, it is a string to be printed to indent the
1615    wrapped part on the next line.  INDENT must remain accessible until
1616    the next call to wrap_here() or until a newline is printed through
1617    fputs_filtered().
1618
1619    If the line is already overfull, we immediately print a newline and
1620    the indentation, and disable further wrapping.
1621
1622    If we don't know the width of lines, but we know the page height,
1623    we must not wrap words, but should still keep track of newlines
1624    that were explicitly printed.
1625
1626    INDENT should not contain tabs, as that will mess up the char count
1627    on the next line.  FIXME.
1628
1629    This routine is guaranteed to force out any output which has been
1630    squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1631    used to force out output from the wrap_buffer.  */
1632
1633 void
1634 wrap_here (const char *indent)
1635 {
1636   /* This should have been allocated, but be paranoid anyway.  */
1637   if (!filter_initialized)
1638     internal_error (__FILE__, __LINE__,
1639                     _("failed internal consistency check"));
1640
1641   flush_wrap_buffer (gdb_stdout);
1642   if (chars_per_line == UINT_MAX)       /* No line overflow checking.  */
1643     {
1644       wrap_column = 0;
1645     }
1646   else if (chars_printed >= chars_per_line)
1647     {
1648       puts_filtered ("\n");
1649       if (indent != NULL)
1650         puts_filtered (indent);
1651       wrap_column = 0;
1652     }
1653   else
1654     {
1655       wrap_column = chars_printed;
1656       if (indent == NULL)
1657         wrap_indent = "";
1658       else
1659         wrap_indent = indent;
1660       wrap_style = applied_style;
1661     }
1662 }
1663
1664 /* Print input string to gdb_stdout, filtered, with wrap, 
1665    arranging strings in columns of n chars.  String can be
1666    right or left justified in the column.  Never prints 
1667    trailing spaces.  String should never be longer than
1668    width.  FIXME: this could be useful for the EXAMINE 
1669    command, which currently doesn't tabulate very well.  */
1670
1671 void
1672 puts_filtered_tabular (char *string, int width, int right)
1673 {
1674   int spaces = 0;
1675   int stringlen;
1676   char *spacebuf;
1677
1678   gdb_assert (chars_per_line > 0);
1679   if (chars_per_line == UINT_MAX)
1680     {
1681       fputs_filtered (string, gdb_stdout);
1682       fputs_filtered ("\n", gdb_stdout);
1683       return;
1684     }
1685
1686   if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
1687     fputs_filtered ("\n", gdb_stdout);
1688
1689   if (width >= chars_per_line)
1690     width = chars_per_line - 1;
1691
1692   stringlen = strlen (string);
1693
1694   if (chars_printed > 0)
1695     spaces = width - (chars_printed - 1) % width - 1;
1696   if (right)
1697     spaces += width - stringlen;
1698
1699   spacebuf = (char *) alloca (spaces + 1);
1700   spacebuf[spaces] = '\0';
1701   while (spaces--)
1702     spacebuf[spaces] = ' ';
1703
1704   fputs_filtered (spacebuf, gdb_stdout);
1705   fputs_filtered (string, gdb_stdout);
1706 }
1707
1708
1709 /* Ensure that whatever gets printed next, using the filtered output
1710    commands, starts at the beginning of the line.  I.e. if there is
1711    any pending output for the current line, flush it and start a new
1712    line.  Otherwise do nothing.  */
1713
1714 void
1715 begin_line (void)
1716 {
1717   if (chars_printed > 0)
1718     {
1719       puts_filtered ("\n");
1720     }
1721 }
1722
1723
1724 /* Like fputs but if FILTER is true, pause after every screenful.
1725
1726    Regardless of FILTER can wrap at points other than the final
1727    character of a line.
1728
1729    Unlike fputs, fputs_maybe_filtered does not return a value.
1730    It is OK for LINEBUFFER to be NULL, in which case just don't print
1731    anything.
1732
1733    Note that a longjmp to top level may occur in this routine (only if
1734    FILTER is true) (since prompt_for_continue may do so) so this
1735    routine should not be called when cleanups are not in place.  */
1736
1737 static void
1738 fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
1739                       int filter)
1740 {
1741   const char *lineptr;
1742
1743   if (linebuffer == 0)
1744     return;
1745
1746   /* Don't do any filtering if it is disabled.  */
1747   if (stream != gdb_stdout
1748       || !pagination_enabled
1749       || pagination_disabled_for_command
1750       || batch_flag
1751       || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
1752       || top_level_interpreter () == NULL
1753       || top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
1754     {
1755       flush_wrap_buffer (stream);
1756       fputs_unfiltered (linebuffer, stream);
1757       return;
1758     }
1759
1760   auto buffer_clearer
1761     = make_scope_exit ([&] ()
1762                        {
1763                          wrap_buffer.clear ();
1764                          wrap_column = 0;
1765                          wrap_indent = "";
1766                        });
1767
1768   /* Go through and output each character.  Show line extension
1769      when this is necessary; prompt user for new page when this is
1770      necessary.  */
1771
1772   lineptr = linebuffer;
1773   while (*lineptr)
1774     {
1775       /* Possible new page.  Note that PAGINATION_DISABLED_FOR_COMMAND
1776          might be set during this loop, so we must continue to check
1777          it here.  */
1778       if (filter && (lines_printed >= lines_per_page - 1)
1779           && !pagination_disabled_for_command)
1780         prompt_for_continue ();
1781
1782       while (*lineptr && *lineptr != '\n')
1783         {
1784           int skip_bytes;
1785
1786           /* Print a single line.  */
1787           if (*lineptr == '\t')
1788             {
1789               wrap_buffer.push_back ('\t');
1790               /* Shifting right by 3 produces the number of tab stops
1791                  we have already passed, and then adding one and
1792                  shifting left 3 advances to the next tab stop.  */
1793               chars_printed = ((chars_printed >> 3) + 1) << 3;
1794               lineptr++;
1795             }
1796           else if (*lineptr == '\033'
1797                    && skip_ansi_escape (lineptr, &skip_bytes))
1798             {
1799               wrap_buffer.append (lineptr, skip_bytes);
1800               /* Note that we don't consider this a character, so we
1801                  don't increment chars_printed here.  */
1802               lineptr += skip_bytes;
1803             }
1804           else
1805             {
1806               wrap_buffer.push_back (*lineptr);
1807               chars_printed++;
1808               lineptr++;
1809             }
1810
1811           if (chars_printed >= chars_per_line)
1812             {
1813               unsigned int save_chars = chars_printed;
1814
1815               chars_printed = 0;
1816               lines_printed++;
1817               if (wrap_column)
1818                 {
1819                   if (can_emit_style_escape (stream))
1820                     emit_style_escape (ui_file_style (), stream);
1821                   /* If we aren't actually wrapping, don't output
1822                      newline -- if chars_per_line is right, we
1823                      probably just overflowed anyway; if it's wrong,
1824                      let us keep going.  */
1825                   fputc_unfiltered ('\n', stream);
1826                 }
1827               else
1828                 flush_wrap_buffer (stream);
1829
1830               /* Possible new page.  Note that
1831                  PAGINATION_DISABLED_FOR_COMMAND might be set during
1832                  this loop, so we must continue to check it here.  */
1833               if (lines_printed >= lines_per_page - 1
1834                   && !pagination_disabled_for_command)
1835                 prompt_for_continue ();
1836
1837               /* Now output indentation and wrapped string.  */
1838               if (wrap_column)
1839                 {
1840                   fputs_unfiltered (wrap_indent, stream);
1841                   if (can_emit_style_escape (stream))
1842                     emit_style_escape (wrap_style, stream);
1843                   /* FIXME, this strlen is what prevents wrap_indent from
1844                      containing tabs.  However, if we recurse to print it
1845                      and count its chars, we risk trouble if wrap_indent is
1846                      longer than (the user settable) chars_per_line.
1847                      Note also that this can set chars_printed > chars_per_line
1848                      if we are printing a long string.  */
1849                   chars_printed = strlen (wrap_indent)
1850                     + (save_chars - wrap_column);
1851                   wrap_column = 0;      /* And disable fancy wrap */
1852                 }
1853             }
1854         }
1855
1856       if (*lineptr == '\n')
1857         {
1858           chars_printed = 0;
1859           wrap_here ((char *) 0);       /* Spit out chars, cancel
1860                                            further wraps.  */
1861           lines_printed++;
1862           fputc_unfiltered ('\n', stream);
1863           lineptr++;
1864         }
1865     }
1866
1867   buffer_clearer.release ();
1868 }
1869
1870 void
1871 fputs_filtered (const char *linebuffer, struct ui_file *stream)
1872 {
1873   fputs_maybe_filtered (linebuffer, stream, 1);
1874 }
1875
1876 /* See utils.h.  */
1877
1878 void
1879 fputs_styled (const char *linebuffer, const ui_file_style &style,
1880               struct ui_file *stream)
1881 {
1882   /* This just makes it so we emit somewhat fewer escape
1883      sequences.  */
1884   if (style.is_default ())
1885     fputs_maybe_filtered (linebuffer, stream, 1);
1886   else
1887     {
1888       set_output_style (stream, style);
1889       fputs_maybe_filtered (linebuffer, stream, 1);
1890       set_output_style (stream, ui_file_style ());
1891     }
1892 }
1893
1894 int
1895 putchar_unfiltered (int c)
1896 {
1897   char buf = c;
1898
1899   ui_file_write (gdb_stdout, &buf, 1);
1900   return c;
1901 }
1902
1903 /* Write character C to gdb_stdout using GDB's paging mechanism and return C.
1904    May return nonlocally.  */
1905
1906 int
1907 putchar_filtered (int c)
1908 {
1909   return fputc_filtered (c, gdb_stdout);
1910 }
1911
1912 int
1913 fputc_unfiltered (int c, struct ui_file *stream)
1914 {
1915   char buf = c;
1916
1917   ui_file_write (stream, &buf, 1);
1918   return c;
1919 }
1920
1921 int
1922 fputc_filtered (int c, struct ui_file *stream)
1923 {
1924   char buf[2];
1925
1926   buf[0] = c;
1927   buf[1] = 0;
1928   fputs_filtered (buf, stream);
1929   return c;
1930 }
1931
1932 /* puts_debug is like fputs_unfiltered, except it prints special
1933    characters in printable fashion.  */
1934
1935 void
1936 puts_debug (char *prefix, char *string, char *suffix)
1937 {
1938   int ch;
1939
1940   /* Print prefix and suffix after each line.  */
1941   static int new_line = 1;
1942   static int return_p = 0;
1943   static const char *prev_prefix = "";
1944   static const char *prev_suffix = "";
1945
1946   if (*string == '\n')
1947     return_p = 0;
1948
1949   /* If the prefix is changing, print the previous suffix, a new line,
1950      and the new prefix.  */
1951   if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
1952     {
1953       fputs_unfiltered (prev_suffix, gdb_stdlog);
1954       fputs_unfiltered ("\n", gdb_stdlog);
1955       fputs_unfiltered (prefix, gdb_stdlog);
1956     }
1957
1958   /* Print prefix if we printed a newline during the previous call.  */
1959   if (new_line)
1960     {
1961       new_line = 0;
1962       fputs_unfiltered (prefix, gdb_stdlog);
1963     }
1964
1965   prev_prefix = prefix;
1966   prev_suffix = suffix;
1967
1968   /* Output characters in a printable format.  */
1969   while ((ch = *string++) != '\0')
1970     {
1971       switch (ch)
1972         {
1973         default:
1974           if (isprint (ch))
1975             fputc_unfiltered (ch, gdb_stdlog);
1976
1977           else
1978             fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
1979           break;
1980
1981         case '\\':
1982           fputs_unfiltered ("\\\\", gdb_stdlog);
1983           break;
1984         case '\b':
1985           fputs_unfiltered ("\\b", gdb_stdlog);
1986           break;
1987         case '\f':
1988           fputs_unfiltered ("\\f", gdb_stdlog);
1989           break;
1990         case '\n':
1991           new_line = 1;
1992           fputs_unfiltered ("\\n", gdb_stdlog);
1993           break;
1994         case '\r':
1995           fputs_unfiltered ("\\r", gdb_stdlog);
1996           break;
1997         case '\t':
1998           fputs_unfiltered ("\\t", gdb_stdlog);
1999           break;
2000         case '\v':
2001           fputs_unfiltered ("\\v", gdb_stdlog);
2002           break;
2003         }
2004
2005       return_p = ch == '\r';
2006     }
2007
2008   /* Print suffix if we printed a newline.  */
2009   if (new_line)
2010     {
2011       fputs_unfiltered (suffix, gdb_stdlog);
2012       fputs_unfiltered ("\n", gdb_stdlog);
2013     }
2014 }
2015
2016
2017 /* Print a variable number of ARGS using format FORMAT.  If this
2018    information is going to put the amount written (since the last call
2019    to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2020    call prompt_for_continue to get the users permision to continue.
2021
2022    Unlike fprintf, this function does not return a value.
2023
2024    We implement three variants, vfprintf (takes a vararg list and stream),
2025    fprintf (takes a stream to write on), and printf (the usual).
2026
2027    Note also that a longjmp to top level may occur in this routine
2028    (since prompt_for_continue may do so) so this routine should not be
2029    called when cleanups are not in place.  */
2030
2031 static void
2032 vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
2033                          va_list args, int filter)
2034 {
2035   std::string linebuffer = string_vprintf (format, args);
2036   fputs_maybe_filtered (linebuffer.c_str (), stream, filter);
2037 }
2038
2039
2040 void
2041 vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
2042 {
2043   vfprintf_maybe_filtered (stream, format, args, 1);
2044 }
2045
2046 void
2047 vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
2048 {
2049   std::string linebuffer = string_vprintf (format, args);
2050   if (debug_timestamp && stream == gdb_stdlog)
2051     {
2052       using namespace std::chrono;
2053       int len, need_nl;
2054
2055       steady_clock::time_point now = steady_clock::now ();
2056       seconds s = duration_cast<seconds> (now.time_since_epoch ());
2057       microseconds us = duration_cast<microseconds> (now.time_since_epoch () - s);
2058
2059       len = linebuffer.size ();
2060       need_nl = (len > 0 && linebuffer[len - 1] != '\n');
2061
2062       std::string timestamp = string_printf ("%ld.%06ld %s%s",
2063                                              (long) s.count (),
2064                                              (long) us.count (),
2065                                              linebuffer.c_str (),
2066                                              need_nl ? "\n": "");
2067       fputs_unfiltered (timestamp.c_str (), stream);
2068     }
2069   else
2070     fputs_unfiltered (linebuffer.c_str (), stream);
2071 }
2072
2073 void
2074 vprintf_filtered (const char *format, va_list args)
2075 {
2076   vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2077 }
2078
2079 void
2080 vprintf_unfiltered (const char *format, va_list args)
2081 {
2082   vfprintf_unfiltered (gdb_stdout, format, args);
2083 }
2084
2085 void
2086 fprintf_filtered (struct ui_file *stream, const char *format, ...)
2087 {
2088   va_list args;
2089
2090   va_start (args, format);
2091   vfprintf_filtered (stream, format, args);
2092   va_end (args);
2093 }
2094
2095 void
2096 fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
2097 {
2098   va_list args;
2099
2100   va_start (args, format);
2101   vfprintf_unfiltered (stream, format, args);
2102   va_end (args);
2103 }
2104
2105 /* Like fprintf_filtered, but prints its result indented.
2106    Called as fprintfi_filtered (spaces, stream, format, ...);  */
2107
2108 void
2109 fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
2110                    ...)
2111 {
2112   va_list args;
2113
2114   va_start (args, format);
2115   print_spaces_filtered (spaces, stream);
2116
2117   vfprintf_filtered (stream, format, args);
2118   va_end (args);
2119 }
2120
2121 /* See utils.h.  */
2122
2123 void
2124 fprintf_styled (struct ui_file *stream, const ui_file_style &style,
2125                 const char *format, ...)
2126 {
2127   va_list args;
2128
2129   set_output_style (stream, style);
2130   va_start (args, format);
2131   vfprintf_filtered (stream, format, args);
2132   va_end (args);
2133   set_output_style (stream, ui_file_style ());
2134 }
2135
2136
2137 void
2138 printf_filtered (const char *format, ...)
2139 {
2140   va_list args;
2141
2142   va_start (args, format);
2143   vfprintf_filtered (gdb_stdout, format, args);
2144   va_end (args);
2145 }
2146
2147
2148 void
2149 printf_unfiltered (const char *format, ...)
2150 {
2151   va_list args;
2152
2153   va_start (args, format);
2154   vfprintf_unfiltered (gdb_stdout, format, args);
2155   va_end (args);
2156 }
2157
2158 /* Like printf_filtered, but prints it's result indented.
2159    Called as printfi_filtered (spaces, format, ...);  */
2160
2161 void
2162 printfi_filtered (int spaces, const char *format, ...)
2163 {
2164   va_list args;
2165
2166   va_start (args, format);
2167   print_spaces_filtered (spaces, gdb_stdout);
2168   vfprintf_filtered (gdb_stdout, format, args);
2169   va_end (args);
2170 }
2171
2172 /* Easy -- but watch out!
2173
2174    This routine is *not* a replacement for puts()!  puts() appends a newline.
2175    This one doesn't, and had better not!  */
2176
2177 void
2178 puts_filtered (const char *string)
2179 {
2180   fputs_filtered (string, gdb_stdout);
2181 }
2182
2183 void
2184 puts_unfiltered (const char *string)
2185 {
2186   fputs_unfiltered (string, gdb_stdout);
2187 }
2188
2189 /* Return a pointer to N spaces and a null.  The pointer is good
2190    until the next call to here.  */
2191 char *
2192 n_spaces (int n)
2193 {
2194   char *t;
2195   static char *spaces = 0;
2196   static int max_spaces = -1;
2197
2198   if (n > max_spaces)
2199     {
2200       if (spaces)
2201         xfree (spaces);
2202       spaces = (char *) xmalloc (n + 1);
2203       for (t = spaces + n; t != spaces;)
2204         *--t = ' ';
2205       spaces[n] = '\0';
2206       max_spaces = n;
2207     }
2208
2209   return spaces + max_spaces - n;
2210 }
2211
2212 /* Print N spaces.  */
2213 void
2214 print_spaces_filtered (int n, struct ui_file *stream)
2215 {
2216   fputs_filtered (n_spaces (n), stream);
2217 }
2218 \f
2219 /* C++/ObjC demangler stuff.  */
2220
2221 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2222    LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2223    If the name is not mangled, or the language for the name is unknown, or
2224    demangling is off, the name is printed in its "raw" form.  */
2225
2226 void
2227 fprintf_symbol_filtered (struct ui_file *stream, const char *name,
2228                          enum language lang, int arg_mode)
2229 {
2230   char *demangled;
2231
2232   if (name != NULL)
2233     {
2234       /* If user wants to see raw output, no problem.  */
2235       if (!demangle)
2236         {
2237           fputs_filtered (name, stream);
2238         }
2239       else
2240         {
2241           demangled = language_demangle (language_def (lang), name, arg_mode);
2242           fputs_filtered (demangled ? demangled : name, stream);
2243           if (demangled != NULL)
2244             {
2245               xfree (demangled);
2246             }
2247         }
2248     }
2249 }
2250
2251 /* True if CH is a character that can be part of a symbol name.  I.e.,
2252    either a number, a letter, or a '_'.  */
2253
2254 static bool
2255 valid_identifier_name_char (int ch)
2256 {
2257   return (isalnum (ch) || ch == '_');
2258 }
2259
2260 /* Skip to end of token, or to END, whatever comes first.  Input is
2261    assumed to be a C++ operator name.  */
2262
2263 static const char *
2264 cp_skip_operator_token (const char *token, const char *end)
2265 {
2266   const char *p = token;
2267   while (p != end && !isspace (*p) && *p != '(')
2268     {
2269       if (valid_identifier_name_char (*p))
2270         {
2271           while (p != end && valid_identifier_name_char (*p))
2272             p++;
2273           return p;
2274         }
2275       else
2276         {
2277           /* Note, ordered such that among ops that share a prefix,
2278              longer comes first.  This is so that the loop below can
2279              bail on first match.  */
2280           static const char *ops[] =
2281             {
2282               "[",
2283               "]",
2284               "~",
2285               ",",
2286               "-=", "--", "->", "-",
2287               "+=", "++", "+",
2288               "*=", "*",
2289               "/=", "/",
2290               "%=", "%",
2291               "|=", "||", "|",
2292               "&=", "&&", "&",
2293               "^=", "^",
2294               "!=", "!",
2295               "<<=", "<=", "<<", "<",
2296               ">>=", ">=", ">>", ">",
2297               "==", "=",
2298             };
2299
2300           for (const char *op : ops)
2301             {
2302               size_t oplen = strlen (op);
2303               size_t lencmp = std::min<size_t> (oplen, end - p);
2304
2305               if (strncmp (p, op, lencmp) == 0)
2306                 return p + lencmp;
2307             }
2308           /* Some unidentified character.  Return it.  */
2309           return p + 1;
2310         }
2311     }
2312
2313   return p;
2314 }
2315
2316 /* Advance STRING1/STRING2 past whitespace.  */
2317
2318 static void
2319 skip_ws (const char *&string1, const char *&string2, const char *end_str2)
2320 {
2321   while (isspace (*string1))
2322     string1++;
2323   while (string2 < end_str2 && isspace (*string2))
2324     string2++;
2325 }
2326
2327 /* True if STRING points at the start of a C++ operator name.  START
2328    is the start of the string that STRING points to, hence when
2329    reading backwards, we must not read any character before START.  */
2330
2331 static bool
2332 cp_is_operator (const char *string, const char *start)
2333 {
2334   return ((string == start
2335            || !valid_identifier_name_char (string[-1]))
2336           && strncmp (string, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
2337           && !valid_identifier_name_char (string[CP_OPERATOR_LEN]));
2338 }
2339
2340 /* If *NAME points at an ABI tag, skip it and return true.  Otherwise
2341    leave *NAME unmodified and return false.  (see GCC's abi_tag
2342    attribute), such names are demangled as e.g.,
2343    "function[abi:cxx11]()".  */
2344
2345 static bool
2346 skip_abi_tag (const char **name)
2347 {
2348   const char *p = *name;
2349
2350   if (startswith (p, "[abi:"))
2351     {
2352       p += 5;
2353
2354       while (valid_identifier_name_char (*p))
2355         p++;
2356
2357       if (*p == ']')
2358         {
2359           p++;
2360           *name = p;
2361           return true;
2362         }
2363     }
2364   return false;
2365 }
2366
2367 /* See utils.h.  */
2368
2369 int
2370 strncmp_iw_with_mode (const char *string1, const char *string2,
2371                       size_t string2_len, strncmp_iw_mode mode,
2372                       enum language language,
2373                       completion_match_for_lcd *match_for_lcd)
2374 {
2375   const char *string1_start = string1;
2376   const char *end_str2 = string2 + string2_len;
2377   bool skip_spaces = true;
2378   bool have_colon_op = (language == language_cplus
2379                         || language == language_rust
2380                         || language == language_fortran);
2381
2382   while (1)
2383     {
2384       if (skip_spaces
2385           || ((isspace (*string1) && !valid_identifier_name_char (*string2))
2386               || (isspace (*string2) && !valid_identifier_name_char (*string1))))
2387         {
2388           skip_ws (string1, string2, end_str2);
2389           skip_spaces = false;
2390         }
2391
2392       /* Skip [abi:cxx11] tags in the symbol name if the lookup name
2393          doesn't include them.  E.g.:
2394
2395          string1: function[abi:cxx1](int)
2396          string2: function
2397
2398          string1: function[abi:cxx1](int)
2399          string2: function(int)
2400
2401          string1: Struct[abi:cxx1]::function()
2402          string2: Struct::function()
2403
2404          string1: function(Struct[abi:cxx1], int)
2405          string2: function(Struct, int)
2406       */
2407       if (string2 == end_str2
2408           || (*string2 != '[' && !valid_identifier_name_char (*string2)))
2409         {
2410           const char *abi_start = string1;
2411
2412           /* There can be more than one tag.  */
2413           while (*string1 == '[' && skip_abi_tag (&string1))
2414             ;
2415
2416           if (match_for_lcd != NULL && abi_start != string1)
2417             match_for_lcd->mark_ignored_range (abi_start, string1);
2418
2419           while (isspace (*string1))
2420             string1++;
2421         }
2422
2423       if (*string1 == '\0' || string2 == end_str2)
2424         break;
2425
2426       /* Handle the :: operator.  */
2427       if (have_colon_op && string1[0] == ':' && string1[1] == ':')
2428         {
2429           if (*string2 != ':')
2430             return 1;
2431
2432           string1++;
2433           string2++;
2434
2435           if (string2 == end_str2)
2436             break;
2437
2438           if (*string2 != ':')
2439             return 1;
2440
2441           string1++;
2442           string2++;
2443
2444           while (isspace (*string1))
2445             string1++;
2446           while (string2 < end_str2 && isspace (*string2))
2447             string2++;
2448           continue;
2449         }
2450
2451       /* Handle C++ user-defined operators.  */
2452       else if (language == language_cplus
2453                && *string1 == 'o')
2454         {
2455           if (cp_is_operator (string1, string1_start))
2456             {
2457               /* An operator name in STRING1.  Check STRING2.  */
2458               size_t cmplen
2459                 = std::min<size_t> (CP_OPERATOR_LEN, end_str2 - string2);
2460               if (strncmp (string1, string2, cmplen) != 0)
2461                 return 1;
2462
2463               string1 += cmplen;
2464               string2 += cmplen;
2465
2466               if (string2 != end_str2)
2467                 {
2468                   /* Check for "operatorX" in STRING2.  */
2469                   if (valid_identifier_name_char (*string2))
2470                     return 1;
2471
2472                   skip_ws (string1, string2, end_str2);
2473                 }
2474
2475               /* Handle operator().  */
2476               if (*string1 == '(')
2477                 {
2478                   if (string2 == end_str2)
2479                     {
2480                       if (mode == strncmp_iw_mode::NORMAL)
2481                         return 0;
2482                       else
2483                         {
2484                           /* Don't break for the regular return at the
2485                              bottom, because "operator" should not
2486                              match "operator()", since this open
2487                              parentheses is not the parameter list
2488                              start.  */
2489                           return *string1 != '\0';
2490                         }
2491                     }
2492
2493                   if (*string1 != *string2)
2494                     return 1;
2495
2496                   string1++;
2497                   string2++;
2498                 }
2499
2500               while (1)
2501                 {
2502                   skip_ws (string1, string2, end_str2);
2503
2504                   /* Skip to end of token, or to END, whatever comes
2505                      first.  */
2506                   const char *end_str1 = string1 + strlen (string1);
2507                   const char *p1 = cp_skip_operator_token (string1, end_str1);
2508                   const char *p2 = cp_skip_operator_token (string2, end_str2);
2509
2510                   cmplen = std::min (p1 - string1, p2 - string2);
2511                   if (p2 == end_str2)
2512                     {
2513                       if (strncmp (string1, string2, cmplen) != 0)
2514                         return 1;
2515                     }
2516                   else
2517                     {
2518                       if (p1 - string1 != p2 - string2)
2519                         return 1;
2520                       if (strncmp (string1, string2, cmplen) != 0)
2521                         return 1;
2522                     }
2523
2524                   string1 += cmplen;
2525                   string2 += cmplen;
2526
2527                   if (*string1 == '\0' || string2 == end_str2)
2528                     break;
2529                   if (*string1 == '(' || *string2 == '(')
2530                     break;
2531                 }
2532
2533               continue;
2534             }
2535         }
2536
2537       if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2538         break;
2539       if (case_sensitivity == case_sensitive_off
2540           && (tolower ((unsigned char) *string1)
2541               != tolower ((unsigned char) *string2)))
2542         break;
2543
2544       /* If we see any non-whitespace, non-identifier-name character
2545          (any of "()<>*&" etc.), then skip spaces the next time
2546          around.  */
2547       if (!isspace (*string1) && !valid_identifier_name_char (*string1))
2548         skip_spaces = true;
2549
2550       string1++;
2551       string2++;
2552     }
2553
2554   if (string2 == end_str2)
2555     {
2556       if (mode == strncmp_iw_mode::NORMAL)
2557         {
2558           /* Strip abi tag markers from the matched symbol name.
2559              Usually the ABI marker will be found on function name
2560              (automatically added because the function returns an
2561              object marked with an ABI tag).  However, it's also
2562              possible to see a marker in one of the function
2563              parameters, for example.
2564
2565              string2 (lookup name):
2566                func
2567              symbol name:
2568                function(some_struct[abi:cxx11], int)
2569
2570              and for completion LCD computation we want to say that
2571              the match was for:
2572                function(some_struct, int)
2573           */
2574           if (match_for_lcd != NULL)
2575             {
2576               while ((string1 = strstr (string1, "[abi:")) != NULL)
2577                 {
2578                   const char *abi_start = string1;
2579
2580                   /* There can be more than one tag.  */
2581                   while (skip_abi_tag (&string1) && *string1 == '[')
2582                     ;
2583
2584                   if (abi_start != string1)
2585                     match_for_lcd->mark_ignored_range (abi_start, string1);
2586                 }
2587             }
2588
2589           return 0;
2590         }
2591       else
2592         return (*string1 != '\0' && *string1 != '(');
2593     }
2594   else
2595     return 1;
2596 }
2597
2598 /* See utils.h.  */
2599
2600 int
2601 strncmp_iw (const char *string1, const char *string2, size_t string2_len)
2602 {
2603   return strncmp_iw_with_mode (string1, string2, string2_len,
2604                                strncmp_iw_mode::NORMAL, language_minimal);
2605 }
2606
2607 /* See utils.h.  */
2608
2609 int
2610 strcmp_iw (const char *string1, const char *string2)
2611 {
2612   return strncmp_iw_with_mode (string1, string2, strlen (string2),
2613                                strncmp_iw_mode::MATCH_PARAMS, language_minimal);
2614 }
2615
2616 /* This is like strcmp except that it ignores whitespace and treats
2617    '(' as the first non-NULL character in terms of ordering.  Like
2618    strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
2619    STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
2620    according to that ordering.
2621
2622    If a list is sorted according to this function and if you want to
2623    find names in the list that match some fixed NAME according to
2624    strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
2625    where this function would put NAME.
2626
2627    This function must be neutral to the CASE_SENSITIVITY setting as the user
2628    may choose it during later lookup.  Therefore this function always sorts
2629    primarily case-insensitively and secondarily case-sensitively.
2630
2631    Here are some examples of why using strcmp to sort is a bad idea:
2632
2633    Whitespace example:
2634
2635    Say your partial symtab contains: "foo<char *>", "goo".  Then, if
2636    we try to do a search for "foo<char*>", strcmp will locate this
2637    after "foo<char *>" and before "goo".  Then lookup_partial_symbol
2638    will start looking at strings beginning with "goo", and will never
2639    see the correct match of "foo<char *>".
2640
2641    Parenthesis example:
2642
2643    In practice, this is less like to be an issue, but I'll give it a
2644    shot.  Let's assume that '$' is a legitimate character to occur in
2645    symbols.  (Which may well even be the case on some systems.)  Then
2646    say that the partial symbol table contains "foo$" and "foo(int)".
2647    strcmp will put them in this order, since '$' < '('.  Now, if the
2648    user searches for "foo", then strcmp will sort "foo" before "foo$".
2649    Then lookup_partial_symbol will notice that strcmp_iw("foo$",
2650    "foo") is false, so it won't proceed to the actual match of
2651    "foo(int)" with "foo".  */
2652
2653 int
2654 strcmp_iw_ordered (const char *string1, const char *string2)
2655 {
2656   const char *saved_string1 = string1, *saved_string2 = string2;
2657   enum case_sensitivity case_pass = case_sensitive_off;
2658
2659   for (;;)
2660     {
2661       /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
2662          Provide stub characters if we are already at the end of one of the
2663          strings.  */
2664       char c1 = 'X', c2 = 'X';
2665
2666       while (*string1 != '\0' && *string2 != '\0')
2667         {
2668           while (isspace (*string1))
2669             string1++;
2670           while (isspace (*string2))
2671             string2++;
2672
2673           switch (case_pass)
2674           {
2675             case case_sensitive_off:
2676               c1 = tolower ((unsigned char) *string1);
2677               c2 = tolower ((unsigned char) *string2);
2678               break;
2679             case case_sensitive_on:
2680               c1 = *string1;
2681               c2 = *string2;
2682               break;
2683           }
2684           if (c1 != c2)
2685             break;
2686
2687           if (*string1 != '\0')
2688             {
2689               string1++;
2690               string2++;
2691             }
2692         }
2693
2694       switch (*string1)
2695         {
2696           /* Characters are non-equal unless they're both '\0'; we want to
2697              make sure we get the comparison right according to our
2698              comparison in the cases where one of them is '\0' or '('.  */
2699         case '\0':
2700           if (*string2 == '\0')
2701             break;
2702           else
2703             return -1;
2704         case '(':
2705           if (*string2 == '\0')
2706             return 1;
2707           else
2708             return -1;
2709         default:
2710           if (*string2 == '\0' || *string2 == '(')
2711             return 1;
2712           else if (c1 > c2)
2713             return 1;
2714           else if (c1 < c2)
2715             return -1;
2716           /* PASSTHRU */
2717         }
2718
2719       if (case_pass == case_sensitive_on)
2720         return 0;
2721       
2722       /* Otherwise the strings were equal in case insensitive way, make
2723          a more fine grained comparison in a case sensitive way.  */
2724
2725       case_pass = case_sensitive_on;
2726       string1 = saved_string1;
2727       string2 = saved_string2;
2728     }
2729 }
2730
2731 /* See utils.h.  */
2732
2733 bool
2734 streq (const char *lhs, const char *rhs)
2735 {
2736   return !strcmp (lhs, rhs);
2737 }
2738
2739 /* See utils.h.  */
2740
2741 int
2742 streq_hash (const void *lhs, const void *rhs)
2743 {
2744   return streq ((const char *) lhs, (const char *) rhs);
2745 }
2746
2747 \f
2748
2749 /*
2750    ** subset_compare()
2751    **    Answer whether string_to_compare is a full or partial match to
2752    **    template_string.  The partial match must be in sequence starting
2753    **    at index 0.
2754  */
2755 int
2756 subset_compare (const char *string_to_compare, const char *template_string)
2757 {
2758   int match;
2759
2760   if (template_string != (char *) NULL && string_to_compare != (char *) NULL
2761       && strlen (string_to_compare) <= strlen (template_string))
2762     match =
2763       (startswith (template_string, string_to_compare));
2764   else
2765     match = 0;
2766   return match;
2767 }
2768
2769 static void
2770 show_debug_timestamp (struct ui_file *file, int from_tty,
2771                       struct cmd_list_element *c, const char *value)
2772 {
2773   fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"),
2774                     value);
2775 }
2776 \f
2777
2778 void
2779 initialize_utils (void)
2780 {
2781   add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
2782 Set number of characters where GDB should wrap lines of its output."), _("\
2783 Show number of characters where GDB should wrap lines of its output."), _("\
2784 This affects where GDB wraps its output to fit the screen width.\n\
2785 Setting this to \"unlimited\" or zero prevents GDB from wrapping its output."),
2786                             set_width_command,
2787                             show_chars_per_line,
2788                             &setlist, &showlist);
2789
2790   add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
2791 Set number of lines in a page for GDB output pagination."), _("\
2792 Show number of lines in a page for GDB output pagination."), _("\
2793 This affects the number of lines after which GDB will pause\n\
2794 its output and ask you whether to continue.\n\
2795 Setting this to \"unlimited\" or zero causes GDB never pause during output."),
2796                             set_height_command,
2797                             show_lines_per_page,
2798                             &setlist, &showlist);
2799
2800   add_setshow_boolean_cmd ("pagination", class_support,
2801                            &pagination_enabled, _("\
2802 Set state of GDB output pagination."), _("\
2803 Show state of GDB output pagination."), _("\
2804 When pagination is ON, GDB pauses at end of each screenful of\n\
2805 its output and asks you whether to continue.\n\
2806 Turning pagination off is an alternative to \"set height unlimited\"."),
2807                            NULL,
2808                            show_pagination_enabled,
2809                            &setlist, &showlist);
2810
2811   add_setshow_boolean_cmd ("sevenbit-strings", class_support,
2812                            &sevenbit_strings, _("\
2813 Set printing of 8-bit characters in strings as \\nnn."), _("\
2814 Show printing of 8-bit characters in strings as \\nnn."), NULL,
2815                            NULL,
2816                            show_sevenbit_strings,
2817                            &setprintlist, &showprintlist);
2818
2819   add_setshow_boolean_cmd ("timestamp", class_maintenance,
2820                             &debug_timestamp, _("\
2821 Set timestamping of debugging messages."), _("\
2822 Show timestamping of debugging messages."), _("\
2823 When set, debugging messages will be marked with seconds and microseconds."),
2824                            NULL,
2825                            show_debug_timestamp,
2826                            &setdebuglist, &showdebuglist);
2827 }
2828
2829 /* See utils.h.  */
2830
2831 CORE_ADDR
2832 address_significant (gdbarch *gdbarch, CORE_ADDR addr)
2833 {
2834   /* Clear insignificant bits of a target address and sign extend resulting
2835      address, avoiding shifts larger or equal than the width of a CORE_ADDR.
2836      The local variable ADDR_BIT stops the compiler reporting a shift overflow
2837      when it won't occur.  Skip updating of target address if current target
2838      has not set gdbarch significant_addr_bit.  */
2839   int addr_bit = gdbarch_significant_addr_bit (gdbarch);
2840
2841   if (addr_bit && (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT)))
2842     {
2843       CORE_ADDR sign = (CORE_ADDR) 1 << (addr_bit - 1);
2844       addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
2845       addr = (addr ^ sign) - sign;
2846     }
2847
2848   return addr;
2849 }
2850
2851 const char *
2852 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
2853 {
2854   /* Truncate address to the size of a target address, avoiding shifts
2855      larger or equal than the width of a CORE_ADDR.  The local
2856      variable ADDR_BIT stops the compiler reporting a shift overflow
2857      when it won't occur.  */
2858   /* NOTE: This assumes that the significant address information is
2859      kept in the least significant bits of ADDR - the upper bits were
2860      either zero or sign extended.  Should gdbarch_address_to_pointer or
2861      some ADDRESS_TO_PRINTABLE() be used to do the conversion?  */
2862
2863   int addr_bit = gdbarch_addr_bit (gdbarch);
2864
2865   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2866     addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
2867   return hex_string (addr);
2868 }
2869
2870 /* This function is described in "defs.h".  */
2871
2872 const char *
2873 print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
2874 {
2875   int addr_bit = gdbarch_addr_bit (gdbarch);
2876
2877   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2878     address &= ((CORE_ADDR) 1 << addr_bit) - 1;
2879
2880   /* FIXME: cagney/2002-05-03: Need local_address_string() function
2881      that returns the language localized string formatted to a width
2882      based on gdbarch_addr_bit.  */
2883   if (addr_bit <= 32)
2884     return hex_string_custom (address, 8);
2885   else
2886     return hex_string_custom (address, 16);
2887 }
2888
2889 /* Callback hash_f for htab_create_alloc or htab_create_alloc_ex.  */
2890
2891 hashval_t
2892 core_addr_hash (const void *ap)
2893 {
2894   const CORE_ADDR *addrp = (const CORE_ADDR *) ap;
2895
2896   return *addrp;
2897 }
2898
2899 /* Callback eq_f for htab_create_alloc or htab_create_alloc_ex.  */
2900
2901 int
2902 core_addr_eq (const void *ap, const void *bp)
2903 {
2904   const CORE_ADDR *addr_ap = (const CORE_ADDR *) ap;
2905   const CORE_ADDR *addr_bp = (const CORE_ADDR *) bp;
2906
2907   return *addr_ap == *addr_bp;
2908 }
2909
2910 /* Convert a string back into a CORE_ADDR.  */
2911 CORE_ADDR
2912 string_to_core_addr (const char *my_string)
2913 {
2914   CORE_ADDR addr = 0;
2915
2916   if (my_string[0] == '0' && tolower (my_string[1]) == 'x')
2917     {
2918       /* Assume that it is in hex.  */
2919       int i;
2920
2921       for (i = 2; my_string[i] != '\0'; i++)
2922         {
2923           if (isdigit (my_string[i]))
2924             addr = (my_string[i] - '0') + (addr * 16);
2925           else if (isxdigit (my_string[i]))
2926             addr = (tolower (my_string[i]) - 'a' + 0xa) + (addr * 16);
2927           else
2928             error (_("invalid hex \"%s\""), my_string);
2929         }
2930     }
2931   else
2932     {
2933       /* Assume that it is in decimal.  */
2934       int i;
2935
2936       for (i = 0; my_string[i] != '\0'; i++)
2937         {
2938           if (isdigit (my_string[i]))
2939             addr = (my_string[i] - '0') + (addr * 10);
2940           else
2941             error (_("invalid decimal \"%s\""), my_string);
2942         }
2943     }
2944
2945   return addr;
2946 }
2947
2948 #if GDB_SELF_TEST
2949
2950 static void
2951 gdb_realpath_check_trailer (const char *input, const char *trailer)
2952 {
2953   gdb::unique_xmalloc_ptr<char> result = gdb_realpath (input);
2954
2955   size_t len = strlen (result.get ());
2956   size_t trail_len = strlen (trailer);
2957
2958   SELF_CHECK (len >= trail_len
2959               && strcmp (result.get () + len - trail_len, trailer) == 0);
2960 }
2961
2962 static void
2963 gdb_realpath_tests ()
2964 {
2965   /* A file which contains a directory prefix.  */
2966   gdb_realpath_check_trailer ("./xfullpath.exp", "/xfullpath.exp");
2967   /* A file which contains a directory prefix.  */
2968   gdb_realpath_check_trailer ("../../defs.h", "/defs.h");
2969   /* A one-character filename.  */
2970   gdb_realpath_check_trailer ("./a", "/a");
2971   /* A file in the root directory.  */
2972   gdb_realpath_check_trailer ("/root_file_which_should_exist",
2973                               "/root_file_which_should_exist");
2974   /* A file which does not have a directory prefix.  */
2975   gdb_realpath_check_trailer ("xfullpath.exp", "xfullpath.exp");
2976   /* A one-char filename without any directory prefix.  */
2977   gdb_realpath_check_trailer ("a", "a");
2978   /* An empty filename.  */
2979   gdb_realpath_check_trailer ("", "");
2980 }
2981
2982 #endif /* GDB_SELF_TEST */
2983
2984 /* Allocation function for the libiberty hash table which uses an
2985    obstack.  The obstack is passed as DATA.  */
2986
2987 void *
2988 hashtab_obstack_allocate (void *data, size_t size, size_t count)
2989 {
2990   size_t total = size * count;
2991   void *ptr = obstack_alloc ((struct obstack *) data, total);
2992
2993   memset (ptr, 0, total);
2994   return ptr;
2995 }
2996
2997 /* Trivial deallocation function for the libiberty splay tree and hash
2998    table - don't deallocate anything.  Rely on later deletion of the
2999    obstack.  DATA will be the obstack, although it is not needed
3000    here.  */
3001
3002 void
3003 dummy_obstack_deallocate (void *object, void *data)
3004 {
3005   return;
3006 }
3007
3008 /* Simple, portable version of dirname that does not modify its
3009    argument.  */
3010
3011 std::string
3012 ldirname (const char *filename)
3013 {
3014   std::string dirname;
3015   const char *base = lbasename (filename);
3016
3017   while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3018     --base;
3019
3020   if (base == filename)
3021     return dirname;
3022
3023   dirname = std::string (filename, base - filename);
3024
3025   /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3026      create "d:./bar" later instead of the (different) "d:/bar".  */
3027   if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3028       && !IS_DIR_SEPARATOR (filename[0]))
3029     dirname[base++ - filename] = '.';
3030
3031   return dirname;
3032 }
3033
3034 /* See utils.h.  */
3035
3036 void
3037 gdb_argv::reset (const char *s)
3038 {
3039   char **argv = buildargv (s);
3040
3041   if (s != NULL && argv == NULL)
3042     malloc_failure (0);
3043
3044   freeargv (m_argv);
3045   m_argv = argv;
3046 }
3047
3048 int
3049 compare_positive_ints (const void *ap, const void *bp)
3050 {
3051   /* Because we know we're comparing two ints which are positive,
3052      there's no danger of overflow here.  */
3053   return * (int *) ap - * (int *) bp;
3054 }
3055
3056 #define AMBIGUOUS_MESS1 ".\nMatching formats:"
3057 #define AMBIGUOUS_MESS2 \
3058   ".\nUse \"set gnutarget format-name\" to specify the format."
3059
3060 std::string
3061 gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
3062 {
3063   char **p;
3064
3065   /* Check if errmsg just need simple return.  */
3066   if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
3067     return bfd_errmsg (error_tag);
3068
3069   std::string ret (bfd_errmsg (error_tag));
3070   ret += AMBIGUOUS_MESS1;
3071
3072   for (p = matching; *p; p++)
3073     {
3074       ret += " ";
3075       ret += *p;
3076     }
3077   ret += AMBIGUOUS_MESS2;
3078
3079   xfree (matching);
3080
3081   return ret;
3082 }
3083
3084 /* Return ARGS parsed as a valid pid, or throw an error.  */
3085
3086 int
3087 parse_pid_to_attach (const char *args)
3088 {
3089   unsigned long pid;
3090   char *dummy;
3091
3092   if (!args)
3093     error_no_arg (_("process-id to attach"));
3094
3095   dummy = (char *) args;
3096   pid = strtoul (args, &dummy, 0);
3097   /* Some targets don't set errno on errors, grrr!  */
3098   if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3099     error (_("Illegal process-id: %s."), args);
3100
3101   return pid;
3102 }
3103
3104 /* Substitute all occurences of string FROM by string TO in *STRINGP.  *STRINGP
3105    must come from xrealloc-compatible allocator and it may be updated.  FROM
3106    needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
3107    located at the start or end of *STRINGP.  */
3108
3109 void
3110 substitute_path_component (char **stringp, const char *from, const char *to)
3111 {
3112   char *string = *stringp, *s;
3113   const size_t from_len = strlen (from);
3114   const size_t to_len = strlen (to);
3115
3116   for (s = string;;)
3117     {
3118       s = strstr (s, from);
3119       if (s == NULL)
3120         break;
3121
3122       if ((s == string || IS_DIR_SEPARATOR (s[-1])
3123            || s[-1] == DIRNAME_SEPARATOR)
3124           && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
3125               || s[from_len] == DIRNAME_SEPARATOR))
3126         {
3127           char *string_new;
3128
3129           string_new
3130             = (char *) xrealloc (string, (strlen (string) + to_len + 1));
3131
3132           /* Relocate the current S pointer.  */
3133           s = s - string + string_new;
3134           string = string_new;
3135
3136           /* Replace from by to.  */
3137           memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
3138           memcpy (s, to, to_len);
3139
3140           s += to_len;
3141         }
3142       else
3143         s++;
3144     }
3145
3146   *stringp = string;
3147 }
3148
3149 #ifdef HAVE_WAITPID
3150
3151 #ifdef SIGALRM
3152
3153 /* SIGALRM handler for waitpid_with_timeout.  */
3154
3155 static void
3156 sigalrm_handler (int signo)
3157 {
3158   /* Nothing to do.  */
3159 }
3160
3161 #endif
3162
3163 /* Wrapper to wait for child PID to die with TIMEOUT.
3164    TIMEOUT is the time to stop waiting in seconds.
3165    If TIMEOUT is zero, pass WNOHANG to waitpid.
3166    Returns PID if it was successfully waited for, otherwise -1.
3167
3168    Timeouts are currently implemented with alarm and SIGALRM.
3169    If the host does not support them, this waits "forever".
3170    It would be odd though for a host to have waitpid and not SIGALRM.  */
3171
3172 pid_t
3173 wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3174 {
3175   pid_t waitpid_result;
3176
3177   gdb_assert (pid > 0);
3178   gdb_assert (timeout >= 0);
3179
3180   if (timeout > 0)
3181     {
3182 #ifdef SIGALRM
3183 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3184       struct sigaction sa, old_sa;
3185
3186       sa.sa_handler = sigalrm_handler;
3187       sigemptyset (&sa.sa_mask);
3188       sa.sa_flags = 0;
3189       sigaction (SIGALRM, &sa, &old_sa);
3190 #else
3191       sighandler_t ofunc;
3192
3193       ofunc = signal (SIGALRM, sigalrm_handler);
3194 #endif
3195
3196       alarm (timeout);
3197 #endif
3198
3199       waitpid_result = waitpid (pid, status, 0);
3200
3201 #ifdef SIGALRM
3202       alarm (0);
3203 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3204       sigaction (SIGALRM, &old_sa, NULL);
3205 #else
3206       signal (SIGALRM, ofunc);
3207 #endif
3208 #endif
3209     }
3210   else
3211     waitpid_result = waitpid (pid, status, WNOHANG);
3212
3213   if (waitpid_result == pid)
3214     return pid;
3215   else
3216     return -1;
3217 }
3218
3219 #endif /* HAVE_WAITPID */
3220
3221 /* Provide fnmatch compatible function for FNM_FILE_NAME matching of host files.
3222    Both FNM_FILE_NAME and FNM_NOESCAPE must be set in FLAGS.
3223
3224    It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3225    HAVE_CASE_INSENSITIVE_FILE_SYSTEM.  */
3226
3227 int
3228 gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3229 {
3230   gdb_assert ((flags & FNM_FILE_NAME) != 0);
3231
3232   /* It is unclear how '\' escaping vs. directory separator should coexist.  */
3233   gdb_assert ((flags & FNM_NOESCAPE) != 0);
3234
3235 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3236   {
3237     char *pattern_slash, *string_slash;
3238
3239     /* Replace '\' by '/' in both strings.  */
3240
3241     pattern_slash = (char *) alloca (strlen (pattern) + 1);
3242     strcpy (pattern_slash, pattern);
3243     pattern = pattern_slash;
3244     for (; *pattern_slash != 0; pattern_slash++)
3245       if (IS_DIR_SEPARATOR (*pattern_slash))
3246         *pattern_slash = '/';
3247
3248     string_slash = (char *) alloca (strlen (string) + 1);
3249     strcpy (string_slash, string);
3250     string = string_slash;
3251     for (; *string_slash != 0; string_slash++)
3252       if (IS_DIR_SEPARATOR (*string_slash))
3253         *string_slash = '/';
3254   }
3255 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3256
3257 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3258   flags |= FNM_CASEFOLD;
3259 #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3260
3261   return fnmatch (pattern, string, flags);
3262 }
3263
3264 /* Return the number of path elements in PATH.
3265    / = 1
3266    /foo = 2
3267    /foo/ = 2
3268    foo/bar = 2
3269    foo/ = 1  */
3270
3271 int
3272 count_path_elements (const char *path)
3273 {
3274   int count = 0;
3275   const char *p = path;
3276
3277   if (HAS_DRIVE_SPEC (p))
3278     {
3279       p = STRIP_DRIVE_SPEC (p);
3280       ++count;
3281     }
3282
3283   while (*p != '\0')
3284     {
3285       if (IS_DIR_SEPARATOR (*p))
3286         ++count;
3287       ++p;
3288     }
3289
3290   /* Backup one if last character is /, unless it's the only one.  */
3291   if (p > path + 1 && IS_DIR_SEPARATOR (p[-1]))
3292     --count;
3293
3294   /* Add one for the file name, if present.  */
3295   if (p > path && !IS_DIR_SEPARATOR (p[-1]))
3296     ++count;
3297
3298   return count;
3299 }
3300
3301 /* Remove N leading path elements from PATH.
3302    N must be non-negative.
3303    If PATH has more than N path elements then return NULL.
3304    If PATH has exactly N path elements then return "".
3305    See count_path_elements for a description of how we do the counting.  */
3306
3307 const char *
3308 strip_leading_path_elements (const char *path, int n)
3309 {
3310   int i = 0;
3311   const char *p = path;
3312
3313   gdb_assert (n >= 0);
3314
3315   if (n == 0)
3316     return p;
3317
3318   if (HAS_DRIVE_SPEC (p))
3319     {
3320       p = STRIP_DRIVE_SPEC (p);
3321       ++i;
3322     }
3323
3324   while (i < n)
3325     {
3326       while (*p != '\0' && !IS_DIR_SEPARATOR (*p))
3327         ++p;
3328       if (*p == '\0')
3329         {
3330           if (i + 1 == n)
3331             return "";
3332           return NULL;
3333         }
3334       ++p;
3335       ++i;
3336     }
3337
3338   return p;
3339 }
3340
3341 /* See utils.h.  */
3342
3343 void
3344 copy_bitwise (gdb_byte *dest, ULONGEST dest_offset,
3345               const gdb_byte *source, ULONGEST source_offset,
3346               ULONGEST nbits, int bits_big_endian)
3347 {
3348   unsigned int buf, avail;
3349
3350   if (nbits == 0)
3351     return;
3352
3353   if (bits_big_endian)
3354     {
3355       /* Start from the end, then work backwards.  */
3356       dest_offset += nbits - 1;
3357       dest += dest_offset / 8;
3358       dest_offset = 7 - dest_offset % 8;
3359       source_offset += nbits - 1;
3360       source += source_offset / 8;
3361       source_offset = 7 - source_offset % 8;
3362     }
3363   else
3364     {
3365       dest += dest_offset / 8;
3366       dest_offset %= 8;
3367       source += source_offset / 8;
3368       source_offset %= 8;
3369     }
3370
3371   /* Fill BUF with DEST_OFFSET bits from the destination and 8 -
3372      SOURCE_OFFSET bits from the source.  */
3373   buf = *(bits_big_endian ? source-- : source++) >> source_offset;
3374   buf <<= dest_offset;
3375   buf |= *dest & ((1 << dest_offset) - 1);
3376
3377   /* NBITS: bits yet to be written; AVAIL: BUF's fill level.  */
3378   nbits += dest_offset;
3379   avail = dest_offset + 8 - source_offset;
3380
3381   /* Flush 8 bits from BUF, if appropriate.  */
3382   if (nbits >= 8 && avail >= 8)
3383     {
3384       *(bits_big_endian ? dest-- : dest++) = buf;
3385       buf >>= 8;
3386       avail -= 8;
3387       nbits -= 8;
3388     }
3389
3390   /* Copy the middle part.  */
3391   if (nbits >= 8)
3392     {
3393       size_t len = nbits / 8;
3394
3395       /* Use a faster method for byte-aligned copies.  */
3396       if (avail == 0)
3397         {
3398           if (bits_big_endian)
3399             {
3400               dest -= len;
3401               source -= len;
3402               memcpy (dest + 1, source + 1, len);
3403             }
3404           else
3405             {
3406               memcpy (dest, source, len);
3407               dest += len;
3408               source += len;
3409             }
3410         }
3411       else
3412         {
3413           while (len--)
3414             {
3415               buf |= *(bits_big_endian ? source-- : source++) << avail;
3416               *(bits_big_endian ? dest-- : dest++) = buf;
3417               buf >>= 8;
3418             }
3419         }
3420       nbits %= 8;
3421     }
3422
3423   /* Write the last byte.  */
3424   if (nbits)
3425     {
3426       if (avail < nbits)
3427         buf |= *source << avail;
3428
3429       buf &= (1 << nbits) - 1;
3430       *dest = (*dest & (~0 << nbits)) | buf;
3431     }
3432 }
3433
3434 void
3435 _initialize_utils (void)
3436 {
3437   add_internal_problem_command (&internal_error_problem);
3438   add_internal_problem_command (&internal_warning_problem);
3439   add_internal_problem_command (&demangler_warning_problem);
3440
3441 #if GDB_SELF_TEST
3442   selftests::register_test ("gdb_realpath", gdb_realpath_tests);
3443 #endif
3444 }