Fix test for sections with different VMA<->LMA relationships so that it only applies...
[binutils-gdb.git] / gdb / utils.c
blob6a77f6be713a62e1464937570f488e10bf10fe9d
1 /* General utility routines for GDB, the GNU debugger.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include <ctype.h>
21 #include "gdbsupport/gdb_wait.h"
22 #include "event-top.h"
23 #include "gdbthread.h"
24 #include "fnmatch.h"
25 #include "gdb_bfd.h"
26 #ifdef HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
28 #endif /* HAVE_SYS_RESOURCE_H */
30 #ifdef TUI
31 /* For tui_get_command_dimension and tui_disable. */
32 #include "tui/tui.h"
33 #endif
35 #ifdef __GO32__
36 #include <pc.h>
37 #endif
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 "gdbsupport/gdb_obstack.h"
52 #include "gdbcore.h"
53 #include "top.h"
54 #include "ui.h"
55 #include "main.h"
56 #include "solist.h"
58 #include "inferior.h"
60 #include "gdb_curses.h"
62 #include "readline/readline.h"
64 #include <chrono>
66 #include "interps.h"
67 #include "gdbsupport/gdb_regex.h"
68 #include "gdbsupport/job-control.h"
69 #include "gdbsupport/selftest.h"
70 #include <optional>
71 #include "cp-support.h"
72 #include <algorithm>
73 #include "gdbsupport/pathstuff.h"
74 #include "cli/cli-style.h"
75 #include "gdbsupport/scope-exit.h"
76 #include "gdbarch.h"
77 #include "cli-out.h"
78 #include "gdbsupport/gdb-safe-ctype.h"
79 #include "bt-utils.h"
80 #include "gdbsupport/buildargv.h"
81 #include "pager.h"
82 #include "run-on-main-thread.h"
84 void (*deprecated_error_begin_hook) (void);
86 /* Prototypes for local functions */
88 static void set_screen_size (void);
89 static void set_width (void);
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. */
97 static std::chrono::steady_clock::duration prompt_for_continue_wait_time;
99 /* A flag indicating whether to timestamp debugging messages. */
101 bool debug_timestamp = false;
103 /* True means that strings with character values >0x7F should be printed
104 as octal escapes. False means just print the value (e.g. it's an
105 international character, and the terminal or window can cope.) */
107 bool sevenbit_strings = false;
108 static void
109 show_sevenbit_strings (struct ui_file *file, int from_tty,
110 struct cmd_list_element *c, const char *value)
112 gdb_printf (file, _("Printing of 8-bit characters "
113 "in strings as \\nnn is %s.\n"),
114 value);
117 /* String to be printed before warning messages, if any. */
119 const char *warning_pre_print = "\nwarning: ";
121 bool pagination_enabled = true;
122 static void
123 show_pagination_enabled (struct ui_file *file, int from_tty,
124 struct cmd_list_element *c, const char *value)
126 gdb_printf (file, _("State of pagination is %s.\n"), value);
130 /* Warning hook pointer. This has to be 'static' to avoid link
131 problems with thread-locals on AIX. */
133 static thread_local warning_hook_handler warning_hook;
135 /* See utils.h. */
137 warning_hook_handler
138 get_warning_hook_handler ()
140 return warning_hook;
143 /* See utils.h. */
145 scoped_restore_warning_hook::scoped_restore_warning_hook
146 (warning_hook_handler new_handler)
147 : m_save (warning_hook)
149 warning_hook = new_handler;
152 scoped_restore_warning_hook::~scoped_restore_warning_hook ()
154 warning_hook = m_save;
157 /* Print a warning message. The first argument STRING is the warning
158 message, used as an fprintf format string, the second is the
159 va_list of arguments for that string. A warning is unfiltered (not
160 paginated) so that the user does not need to page through each
161 screen full of warnings when there are lots of them. */
163 void
164 vwarning (const char *string, va_list args)
166 if (warning_hook != nullptr)
167 warning_hook->warn (string, args);
168 else
170 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
171 if (target_supports_terminal_ours ())
173 term_state.emplace ();
174 target_terminal::ours_for_output ();
176 if (warning_pre_print)
177 gdb_puts (warning_pre_print, gdb_stderr);
178 gdb_vprintf (gdb_stderr, string, args);
179 gdb_printf (gdb_stderr, "\n");
183 /* Print an error message and return to command level.
184 The first argument STRING is the error message, used as a fprintf string,
185 and the remaining args are passed as arguments to it. */
187 void
188 verror (const char *string, va_list args)
190 throw_verror (GENERIC_ERROR, string, args);
193 /* Emit a message and abort. */
195 static void ATTRIBUTE_NORETURN
196 abort_with_message (const char *msg)
198 if (current_ui == NULL)
199 fputs (msg, stderr);
200 else
201 gdb_puts (msg, gdb_stderr);
203 abort (); /* ARI: abort */
206 /* Dump core trying to increase the core soft limit to hard limit first. */
208 void
209 dump_core (void)
211 #ifdef HAVE_SETRLIMIT
212 struct rlimit rlim = { (rlim_t) RLIM_INFINITY, (rlim_t) RLIM_INFINITY };
214 setrlimit (RLIMIT_CORE, &rlim);
215 #endif /* HAVE_SETRLIMIT */
217 /* Ensure that the SIGABRT we're about to raise will immediately cause
218 GDB to exit and dump core, we don't want to trigger GDB's printing of
219 a backtrace to the console here. */
220 signal (SIGABRT, SIG_DFL);
222 abort (); /* ARI: abort */
225 /* Check whether GDB will be able to dump core using the dump_core
226 function. Returns zero if GDB cannot or should not dump core.
227 If LIMIT_KIND is LIMIT_CUR the user's soft limit will be respected.
228 If LIMIT_KIND is LIMIT_MAX only the hard limit will be respected. */
231 can_dump_core (enum resource_limit_kind limit_kind)
233 #ifdef HAVE_GETRLIMIT
234 struct rlimit rlim;
236 /* Be quiet and assume we can dump if an error is returned. */
237 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
238 return 1;
240 switch (limit_kind)
242 case LIMIT_CUR:
243 if (rlim.rlim_cur == 0)
244 return 0;
245 [[fallthrough]];
247 case LIMIT_MAX:
248 if (rlim.rlim_max == 0)
249 return 0;
251 #endif /* HAVE_GETRLIMIT */
253 return 1;
256 /* Print a warning that we cannot dump core. */
258 void
259 warn_cant_dump_core (const char *reason)
261 gdb_printf (gdb_stderr,
262 _("%s\nUnable to dump core, use `ulimit -c"
263 " unlimited' before executing GDB next time.\n"),
264 reason);
267 /* Check whether GDB will be able to dump core using the dump_core
268 function, and print a warning if we cannot. */
270 static int
271 can_dump_core_warn (enum resource_limit_kind limit_kind,
272 const char *reason)
274 int core_dump_allowed = can_dump_core (limit_kind);
276 if (!core_dump_allowed)
277 warn_cant_dump_core (reason);
279 return core_dump_allowed;
282 /* Allow the user to configure the debugger behavior with respect to
283 what to do when an internal problem is detected. */
285 const char internal_problem_ask[] = "ask";
286 const char internal_problem_yes[] = "yes";
287 const char internal_problem_no[] = "no";
288 static const char *const internal_problem_modes[] =
290 internal_problem_ask,
291 internal_problem_yes,
292 internal_problem_no,
293 NULL
296 /* Data structure used to control how the internal_vproblem function
297 should behave. An instance of this structure is created for each
298 problem type that GDB supports. */
300 struct internal_problem
302 /* The name of this problem type. This must not contain white space as
303 this string is used to build command names. */
304 const char *name;
306 /* When this is true then a user command is created (based on NAME) that
307 allows the SHOULD_QUIT field to be modified, otherwise, SHOULD_QUIT
308 can't be changed from its default value by the user. */
309 bool user_settable_should_quit;
311 /* Reference a value from internal_problem_modes to indicate if GDB
312 should quit when it hits a problem of this type. */
313 const char *should_quit;
315 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_DUMP_CORE. */
316 bool user_settable_should_dump_core;
318 /* Like SHOULD_QUIT, but whether GDB should dump core. */
319 const char *should_dump_core;
321 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_PRINT_BACKTRACE. */
322 bool user_settable_should_print_backtrace;
324 /* When this is true GDB will print a backtrace when a problem of this
325 type is encountered. */
326 bool should_print_backtrace;
329 /* Return true if the readline callbacks have been initialized for UI.
330 This is always true once GDB is fully initialized, but during the early
331 startup phase this is initially false. */
333 static bool
334 readline_initialized (struct ui *ui)
336 return ui->call_readline != nullptr;
339 /* Report a problem, internal to GDB, to the user. Once the problem
340 has been reported, and assuming GDB didn't quit, the caller can
341 either allow execution to resume or throw an error. */
343 static void ATTRIBUTE_PRINTF (4, 0)
344 internal_vproblem (struct internal_problem *problem,
345 const char *file, int line, const char *fmt, va_list ap)
347 static int dejavu;
348 int quit_p;
349 int dump_core_p;
350 std::string reason;
352 /* Don't allow infinite error/warning recursion. */
354 static const char msg[] = "Recursive internal problem.\n";
356 switch (dejavu)
358 case 0:
359 dejavu = 1;
360 break;
361 case 1:
362 dejavu = 2;
363 abort_with_message (msg);
364 default:
365 dejavu = 3;
366 /* Newer GLIBC versions put the warn_unused_result attribute
367 on write, but this is one of those rare cases where
368 ignoring the return value is correct. Casting to (void)
369 does not fix this problem. This is the solution suggested
370 at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509. */
371 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
372 abort (); /* ARI: abort */
373 exit (1);
377 #ifdef TUI
378 tui_disable ();
379 #endif
381 /* Create a string containing the full error/warning message. Need
382 to call query with this full string, as otherwize the reason
383 (error/warning) and question become separated. Format using a
384 style similar to a compiler error message. Include extra detail
385 so that the user knows that they are living on the edge. */
387 std::string msg = string_vprintf (fmt, ap);
388 reason = string_printf ("%s:%d: %s: %s\n"
389 "A problem internal to GDB has been detected,\n"
390 "further debugging may prove unreliable.",
391 file, line, problem->name, msg.c_str ());
394 /* Fall back to abort_with_message if gdb_stderr is not set up. */
395 if (current_ui == NULL)
397 fputs (reason.c_str (), stderr);
398 abort_with_message ("\n");
401 /* Try to get the message out and at the start of a new line. */
402 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
403 if (target_supports_terminal_ours ())
405 term_state.emplace ();
406 target_terminal::ours_for_output ();
408 if (filtered_printing_initialized ())
409 begin_line ();
411 /* Emit the message unless query will emit it below. */
412 if (problem->should_quit != internal_problem_ask
413 || !confirm
414 || !filtered_printing_initialized ()
415 || !readline_initialized (current_ui)
416 || problem->should_print_backtrace)
417 gdb_printf (gdb_stderr, "%s\n", reason.c_str ());
419 if (problem->should_print_backtrace)
420 gdb_internal_backtrace ();
422 if (problem->should_quit == internal_problem_ask)
424 /* Default (yes/batch case) is to quit GDB. When in batch mode
425 this lessens the likelihood of GDB going into an infinite
426 loop. */
427 if (!confirm || !filtered_printing_initialized ()
428 || !readline_initialized (current_ui))
429 quit_p = 1;
430 else
431 quit_p = query (_("%s\nQuit this debugging session? "),
432 reason.c_str ());
434 else if (problem->should_quit == internal_problem_yes)
435 quit_p = 1;
436 else if (problem->should_quit == internal_problem_no)
437 quit_p = 0;
438 else
439 internal_error (_("bad switch"));
441 gdb_puts (_("\nThis is a bug, please report it."), gdb_stderr);
442 if (REPORT_BUGS_TO[0])
443 gdb_printf (gdb_stderr, _(" For instructions, see:\n%ps."),
444 styled_string (file_name_style.style (),
445 REPORT_BUGS_TO));
446 gdb_puts ("\n\n", gdb_stderr);
448 if (problem->should_dump_core == internal_problem_ask)
450 if (!can_dump_core_warn (LIMIT_MAX, reason.c_str ()))
451 dump_core_p = 0;
452 else if (!filtered_printing_initialized ()
453 || !readline_initialized (current_ui))
454 dump_core_p = 1;
455 else
457 /* Default (yes/batch case) is to dump core. This leaves a GDB
458 `dropping' so that it is easier to see that something went
459 wrong in GDB. */
460 dump_core_p = query (_("%s\nCreate a core file of GDB? "),
461 reason.c_str ());
464 else if (problem->should_dump_core == internal_problem_yes)
465 dump_core_p = can_dump_core_warn (LIMIT_MAX, reason.c_str ());
466 else if (problem->should_dump_core == internal_problem_no)
467 dump_core_p = 0;
468 else
469 internal_error (_("bad switch"));
471 if (quit_p)
473 if (dump_core_p)
474 dump_core ();
475 else
476 exit (1);
478 else
480 if (dump_core_p)
482 #ifdef HAVE_WORKING_FORK
483 if (fork () == 0)
484 dump_core ();
485 #endif
489 dejavu = 0;
492 static struct internal_problem internal_error_problem = {
493 "internal-error", true, internal_problem_ask, true, internal_problem_ask,
494 true, GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON
497 void
498 internal_verror (const char *file, int line, const char *fmt, va_list ap)
500 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
501 throw_quit (_("Command aborted."));
504 static struct internal_problem internal_warning_problem = {
505 "internal-warning", true, internal_problem_ask, true, internal_problem_ask,
506 true, false
509 void
510 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
512 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
515 static struct internal_problem demangler_warning_problem = {
516 "demangler-warning", true, internal_problem_ask, false, internal_problem_no,
517 false, false
520 void
521 demangler_vwarning (const char *file, int line, const char *fmt, va_list ap)
523 internal_vproblem (&demangler_warning_problem, file, line, fmt, ap);
526 void
527 demangler_warning (const char *file, int line, const char *string, ...)
529 va_list ap;
531 va_start (ap, string);
532 demangler_vwarning (file, line, string, ap);
533 va_end (ap);
536 /* When GDB reports an internal problem (error or warning) it gives
537 the user the opportunity to quit GDB and/or create a core file of
538 the current debug session. This function registers a few commands
539 that make it possible to specify that GDB should always or never
540 quit or create a core file, without asking. The commands look
541 like:
543 maint set PROBLEM-NAME quit ask|yes|no
544 maint show PROBLEM-NAME quit
545 maint set PROBLEM-NAME corefile ask|yes|no
546 maint show PROBLEM-NAME corefile
548 Where PROBLEM-NAME is currently "internal-error" or
549 "internal-warning". */
551 static void
552 add_internal_problem_command (struct internal_problem *problem)
554 struct cmd_list_element **set_cmd_list;
555 struct cmd_list_element **show_cmd_list;
557 set_cmd_list = XNEW (struct cmd_list_element *);
558 show_cmd_list = XNEW (struct cmd_list_element *);
559 *set_cmd_list = NULL;
560 *show_cmd_list = NULL;
562 /* The add_basic_prefix_cmd and add_show_prefix_cmd functions take
563 ownership of the string passed in, which is why we don't need to free
564 set_doc and show_doc in this function. */
565 const char *set_doc
566 = xstrprintf (_("Configure what GDB does when %s is detected."),
567 problem->name).release ();
568 const char *show_doc
569 = xstrprintf (_("Show what GDB does when %s is detected."),
570 problem->name).release ();
572 add_setshow_prefix_cmd (problem->name, class_maintenance,
573 set_doc, show_doc, set_cmd_list, show_cmd_list,
574 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
576 if (problem->user_settable_should_quit)
578 std::string set_quit_doc
579 = string_printf (_("Set whether GDB should quit when an %s is "
580 "detected."), problem->name);
581 std::string show_quit_doc
582 = string_printf (_("Show whether GDB will quit when an %s is "
583 "detected."), problem->name);
584 add_setshow_enum_cmd ("quit", class_maintenance,
585 internal_problem_modes,
586 &problem->should_quit,
587 set_quit_doc.c_str (),
588 show_quit_doc.c_str (),
589 NULL, /* help_doc */
590 NULL, /* setfunc */
591 NULL, /* showfunc */
592 set_cmd_list,
593 show_cmd_list);
596 if (problem->user_settable_should_dump_core)
598 std::string set_core_doc
599 = string_printf (_("Set whether GDB should create a core file of "
600 "GDB when %s is detected."), problem->name);
601 std::string show_core_doc
602 = string_printf (_("Show whether GDB will create a core file of "
603 "GDB when %s is detected."), problem->name);
604 add_setshow_enum_cmd ("corefile", class_maintenance,
605 internal_problem_modes,
606 &problem->should_dump_core,
607 set_core_doc.c_str (),
608 show_core_doc.c_str (),
609 NULL, /* help_doc */
610 NULL, /* setfunc */
611 NULL, /* showfunc */
612 set_cmd_list,
613 show_cmd_list);
616 if (problem->user_settable_should_print_backtrace)
618 std::string set_bt_doc
619 = string_printf (_("Set whether GDB should print a backtrace of "
620 "GDB when %s is detected."), problem->name);
621 std::string show_bt_doc
622 = string_printf (_("Show whether GDB will print a backtrace of "
623 "GDB when %s is detected."), problem->name);
624 add_setshow_boolean_cmd ("backtrace", class_maintenance,
625 &problem->should_print_backtrace,
626 set_bt_doc.c_str (),
627 show_bt_doc.c_str (),
628 NULL, /* help_doc */
629 gdb_internal_backtrace_set_cmd,
630 NULL, /* showfunc */
631 set_cmd_list,
632 show_cmd_list);
636 /* Same as perror_with_name except that it prints a warning instead
637 of throwing an error. */
639 void
640 perror_warning_with_name (const char *string)
642 std::string combined = perror_string (string);
643 warning (_("%s"), combined.c_str ());
646 /* See utils.h. */
648 void
649 warning_filename_and_errno (const char *filename, int saved_errno)
651 warning (_("%ps: %s"), styled_string (file_name_style.style (), filename),
652 safe_strerror (saved_errno));
655 /* Control C eventually causes this to be called, at a convenient time. */
657 void
658 quit (void)
660 if (sync_quit_force_run)
662 sync_quit_force_run = false;
663 throw_forced_quit ("SIGTERM");
666 #ifdef __MSDOS__
667 /* No steenking SIGINT will ever be coming our way when the
668 program is resumed. Don't lie. */
669 throw_quit ("Quit");
670 #else
671 if (job_control
672 /* If there is no terminal switching for this target, then we can't
673 possibly get screwed by the lack of job control. */
674 || !target_supports_terminal_ours ())
675 throw_quit ("Quit");
676 else
677 throw_quit ("Quit (expect signal SIGINT when the program is resumed)");
678 #endif
681 /* See defs.h. */
683 void
684 maybe_quit (void)
686 if (!is_main_thread ())
687 return;
689 if (sync_quit_force_run)
690 quit ();
692 quit_handler ();
696 /* Called when a memory allocation fails, with the number of bytes of
697 memory requested in SIZE. */
699 void
700 malloc_failure (long size)
702 if (size > 0)
704 internal_error (_("virtual memory exhausted: can't allocate %ld bytes."),
705 size);
707 else
709 internal_error (_("virtual memory exhausted."));
713 /* See common/errors.h. */
715 void
716 flush_streams ()
718 gdb_stdout->flush ();
719 gdb_stderr->flush ();
722 /* My replacement for the read system call.
723 Used like `read' but keeps going if `read' returns too soon. */
726 myread (int desc, char *addr, int len)
728 int val;
729 int orglen = len;
731 while (len > 0)
733 val = read (desc, addr, len);
734 if (val < 0)
735 return val;
736 if (val == 0)
737 return orglen - len;
738 len -= val;
739 addr += val;
741 return orglen;
746 /* An RAII class that sets up to handle input and then tears down
747 during destruction. */
749 class scoped_input_handler
751 public:
753 scoped_input_handler ()
754 : m_quit_handler (&quit_handler, default_quit_handler),
755 m_ui (NULL)
757 target_terminal::ours ();
758 current_ui->register_file_handler ();
759 if (current_ui->prompt_state == PROMPT_BLOCKED)
760 m_ui = current_ui;
763 ~scoped_input_handler ()
765 if (m_ui != NULL)
766 m_ui->unregister_file_handler ();
769 DISABLE_COPY_AND_ASSIGN (scoped_input_handler);
771 private:
773 /* Save and restore the terminal state. */
774 target_terminal::scoped_restore_terminal_state m_term_state;
776 /* Save and restore the quit handler. */
777 scoped_restore_tmpl<quit_handler_ftype *> m_quit_handler;
779 /* The saved UI, if non-NULL. */
780 struct ui *m_ui;
785 /* This function supports the query, nquery, and yquery functions.
786 Ask user a y-or-n question and return 0 if answer is no, 1 if
787 answer is yes, or default the answer to the specified default
788 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
789 default answer, or '\0' for no default.
790 CTLSTR is the control string and should end in "? ". It should
791 not say how to answer, because we do that.
792 ARGS are the arguments passed along with the CTLSTR argument to
793 printf. */
795 static int ATTRIBUTE_PRINTF (1, 0)
796 defaulted_query (const char *ctlstr, const char defchar, va_list args)
798 int retval;
799 int def_value;
800 char def_answer, not_def_answer;
801 const char *y_string, *n_string;
803 /* Set up according to which answer is the default. */
804 if (defchar == '\0')
806 def_value = 1;
807 def_answer = 'Y';
808 not_def_answer = 'N';
809 y_string = "y";
810 n_string = "n";
812 else if (defchar == 'y')
814 def_value = 1;
815 def_answer = 'Y';
816 not_def_answer = 'N';
817 y_string = "[y]";
818 n_string = "n";
820 else
822 def_value = 0;
823 def_answer = 'N';
824 not_def_answer = 'Y';
825 y_string = "y";
826 n_string = "[n]";
829 /* Automatically answer the default value if the user did not want
830 prompts or the command was issued with the server prefix. */
831 if (!confirm || server_command)
832 return def_value;
834 /* If input isn't coming from the user directly, just say what
835 question we're asking, and then answer the default automatically. This
836 way, important error messages don't get lost when talking to GDB
837 over a pipe. */
838 if (current_ui->instream != current_ui->stdin_stream
839 || !current_ui->input_interactive_p ()
840 /* Restrict queries to the main UI. */
841 || current_ui != main_ui)
843 target_terminal::scoped_restore_terminal_state term_state;
844 target_terminal::ours_for_output ();
845 gdb_stdout->wrap_here (0);
846 gdb_vprintf (gdb_stdout, ctlstr, args);
848 gdb_printf (_("(%s or %s) [answered %c; "
849 "input not from terminal]\n"),
850 y_string, n_string, def_answer);
852 return def_value;
855 if (deprecated_query_hook)
857 target_terminal::scoped_restore_terminal_state term_state;
858 return deprecated_query_hook (ctlstr, args);
861 /* Format the question outside of the loop, to avoid reusing args. */
862 std::string question = string_vprintf (ctlstr, args);
863 std::string prompt
864 = string_printf (_("%s%s(%s or %s) %s"),
865 annotation_level > 1 ? "\n\032\032pre-query\n" : "",
866 question.c_str (), y_string, n_string,
867 annotation_level > 1 ? "\n\032\032query\n" : "");
869 /* Used to add duration we waited for user to respond to
870 prompt_for_continue_wait_time. */
871 using namespace std::chrono;
872 steady_clock::time_point prompt_started = steady_clock::now ();
874 scoped_input_handler prepare_input;
876 while (1)
878 char *response, answer;
880 gdb_flush (gdb_stdout);
881 response = gdb_readline_wrapper (prompt.c_str ());
883 if (response == NULL) /* C-d */
885 gdb_printf ("EOF [assumed %c]\n", def_answer);
886 retval = def_value;
887 break;
890 answer = response[0];
891 xfree (response);
893 if (answer >= 'a')
894 answer -= 040;
895 /* Check answer. For the non-default, the user must specify
896 the non-default explicitly. */
897 if (answer == not_def_answer)
899 retval = !def_value;
900 break;
902 /* Otherwise, if a default was specified, the user may either
903 specify the required input or have it default by entering
904 nothing. */
905 if (answer == def_answer
906 || (defchar != '\0' && answer == '\0'))
908 retval = def_value;
909 break;
911 /* Invalid entries are not defaulted and require another selection. */
912 gdb_printf (_("Please answer %s or %s.\n"),
913 y_string, n_string);
916 /* Add time spend in this routine to prompt_for_continue_wait_time. */
917 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
919 if (annotation_level > 1)
920 gdb_printf (("\n\032\032post-query\n"));
921 return retval;
925 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
926 answer is yes, or 0 if answer is defaulted.
927 Takes three args which are given to printf to print the question.
928 The first, a control string, should end in "? ".
929 It should not say how to answer, because we do that. */
932 nquery (const char *ctlstr, ...)
934 va_list args;
935 int ret;
937 va_start (args, ctlstr);
938 ret = defaulted_query (ctlstr, 'n', args);
939 va_end (args);
940 return ret;
943 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
944 answer is yes, or 1 if answer is defaulted.
945 Takes three args which are given to printf to print the question.
946 The first, a control string, should end in "? ".
947 It should not say how to answer, because we do that. */
950 yquery (const char *ctlstr, ...)
952 va_list args;
953 int ret;
955 va_start (args, ctlstr);
956 ret = defaulted_query (ctlstr, 'y', args);
957 va_end (args);
958 return ret;
961 /* Ask user a y-or-n question and return 1 iff answer is yes.
962 Takes three args which are given to printf to print the question.
963 The first, a control string, should end in "? ".
964 It should not say how to answer, because we do that. */
967 query (const char *ctlstr, ...)
969 va_list args;
970 int ret;
972 va_start (args, ctlstr);
973 ret = defaulted_query (ctlstr, '\0', args);
974 va_end (args);
975 return ret;
978 /* A helper for parse_escape that converts a host character to a
979 target character. C is the host character. If conversion is
980 possible, then the target character is stored in *TARGET_C and the
981 function returns 1. Otherwise, the function returns 0. */
983 static int
984 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
986 char the_char = c;
987 int result = 0;
989 auto_obstack host_data;
991 convert_between_encodings (target_charset (gdbarch), host_charset (),
992 (gdb_byte *) &the_char, 1, 1,
993 &host_data, translit_none);
995 if (obstack_object_size (&host_data) == 1)
997 result = 1;
998 *target_c = *(char *) obstack_base (&host_data);
1001 return result;
1004 /* Parse a C escape sequence. STRING_PTR points to a variable
1005 containing a pointer to the string to parse. That pointer
1006 should point to the character after the \. That pointer
1007 is updated past the characters we use. The value of the
1008 escape sequence is returned.
1010 A negative value means the sequence \ newline was seen,
1011 which is supposed to be equivalent to nothing at all.
1013 If \ is followed by a null character, we return a negative
1014 value and leave the string pointer pointing at the null character.
1016 If \ is followed by 000, we return 0 and leave the string pointer
1017 after the zeros. A value of 0 does not mean end of string. */
1020 parse_escape (struct gdbarch *gdbarch, const char **string_ptr)
1022 int target_char = -2; /* Initialize to avoid GCC warnings. */
1023 int c = *(*string_ptr)++;
1025 switch (c)
1027 case '\n':
1028 return -2;
1029 case 0:
1030 (*string_ptr)--;
1031 return 0;
1033 case '0':
1034 case '1':
1035 case '2':
1036 case '3':
1037 case '4':
1038 case '5':
1039 case '6':
1040 case '7':
1042 int i = fromhex (c);
1043 int count = 0;
1044 while (++count < 3)
1046 c = (**string_ptr);
1047 if (ISDIGIT (c) && c != '8' && c != '9')
1049 (*string_ptr)++;
1050 i *= 8;
1051 i += fromhex (c);
1053 else
1055 break;
1058 return i;
1061 case 'a':
1062 c = '\a';
1063 break;
1064 case 'b':
1065 c = '\b';
1066 break;
1067 case 'f':
1068 c = '\f';
1069 break;
1070 case 'n':
1071 c = '\n';
1072 break;
1073 case 'r':
1074 c = '\r';
1075 break;
1076 case 't':
1077 c = '\t';
1078 break;
1079 case 'v':
1080 c = '\v';
1081 break;
1083 default:
1084 break;
1087 if (!host_char_to_target (gdbarch, c, &target_char))
1088 error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1089 " which has no equivalent\nin the `%s' character set."),
1090 c, c, target_charset (gdbarch));
1091 return target_char;
1095 /* Number of lines per page or UINT_MAX if paging is disabled. */
1096 static unsigned int lines_per_page;
1097 static void
1098 show_lines_per_page (struct ui_file *file, int from_tty,
1099 struct cmd_list_element *c, const char *value)
1101 gdb_printf (file,
1102 _("Number of lines gdb thinks are in a page is %s.\n"),
1103 value);
1106 /* Number of chars per line or UINT_MAX if line folding is disabled. */
1107 static unsigned int chars_per_line;
1108 static void
1109 show_chars_per_line (struct ui_file *file, int from_tty,
1110 struct cmd_list_element *c, const char *value)
1112 gdb_printf (file,
1113 _("Number of characters gdb thinks "
1114 "are in a line is %s.\n"),
1115 value);
1118 /* Current count of lines printed on this page, chars on this line. */
1119 static unsigned int lines_printed, chars_printed;
1121 /* True if pagination is disabled for just one command. */
1123 static bool pagination_disabled_for_command;
1125 /* Buffer and start column of buffered text, for doing smarter word-
1126 wrapping. When someone calls wrap_here(), we start buffering output
1127 that comes through gdb_puts(). If we see a newline, we just
1128 spit it out and forget about the wrap_here(). If we see another
1129 wrap_here(), we spit it out and remember the newer one. If we see
1130 the end of the line, we spit out a newline, the indent, and then
1131 the buffered output. */
1133 static bool filter_initialized = false;
1137 /* See utils.h. */
1139 int readline_hidden_cols = 0;
1141 /* Initialize the number of lines per page and chars per line. */
1143 void
1144 init_page_info (void)
1146 if (batch_flag)
1148 lines_per_page = UINT_MAX;
1149 chars_per_line = UINT_MAX;
1151 else
1152 #if defined(TUI)
1153 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1154 #endif
1156 int rows, cols;
1158 #if defined(__GO32__)
1159 rows = ScreenRows ();
1160 cols = ScreenCols ();
1161 lines_per_page = rows;
1162 chars_per_line = cols;
1163 #else
1164 /* Make sure Readline has initialized its terminal settings. */
1165 rl_reset_terminal (NULL);
1167 /* Get the screen size from Readline. */
1168 rl_get_screen_size (&rows, &cols);
1170 /* Readline:
1171 - ignores the COLUMNS variable when detecting screen width
1172 (because rl_prefer_env_winsize defaults to 0)
1173 - puts the detected screen width in the COLUMNS variable
1174 (because rl_change_environment defaults to 1)
1175 - may report one less than the detected screen width in
1176 rl_get_screen_size (when _rl_term_autowrap == 0).
1177 We could use _rl_term_autowrap, but we want to avoid introducing
1178 another dependency on readline private variables, so set
1179 readline_hidden_cols by comparing COLUMNS to cols as returned by
1180 rl_get_screen_size. */
1181 const char *columns_env_str = getenv ("COLUMNS");
1182 gdb_assert (columns_env_str != nullptr);
1183 int columns_env_val = atoi (columns_env_str);
1184 gdb_assert (columns_env_val != 0);
1185 readline_hidden_cols = columns_env_val - cols;
1186 gdb_assert (readline_hidden_cols >= 0);
1187 gdb_assert (readline_hidden_cols <= 1);
1189 lines_per_page = rows;
1190 chars_per_line = cols + readline_hidden_cols;
1192 /* Readline should have fetched the termcap entry for us.
1193 Only try to use tgetnum function if rl_get_screen_size
1194 did not return a useful value. */
1195 if (((rows <= 0) && (tgetnum ((char *) "li") < 0))
1196 /* Also disable paging if inside Emacs. $EMACS was used
1197 before Emacs v25.1, $INSIDE_EMACS is used since then. */
1198 || getenv ("EMACS") || getenv ("INSIDE_EMACS"))
1200 /* The number of lines per page is not mentioned in the terminal
1201 description or EMACS environment variable is set. This probably
1202 means that paging is not useful, so disable paging. */
1203 lines_per_page = UINT_MAX;
1206 /* If the output is not a terminal, don't paginate it. */
1207 if (!gdb_stdout->isatty ())
1208 lines_per_page = UINT_MAX;
1209 #endif
1212 /* We handle SIGWINCH ourselves. */
1213 rl_catch_sigwinch = 0;
1215 set_screen_size ();
1216 set_width ();
1219 /* Return nonzero if filtered printing is initialized. */
1221 filtered_printing_initialized (void)
1223 return filter_initialized;
1226 set_batch_flag_and_restore_page_info::set_batch_flag_and_restore_page_info ()
1227 : m_save_lines_per_page (lines_per_page),
1228 m_save_chars_per_line (chars_per_line),
1229 m_save_batch_flag (batch_flag)
1231 batch_flag = 1;
1232 init_page_info ();
1235 set_batch_flag_and_restore_page_info::~set_batch_flag_and_restore_page_info ()
1237 batch_flag = m_save_batch_flag;
1238 chars_per_line = m_save_chars_per_line;
1239 lines_per_page = m_save_lines_per_page;
1241 set_screen_size ();
1242 set_width ();
1245 /* An approximation of SQRT(INT_MAX) that is:
1246 - cheap to calculate,
1247 - guaranteed to be smaller than SQRT(INT_MAX), such that
1248 sqrt_int_max * sqrt_int_max doesn't overflow, and
1249 - "close enough" to SQRT(INT_MAX), for instance for INT_MAX == 2147483647,
1250 SQRT(INT_MAX) is ~46341 and sqrt_int_max == 32767. */
1252 static const int sqrt_int_max = INT_MAX >> (sizeof (int) * 8 / 2);
1254 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1256 static void
1257 set_screen_size (void)
1259 int rows = lines_per_page;
1260 int cols = chars_per_line;
1262 /* If we get 0 or negative ROWS or COLS, treat as "infinite" size.
1263 A negative number can be seen here with the "set width/height"
1264 commands and either:
1266 - the user specified "unlimited", which maps to UINT_MAX, or
1267 - the user specified some number between INT_MAX and UINT_MAX.
1269 Cap "infinity" to approximately sqrt(INT_MAX) so that we don't
1270 overflow in rl_set_screen_size, which multiplies rows and columns
1271 to compute the number of characters on the screen. */
1273 if (rows <= 0 || rows > sqrt_int_max)
1275 rows = sqrt_int_max;
1276 lines_per_page = UINT_MAX;
1279 if (cols <= 0 || cols > sqrt_int_max)
1281 cols = sqrt_int_max;
1282 chars_per_line = UINT_MAX;
1285 /* Update Readline's idea of the terminal size. */
1286 rl_set_screen_size (rows, cols);
1289 /* Reinitialize WRAP_BUFFER. */
1291 static void
1292 set_width (void)
1294 if (chars_per_line == 0)
1295 init_page_info ();
1297 filter_initialized = true;
1300 static void
1301 set_width_command (const char *args, int from_tty, struct cmd_list_element *c)
1303 set_screen_size ();
1304 set_width ();
1307 static void
1308 set_height_command (const char *args, int from_tty, struct cmd_list_element *c)
1310 set_screen_size ();
1313 /* See utils.h. */
1315 void
1316 set_screen_width_and_height (int width, int height)
1318 lines_per_page = height;
1319 chars_per_line = width;
1321 set_screen_size ();
1322 set_width ();
1325 /* Implement "maint info screen". */
1327 static void
1328 maintenance_info_screen (const char *args, int from_tty)
1330 int rows, cols;
1331 rl_get_screen_size (&rows, &cols);
1333 gdb_printf (gdb_stdout,
1334 _("Number of characters gdb thinks "
1335 "are in a line is %u%s.\n"),
1336 chars_per_line,
1337 chars_per_line == UINT_MAX ? " (unlimited)" : "");
1339 gdb_printf (gdb_stdout,
1340 _("Number of characters readline reports "
1341 "are in a line is %d%s.\n"),
1342 cols,
1343 (cols == sqrt_int_max
1344 ? " (unlimited)"
1345 : (cols == sqrt_int_max - 1
1346 ? " (unlimited - 1)"
1347 : "")));
1349 #ifdef HAVE_LIBCURSES
1350 gdb_printf (gdb_stdout,
1351 _("Number of characters curses thinks "
1352 "are in a line is %d.\n"),
1353 COLS);
1354 #endif
1356 gdb_printf (gdb_stdout,
1357 _("Number of characters environment thinks "
1358 "are in a line is %s (COLUMNS).\n"),
1359 getenv ("COLUMNS"));
1361 gdb_printf (gdb_stdout,
1362 _("Number of lines gdb thinks are in a page is %u%s.\n"),
1363 lines_per_page,
1364 lines_per_page == UINT_MAX ? " (unlimited)" : "");
1366 gdb_printf (gdb_stdout,
1367 _("Number of lines readline reports "
1368 "are in a page is %d%s.\n"),
1369 rows,
1370 rows == sqrt_int_max ? " (unlimited)" : "");
1372 #ifdef HAVE_LIBCURSES
1373 gdb_printf (gdb_stdout,
1374 _("Number of lines curses thinks "
1375 "are in a page is %d.\n"),
1376 LINES);
1377 #endif
1379 gdb_printf (gdb_stdout,
1380 _("Number of lines environment thinks "
1381 "are in a page is %s (LINES).\n"),
1382 getenv ("LINES"));
1385 void
1386 pager_file::emit_style_escape (const ui_file_style &style)
1388 if (can_emit_style_escape () && style != m_applied_style)
1390 m_applied_style = style;
1391 if (m_paging)
1392 m_stream->emit_style_escape (style);
1393 else
1394 m_wrap_buffer.append (style.to_ansi ());
1398 /* See pager.h. */
1400 void
1401 pager_file::reset_style ()
1403 if (can_emit_style_escape ())
1405 m_applied_style = ui_file_style ();
1406 m_wrap_buffer.append (m_applied_style.to_ansi ());
1410 /* Wait, so the user can read what's on the screen. Prompt the user
1411 to continue by pressing RETURN. 'q' is also provided because
1412 telling users what to do in the prompt is more user-friendly than
1413 expecting them to think of Ctrl-C/SIGINT. */
1415 void
1416 pager_file::prompt_for_continue ()
1418 char cont_prompt[120];
1419 /* Used to add duration we waited for user to respond to
1420 prompt_for_continue_wait_time. */
1421 using namespace std::chrono;
1422 steady_clock::time_point prompt_started = steady_clock::now ();
1423 bool disable_pagination = pagination_disabled_for_command;
1425 scoped_restore save_paging = make_scoped_restore (&m_paging, true);
1427 /* Clear the current styling. */
1428 m_stream->emit_style_escape (ui_file_style ());
1430 if (annotation_level > 1)
1431 m_stream->puts (("\n\032\032pre-prompt-for-continue\n"));
1433 strcpy (cont_prompt,
1434 "--Type <RET> for more, q to quit, "
1435 "c to continue without paging--");
1436 if (annotation_level > 1)
1437 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1439 /* We must do this *before* we call gdb_readline_wrapper, else it
1440 will eventually call us -- thinking that we're trying to print
1441 beyond the end of the screen. */
1442 reinitialize_more_filter ();
1444 scoped_input_handler prepare_input;
1446 /* Call gdb_readline_wrapper, not readline, in order to keep an
1447 event loop running. */
1448 gdb::unique_xmalloc_ptr<char> ignore (gdb_readline_wrapper (cont_prompt));
1450 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1451 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
1453 if (annotation_level > 1)
1454 m_stream->puts (("\n\032\032post-prompt-for-continue\n"));
1456 if (ignore != NULL)
1458 char *p = ignore.get ();
1460 while (*p == ' ' || *p == '\t')
1461 ++p;
1462 if (p[0] == 'q')
1463 /* Do not call quit here; there is no possibility of SIGINT. */
1464 throw_quit ("Quit");
1465 if (p[0] == 'c')
1466 disable_pagination = true;
1469 /* Now we have to do this again, so that GDB will know that it doesn't
1470 need to save the ---Type <return>--- line at the top of the screen. */
1471 reinitialize_more_filter ();
1472 pagination_disabled_for_command = disable_pagination;
1474 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1477 /* Initialize timer to keep track of how long we waited for the user. */
1479 void
1480 reset_prompt_for_continue_wait_time (void)
1482 using namespace std::chrono;
1484 prompt_for_continue_wait_time = steady_clock::duration::zero ();
1487 /* Fetch the cumulative time spent in prompt_for_continue. */
1489 std::chrono::steady_clock::duration
1490 get_prompt_for_continue_wait_time ()
1492 return prompt_for_continue_wait_time;
1495 /* Reinitialize filter; ie. tell it to reset to original values. */
1497 void
1498 reinitialize_more_filter (void)
1500 lines_printed = 0;
1501 chars_printed = 0;
1502 pagination_disabled_for_command = false;
1505 void
1506 pager_file::flush_wrap_buffer ()
1508 if (!m_paging && !m_wrap_buffer.empty ())
1510 m_stream->puts (m_wrap_buffer.c_str ());
1511 m_wrap_buffer.clear ();
1515 void
1516 pager_file::flush ()
1518 flush_wrap_buffer ();
1519 m_stream->flush ();
1522 /* See utils.h. */
1524 void
1525 gdb_flush (struct ui_file *stream)
1527 stream->flush ();
1530 /* See utils.h. */
1533 get_chars_per_line ()
1535 return chars_per_line;
1538 /* See ui-file.h. */
1540 void
1541 pager_file::wrap_here (int indent)
1543 /* This should have been allocated, but be paranoid anyway. */
1544 gdb_assert (filter_initialized);
1546 flush_wrap_buffer ();
1547 if (chars_per_line == UINT_MAX) /* No line overflow checking. */
1549 m_wrap_column = 0;
1551 else if (chars_printed >= chars_per_line)
1553 this->puts ("\n");
1554 if (indent != 0)
1555 this->puts (n_spaces (indent));
1556 m_wrap_column = 0;
1558 else
1560 m_wrap_column = chars_printed;
1561 m_wrap_indent = indent;
1562 m_wrap_style = m_applied_style;
1566 /* Print input string to gdb_stdout arranging strings in columns of n
1567 chars. String can be right or left justified in the column. Never
1568 prints trailing spaces. String should never be longer than width.
1569 FIXME: this could be useful for the EXAMINE command, which
1570 currently doesn't tabulate very well. */
1572 void
1573 puts_tabular (char *string, int width, int right)
1575 int spaces = 0;
1576 int stringlen;
1577 char *spacebuf;
1579 gdb_assert (chars_per_line > 0);
1580 if (chars_per_line == UINT_MAX)
1582 gdb_puts (string);
1583 gdb_puts ("\n");
1584 return;
1587 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
1588 gdb_puts ("\n");
1590 if (width >= chars_per_line)
1591 width = chars_per_line - 1;
1593 stringlen = strlen (string);
1595 if (chars_printed > 0)
1596 spaces = width - (chars_printed - 1) % width - 1;
1597 if (right)
1598 spaces += width - stringlen;
1600 spacebuf = (char *) alloca (spaces + 1);
1601 spacebuf[spaces] = '\0';
1602 while (spaces--)
1603 spacebuf[spaces] = ' ';
1605 gdb_puts (spacebuf);
1606 gdb_puts (string);
1610 /* Ensure that whatever gets printed next, using the filtered output
1611 commands, starts at the beginning of the line. I.e. if there is
1612 any pending output for the current line, flush it and start a new
1613 line. Otherwise do nothing. */
1615 void
1616 begin_line (void)
1618 if (chars_printed > 0)
1620 gdb_puts ("\n");
1624 void
1625 pager_file::puts (const char *linebuffer)
1627 const char *lineptr;
1629 if (linebuffer == 0)
1630 return;
1632 /* Don't do any filtering or wrapping if both are disabled. */
1633 if (batch_flag
1634 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
1635 || top_level_interpreter () == NULL
1636 || top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
1638 flush_wrap_buffer ();
1639 m_stream->puts (linebuffer);
1640 return;
1643 auto buffer_clearer
1644 = make_scope_exit ([&] ()
1646 m_wrap_buffer.clear ();
1647 m_wrap_column = 0;
1648 m_wrap_indent = 0;
1651 /* If the user does "set height 1" then the pager will exhibit weird
1652 behavior. This is pathological, though, so don't allow it. */
1653 const unsigned int lines_allowed = (lines_per_page > 1
1654 ? lines_per_page - 1
1655 : 1);
1657 /* Go through and output each character. Show line extension
1658 when this is necessary; prompt user for new page when this is
1659 necessary. */
1661 lineptr = linebuffer;
1662 while (*lineptr)
1664 /* Possible new page. Note that PAGINATION_DISABLED_FOR_COMMAND
1665 might be set during this loop, so we must continue to check
1666 it here. */
1667 if (pagination_enabled
1668 && !pagination_disabled_for_command
1669 && lines_printed >= lines_allowed)
1670 prompt_for_continue ();
1672 while (*lineptr && *lineptr != '\n')
1674 int skip_bytes;
1676 /* Print a single line. */
1677 if (*lineptr == '\t')
1679 m_wrap_buffer.push_back ('\t');
1680 /* Shifting right by 3 produces the number of tab stops
1681 we have already passed, and then adding one and
1682 shifting left 3 advances to the next tab stop. */
1683 chars_printed = ((chars_printed >> 3) + 1) << 3;
1684 lineptr++;
1686 else if (*lineptr == '\033'
1687 && skip_ansi_escape (lineptr, &skip_bytes))
1689 m_wrap_buffer.append (lineptr, skip_bytes);
1690 /* Note that we don't consider this a character, so we
1691 don't increment chars_printed here. */
1692 lineptr += skip_bytes;
1694 else if (*lineptr == '\r')
1696 m_wrap_buffer.push_back (*lineptr);
1697 chars_printed = 0;
1698 lineptr++;
1700 else
1702 m_wrap_buffer.push_back (*lineptr);
1703 chars_printed++;
1704 lineptr++;
1707 if (chars_printed >= chars_per_line)
1709 unsigned int save_chars = chars_printed;
1711 /* If we change the style, below, we'll want to reset it
1712 before continuing to print. If there is no wrap
1713 column, then we'll only reset the style if the pager
1714 prompt is given; and to avoid emitting style
1715 sequences in the middle of a run of text, we track
1716 this as well. */
1717 ui_file_style save_style = m_applied_style;
1718 bool did_paginate = false;
1720 chars_printed = 0;
1721 lines_printed++;
1722 if (m_wrap_column)
1724 /* We are about to insert a newline at an historic
1725 location in the WRAP_BUFFER. Before we do we want to
1726 restore the default style. To know if we actually
1727 need to insert an escape sequence we must restore the
1728 current applied style to how it was at the WRAP_COLUMN
1729 location. */
1730 m_applied_style = m_wrap_style;
1731 m_stream->emit_style_escape (ui_file_style ());
1732 /* If we aren't actually wrapping, don't output
1733 newline -- if chars_per_line is right, we
1734 probably just overflowed anyway; if it's wrong,
1735 let us keep going. */
1736 m_stream->puts ("\n");
1738 else
1739 this->flush_wrap_buffer ();
1741 /* Possible new page. Note that
1742 PAGINATION_DISABLED_FOR_COMMAND might be set during
1743 this loop, so we must continue to check it here. */
1744 if (pagination_enabled
1745 && !pagination_disabled_for_command
1746 && lines_printed >= lines_allowed)
1748 prompt_for_continue ();
1749 did_paginate = true;
1752 /* Now output indentation and wrapped string. */
1753 if (m_wrap_column)
1755 m_stream->puts (n_spaces (m_wrap_indent));
1757 /* Having finished inserting the wrapping we should
1758 restore the style as it was at the WRAP_COLUMN. */
1759 m_stream->emit_style_escape (m_wrap_style);
1761 /* The WRAP_BUFFER will still contain content, and that
1762 content might set some alternative style. Restore
1763 APPLIED_STYLE as it was before we started wrapping,
1764 this reflects the current style for the last character
1765 in WRAP_BUFFER. */
1766 m_applied_style = save_style;
1768 /* Note that this can set chars_printed > chars_per_line
1769 if we are printing a long string. */
1770 chars_printed = m_wrap_indent + (save_chars - m_wrap_column);
1771 m_wrap_column = 0; /* And disable fancy wrap */
1773 else if (did_paginate)
1774 m_stream->emit_style_escape (save_style);
1778 if (*lineptr == '\n')
1780 chars_printed = 0;
1781 wrap_here (0); /* Spit out chars, cancel further wraps. */
1782 lines_printed++;
1783 m_stream->puts ("\n");
1784 lineptr++;
1788 buffer_clearer.release ();
1791 void
1792 pager_file::write (const char *buf, long length_buf)
1794 /* We have to make a string here because the pager uses
1795 skip_ansi_escape, which requires NUL-termination. */
1796 std::string str (buf, length_buf);
1797 this->puts (str.c_str ());
1800 #if GDB_SELF_TEST
1802 /* Test that disabling the pager does not also disable word
1803 wrapping. */
1805 static void
1806 test_pager ()
1808 string_file *strfile = new string_file ();
1809 pager_file pager (strfile);
1811 /* Make sure the pager is disabled. */
1812 scoped_restore save_enabled
1813 = make_scoped_restore (&pagination_enabled, false);
1814 scoped_restore save_disabled
1815 = make_scoped_restore (&pagination_disabled_for_command, false);
1816 scoped_restore save_batch
1817 = make_scoped_restore (&batch_flag, false);
1818 scoped_restore save_lines
1819 = make_scoped_restore (&lines_per_page, 50);
1820 /* Make it easy to word wrap. */
1821 scoped_restore save_chars
1822 = make_scoped_restore (&chars_per_line, 15);
1823 scoped_restore save_printed
1824 = make_scoped_restore (&chars_printed, 0);
1826 pager.puts ("aaaaaaaaaaaa");
1827 pager.wrap_here (2);
1828 pager.puts ("bbbbbbbbbbbb\n");
1830 SELF_CHECK (strfile->string () == "aaaaaaaaaaaa\n bbbbbbbbbbbb\n");
1833 #endif /* GDB_SELF_TEST */
1835 void
1836 gdb_puts (const char *linebuffer, struct ui_file *stream)
1838 stream->puts (linebuffer);
1841 /* See utils.h. */
1843 void
1844 fputs_styled (const char *linebuffer, const ui_file_style &style,
1845 struct ui_file *stream)
1847 stream->emit_style_escape (style);
1848 gdb_puts (linebuffer, stream);
1849 stream->emit_style_escape (ui_file_style ());
1852 /* See utils.h. */
1854 void
1855 fputs_highlighted (const char *str, const compiled_regex &highlight,
1856 struct ui_file *stream)
1858 regmatch_t pmatch;
1860 while (*str && highlight.exec (str, 1, &pmatch, 0) == 0)
1862 size_t n_highlight = pmatch.rm_eo - pmatch.rm_so;
1864 /* Output the part before pmatch with current style. */
1865 while (pmatch.rm_so > 0)
1867 gdb_putc (*str, stream);
1868 pmatch.rm_so--;
1869 str++;
1872 /* Output pmatch with the highlight style. */
1873 stream->emit_style_escape (highlight_style.style ());
1874 while (n_highlight > 0)
1876 gdb_putc (*str, stream);
1877 n_highlight--;
1878 str++;
1880 stream->emit_style_escape (ui_file_style ());
1883 /* Output the trailing part of STR not matching HIGHLIGHT. */
1884 if (*str)
1885 gdb_puts (str, stream);
1888 void
1889 gdb_putc (int c)
1891 return gdb_stdout->putc (c);
1894 void
1895 gdb_putc (int c, struct ui_file *stream)
1897 return stream->putc (c);
1900 void
1901 gdb_vprintf (struct ui_file *stream, const char *format, va_list args)
1903 stream->vprintf (format, args);
1906 void
1907 gdb_vprintf (const char *format, va_list args)
1909 gdb_stdout->vprintf (format, args);
1912 void
1913 gdb_printf (struct ui_file *stream, const char *format, ...)
1915 va_list args;
1917 va_start (args, format);
1918 gdb_vprintf (stream, format, args);
1919 va_end (args);
1922 /* See utils.h. */
1924 void
1925 fprintf_styled (struct ui_file *stream, const ui_file_style &style,
1926 const char *format, ...)
1928 va_list args;
1930 stream->emit_style_escape (style);
1931 va_start (args, format);
1932 gdb_vprintf (stream, format, args);
1933 va_end (args);
1934 stream->emit_style_escape (ui_file_style ());
1937 void
1938 gdb_printf (const char *format, ...)
1940 va_list args;
1942 va_start (args, format);
1943 gdb_vprintf (gdb_stdout, format, args);
1944 va_end (args);
1948 void
1949 printf_unfiltered (const char *format, ...)
1951 va_list args;
1953 va_start (args, format);
1954 string_file file (gdb_stdout->can_emit_style_escape ());
1955 file.vprintf (format, args);
1956 gdb_stdout->puts_unfiltered (file.string ().c_str ());
1957 va_end (args);
1960 /* Easy -- but watch out!
1962 This routine is *not* a replacement for puts()! puts() appends a newline.
1963 This one doesn't, and had better not! */
1965 void
1966 gdb_puts (const char *string)
1968 gdb_stdout->puts (string);
1971 /* Return a pointer to N spaces and a null. The pointer is good
1972 until the next call to here. */
1973 const char *
1974 n_spaces (int n)
1976 char *t;
1977 static char *spaces = 0;
1978 static int max_spaces = -1;
1980 if (n > max_spaces)
1982 xfree (spaces);
1983 spaces = (char *) xmalloc (n + 1);
1984 for (t = spaces + n; t != spaces;)
1985 *--t = ' ';
1986 spaces[n] = '\0';
1987 max_spaces = n;
1990 return spaces + max_spaces - n;
1993 /* Print N spaces. */
1994 void
1995 print_spaces (int n, struct ui_file *stream)
1997 gdb_puts (n_spaces (n), stream);
2000 /* C++/ObjC demangler stuff. */
2002 /* fprintf_symbol attempts to demangle NAME, a symbol in language
2003 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2004 If the name is not mangled, or the language for the name is unknown, or
2005 demangling is off, the name is printed in its "raw" form. */
2007 void
2008 fprintf_symbol (struct ui_file *stream, const char *name,
2009 enum language lang, int arg_mode)
2011 if (name != NULL)
2013 /* If user wants to see raw output, no problem. */
2014 if (!demangle)
2016 gdb_puts (name, stream);
2018 else
2020 gdb::unique_xmalloc_ptr<char> demangled
2021 = language_def (lang)->demangle_symbol (name, arg_mode);
2022 gdb_puts (demangled ? demangled.get () : name, stream);
2027 /* True if CH is a character that can be part of a symbol name. I.e.,
2028 either a number, a letter, or a '_'. */
2030 static bool
2031 valid_identifier_name_char (int ch)
2033 return (ISALNUM (ch) || ch == '_');
2036 /* Skip to end of token, or to END, whatever comes first. Input is
2037 assumed to be a C++ operator name. */
2039 static const char *
2040 cp_skip_operator_token (const char *token, const char *end)
2042 const char *p = token;
2043 while (p != end && !ISSPACE (*p) && *p != '(')
2045 if (valid_identifier_name_char (*p))
2047 while (p != end && valid_identifier_name_char (*p))
2048 p++;
2049 return p;
2051 else
2053 /* Note, ordered such that among ops that share a prefix,
2054 longer comes first. This is so that the loop below can
2055 bail on first match. */
2056 static const char *ops[] =
2058 "[",
2059 "]",
2060 "~",
2061 ",",
2062 "-=", "--", "->", "-",
2063 "+=", "++", "+",
2064 "*=", "*",
2065 "/=", "/",
2066 "%=", "%",
2067 "|=", "||", "|",
2068 "&=", "&&", "&",
2069 "^=", "^",
2070 "!=", "!",
2071 "<<=", "<=", "<<", "<",
2072 ">>=", ">=", ">>", ">",
2073 "==", "=",
2076 for (const char *op : ops)
2078 size_t oplen = strlen (op);
2079 size_t lencmp = std::min<size_t> (oplen, end - p);
2081 if (strncmp (p, op, lencmp) == 0)
2082 return p + lencmp;
2084 /* Some unidentified character. Return it. */
2085 return p + 1;
2089 return p;
2092 /* Advance STRING1/STRING2 past whitespace. */
2094 static void
2095 skip_ws (const char *&string1, const char *&string2, const char *end_str2)
2097 while (ISSPACE (*string1))
2098 string1++;
2099 while (string2 < end_str2 && ISSPACE (*string2))
2100 string2++;
2103 /* True if STRING points at the start of a C++ operator name. START
2104 is the start of the string that STRING points to, hence when
2105 reading backwards, we must not read any character before START. */
2107 static bool
2108 cp_is_operator (const char *string, const char *start)
2110 return ((string == start
2111 || !valid_identifier_name_char (string[-1]))
2112 && strncmp (string, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
2113 && !valid_identifier_name_char (string[CP_OPERATOR_LEN]));
2116 /* If *NAME points at an ABI tag, skip it and return true. Otherwise
2117 leave *NAME unmodified and return false. (see GCC's abi_tag
2118 attribute), such names are demangled as e.g.,
2119 "function[abi:cxx11]()". */
2121 static bool
2122 skip_abi_tag (const char **name)
2124 const char *p = *name;
2126 if (startswith (p, "[abi:"))
2128 p += 5;
2130 while (valid_identifier_name_char (*p))
2131 p++;
2133 if (*p == ']')
2135 p++;
2136 *name = p;
2137 return true;
2140 return false;
2143 /* If *NAME points at a template parameter list, skip it and return true.
2144 Otherwise do nothing and return false. */
2146 static bool
2147 skip_template_parameter_list (const char **name)
2149 const char *p = *name;
2151 if (*p == '<')
2153 const char *template_param_list_end = find_toplevel_char (p + 1, '>');
2155 if (template_param_list_end == NULL)
2156 return false;
2158 p = template_param_list_end + 1;
2160 /* Skip any whitespace that might occur after the closing of the
2161 parameter list, but only if it is the end of parameter list. */
2162 const char *q = p;
2163 while (ISSPACE (*q))
2164 ++q;
2165 if (*q == '>')
2166 p = q;
2167 *name = p;
2168 return true;
2171 return false;
2174 /* See utils.h. */
2177 strncmp_iw_with_mode (const char *string1, const char *string2,
2178 size_t string2_len, strncmp_iw_mode mode,
2179 enum language language,
2180 completion_match_for_lcd *match_for_lcd,
2181 bool ignore_template_params)
2183 const char *string1_start = string1;
2184 const char *end_str2 = string2 + string2_len;
2185 bool skip_spaces = true;
2186 bool have_colon_op = (language == language_cplus
2187 || language == language_rust
2188 || language == language_fortran);
2190 gdb_assert (match_for_lcd == nullptr || match_for_lcd->empty ());
2192 while (1)
2194 if (skip_spaces
2195 || ((ISSPACE (*string1) && !valid_identifier_name_char (*string2))
2196 || (ISSPACE (*string2) && !valid_identifier_name_char (*string1))))
2198 skip_ws (string1, string2, end_str2);
2199 skip_spaces = false;
2202 /* Skip [abi:cxx11] tags in the symbol name if the lookup name
2203 doesn't include them. E.g.:
2205 string1: function[abi:cxx1](int)
2206 string2: function
2208 string1: function[abi:cxx1](int)
2209 string2: function(int)
2211 string1: Struct[abi:cxx1]::function()
2212 string2: Struct::function()
2214 string1: function(Struct[abi:cxx1], int)
2215 string2: function(Struct, int)
2217 if (string2 == end_str2
2218 || (*string2 != '[' && !valid_identifier_name_char (*string2)))
2220 const char *abi_start = string1;
2222 /* There can be more than one tag. */
2223 while (*string1 == '[' && skip_abi_tag (&string1))
2226 if (match_for_lcd != NULL && abi_start != string1)
2227 match_for_lcd->mark_ignored_range (abi_start, string1);
2229 while (ISSPACE (*string1))
2230 string1++;
2233 /* Skip template parameters in STRING1 if STRING2 does not contain
2234 any. E.g.:
2236 Case 1: User is looking for all functions named "foo".
2237 string1: foo <...> (...)
2238 string2: foo
2240 Case 2: User is looking for all methods named "foo" in all template
2241 class instantiations.
2242 string1: Foo<...>::foo <...> (...)
2243 string2: Foo::foo (...)
2245 Case 3: User is looking for a specific overload of a template
2246 function or method.
2247 string1: foo<...>
2248 string2: foo(...)
2250 Case 4: User is looking for a specific overload of a specific
2251 template instantiation.
2252 string1: foo<A> (...)
2253 string2: foo<B> (...)
2255 Case 5: User is looking wild parameter match.
2256 string1: foo<A<a<b<...> > > > (...)
2257 string2: foo<A
2259 if (language == language_cplus && ignore_template_params
2260 && *string1 == '<' && *string2 != '<')
2262 /* Skip any parameter list in STRING1. */
2263 const char *template_start = string1;
2265 if (skip_template_parameter_list (&string1))
2267 /* Don't mark the parameter list ignored if the user didn't
2268 try to ignore it. [Case #5 above] */
2269 if (*string2 != '\0'
2270 && match_for_lcd != NULL && template_start != string1)
2271 match_for_lcd->mark_ignored_range (template_start, string1);
2275 if (*string1 == '\0' || string2 == end_str2)
2276 break;
2278 /* Handle the :: operator. */
2279 if (have_colon_op && string1[0] == ':' && string1[1] == ':')
2281 if (*string2 != ':')
2282 return 1;
2284 string1++;
2285 string2++;
2287 if (string2 == end_str2)
2288 break;
2290 if (*string2 != ':')
2291 return 1;
2293 string1++;
2294 string2++;
2296 while (ISSPACE (*string1))
2297 string1++;
2298 while (string2 < end_str2 && ISSPACE (*string2))
2299 string2++;
2300 continue;
2303 /* Handle C++ user-defined operators. */
2304 else if (language == language_cplus
2305 && *string1 == 'o')
2307 if (cp_is_operator (string1, string1_start))
2309 /* An operator name in STRING1. Check STRING2. */
2310 size_t cmplen
2311 = std::min<size_t> (CP_OPERATOR_LEN, end_str2 - string2);
2312 if (strncmp (string1, string2, cmplen) != 0)
2313 return 1;
2315 string1 += cmplen;
2316 string2 += cmplen;
2318 if (string2 != end_str2)
2320 /* Check for "operatorX" in STRING2. */
2321 if (valid_identifier_name_char (*string2))
2322 return 1;
2324 skip_ws (string1, string2, end_str2);
2327 /* Handle operator(). */
2328 if (*string1 == '(')
2330 if (string2 == end_str2)
2332 if (mode == strncmp_iw_mode::NORMAL)
2333 return 0;
2334 else
2336 /* Don't break for the regular return at the
2337 bottom, because "operator" should not
2338 match "operator()", since this open
2339 parentheses is not the parameter list
2340 start. */
2341 return *string1 != '\0';
2345 if (*string1 != *string2)
2346 return 1;
2348 string1++;
2349 string2++;
2352 while (1)
2354 skip_ws (string1, string2, end_str2);
2356 /* Skip to end of token, or to END, whatever comes
2357 first. */
2358 const char *end_str1 = string1 + strlen (string1);
2359 const char *p1 = cp_skip_operator_token (string1, end_str1);
2360 const char *p2 = cp_skip_operator_token (string2, end_str2);
2362 cmplen = std::min (p1 - string1, p2 - string2);
2363 if (p2 == end_str2)
2365 if (strncmp (string1, string2, cmplen) != 0)
2366 return 1;
2368 else
2370 if (p1 - string1 != p2 - string2)
2371 return 1;
2372 if (strncmp (string1, string2, cmplen) != 0)
2373 return 1;
2376 string1 += cmplen;
2377 string2 += cmplen;
2379 if (*string1 == '\0' || string2 == end_str2)
2380 break;
2381 if (*string1 == '(' || *string2 == '(')
2382 break;
2384 /* If STRING1 or STRING2 starts with a template
2385 parameter list, break out of operator processing. */
2386 skip_ws (string1, string2, end_str2);
2387 if (*string1 == '<' || *string2 == '<')
2388 break;
2391 continue;
2395 if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2396 break;
2397 if (case_sensitivity == case_sensitive_off
2398 && (TOLOWER ((unsigned char) *string1)
2399 != TOLOWER ((unsigned char) *string2)))
2400 break;
2402 /* If we see any non-whitespace, non-identifier-name character
2403 (any of "()<>*&" etc.), then skip spaces the next time
2404 around. */
2405 if (!ISSPACE (*string1) && !valid_identifier_name_char (*string1))
2406 skip_spaces = true;
2408 string1++;
2409 string2++;
2412 if (string2 == end_str2)
2414 if (mode == strncmp_iw_mode::NORMAL)
2416 /* Strip abi tag markers from the matched symbol name.
2417 Usually the ABI marker will be found on function name
2418 (automatically added because the function returns an
2419 object marked with an ABI tag). However, it's also
2420 possible to see a marker in one of the function
2421 parameters, for example.
2423 string2 (lookup name):
2424 func
2425 symbol name:
2426 function(some_struct[abi:cxx11], int)
2428 and for completion LCD computation we want to say that
2429 the match was for:
2430 function(some_struct, int)
2432 if (match_for_lcd != NULL)
2434 while ((string1 = strstr (string1, "[abi:")) != NULL)
2436 const char *abi_start = string1;
2438 /* There can be more than one tag. */
2439 while (skip_abi_tag (&string1) && *string1 == '[')
2442 if (abi_start != string1)
2443 match_for_lcd->mark_ignored_range (abi_start, string1);
2447 return 0;
2449 else
2451 if (*string1 == '(')
2453 int p_count = 0;
2457 if (*string1 == '(')
2458 ++p_count;
2459 else if (*string1 == ')')
2460 --p_count;
2461 ++string1;
2463 while (*string1 != '\0' && p_count > 0);
2465 /* There maybe things like 'const' after the parameters,
2466 which we do want to ignore. However, if there's an '@'
2467 then this likely indicates something like '@plt' which we
2468 should not ignore. */
2469 return *string1 == '@';
2472 return *string1 == '\0' ? 0 : 1;
2476 else
2477 return 1;
2480 #if GDB_SELF_TEST
2482 /* Unit tests for strncmp_iw_with_mode. */
2484 #define CHECK_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2485 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2486 strncmp_iw_mode::MODE, \
2487 (LANG), (LCD)) == 0)
2489 #define CHECK_MATCH_LANG(S1, S2, MODE, LANG) \
2490 CHECK_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2492 #define CHECK_MATCH(S1, S2, MODE) \
2493 CHECK_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2495 #define CHECK_NO_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2496 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2497 strncmp_iw_mode::MODE, \
2498 (LANG)) != 0)
2500 #define CHECK_NO_MATCH_LANG(S1, S2, MODE, LANG) \
2501 CHECK_NO_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2503 #define CHECK_NO_MATCH(S1, S2, MODE) \
2504 CHECK_NO_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2506 static void
2507 check_scope_operator (enum language lang)
2509 CHECK_MATCH_LANG ("::", "::", NORMAL, lang);
2510 CHECK_MATCH_LANG ("::foo", "::", NORMAL, lang);
2511 CHECK_MATCH_LANG ("::foo", "::foo", NORMAL, lang);
2512 CHECK_MATCH_LANG (" :: foo ", "::foo", NORMAL, lang);
2513 CHECK_MATCH_LANG ("a::b", "a ::b", NORMAL, lang);
2514 CHECK_MATCH_LANG ("a::b", "a\t::b", NORMAL, lang);
2515 CHECK_MATCH_LANG ("a::b", "a \t::b", NORMAL, lang);
2516 CHECK_MATCH_LANG ("a::b", "a\t ::b", NORMAL, lang);
2517 CHECK_MATCH_LANG ("a::b", "a:: b", NORMAL, lang);
2518 CHECK_MATCH_LANG ("a::b", "a::\tb", NORMAL, lang);
2519 CHECK_MATCH_LANG ("a::b", "a:: \tb", NORMAL, lang);
2520 CHECK_MATCH_LANG ("a::b", "a::\t b", NORMAL, lang);
2521 CHECK_MATCH_LANG ("a::b", "a :: b", NORMAL, lang);
2522 CHECK_MATCH_LANG ("a::b", "a ::\tb", NORMAL, lang);
2523 CHECK_MATCH_LANG ("a::b", "a\t:: b", NORMAL, lang);
2524 CHECK_MATCH_LANG ("a::b", "a \t::\t b", NORMAL, lang);
2525 CHECK_MATCH_LANG ("a ::b", "a::b", NORMAL, lang);
2526 CHECK_MATCH_LANG ("a\t::b", "a::b", NORMAL, lang);
2527 CHECK_MATCH_LANG ("a \t::b", "a::b", NORMAL, lang);
2528 CHECK_MATCH_LANG ("a\t ::b", "a::b", NORMAL, lang);
2529 CHECK_MATCH_LANG ("a:: b", "a::b", NORMAL, lang);
2530 CHECK_MATCH_LANG ("a::\tb", "a::b", NORMAL, lang);
2531 CHECK_MATCH_LANG ("a:: \tb", "a::b", NORMAL, lang);
2532 CHECK_MATCH_LANG ("a::\t b", "a::b", NORMAL, lang);
2533 CHECK_MATCH_LANG ("a :: b", "a::b", NORMAL, lang);
2534 CHECK_MATCH_LANG ("a ::\tb", "a::b", NORMAL, lang);
2535 CHECK_MATCH_LANG ("a\t:: b", "a::b", NORMAL, lang);
2536 CHECK_MATCH_LANG ("a \t::\t b", "a::b", NORMAL, lang);
2537 CHECK_MATCH_LANG ("a::b::c", "a::b::c", NORMAL, lang);
2538 CHECK_MATCH_LANG (" a:: b:: c", "a::b::c", NORMAL, lang);
2539 CHECK_MATCH_LANG ("a::b::c", " a:: b:: c", NORMAL, lang);
2540 CHECK_MATCH_LANG ("a ::b ::c", "a::b::c", NORMAL, lang);
2541 CHECK_MATCH_LANG ("a::b::c", "a :: b:: c", NORMAL, lang);
2542 CHECK_MATCH_LANG ("\ta::\tb::\tc", "\ta::\tb::\tc", NORMAL, lang);
2543 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a\t::b\t::c\t", NORMAL, lang);
2544 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", " \ta:: \tb:: \tc", NORMAL, lang);
2545 CHECK_MATCH_LANG ("\t a::\t b::\t c", "\t a::\t b::\t c", NORMAL, lang);
2546 CHECK_MATCH_LANG ("a::b::c", "\ta::\tb::\tc", NORMAL, lang);
2547 CHECK_MATCH_LANG ("a::b::c", "a\t::b\t::c\t", NORMAL, lang);
2548 CHECK_MATCH_LANG ("a::b::c", " \ta:: \tb:: \tc", NORMAL, lang);
2549 CHECK_MATCH_LANG ("a::b::c", "\t a::\t b::\t c", NORMAL, lang);
2550 CHECK_MATCH_LANG ("\ta::\tb::\tc", "a::b::c", NORMAL, lang);
2551 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a::b::c", NORMAL, lang);
2552 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", "a::b::c", NORMAL, lang);
2553 CHECK_MATCH_LANG ("\t a::\t b::\t c", "a::b::c", NORMAL, lang);
2554 CHECK_MATCH_LANG ("a :: b:: c\t", "\ta :: b\t:: c\t\t", NORMAL, lang);
2555 CHECK_MATCH_LANG (" a::\t \t b:: c\t", "\ta ::b:: c\t\t",
2556 NORMAL, lang);
2557 CHECK_MATCH_LANG ("a :: b :: \t\t\tc\t",
2558 "\t\t\t\ta :: \t\t\t b \t\t::c",
2559 NORMAL, lang);
2560 CHECK_MATCH_LANG ("a::b()", "a", NORMAL, lang);
2561 CHECK_MATCH_LANG ("a::b()", "a::", NORMAL, lang);
2562 CHECK_MATCH_LANG ("a::b()", "a::b", NORMAL, lang);
2563 CHECK_MATCH_LANG ("a::b(a)", "a", NORMAL, lang);
2564 CHECK_MATCH_LANG ("a::b(a)", "a::", NORMAL, lang);
2565 CHECK_MATCH_LANG ("a::b(a)", "a::b", NORMAL, lang);
2566 CHECK_MATCH_LANG ("a::b(a,b)", "a", NORMAL, lang);
2567 CHECK_MATCH_LANG ("a::b(a,b)", "a::", NORMAL, lang);
2568 CHECK_MATCH_LANG ("a::b(a,b)", "a::b", NORMAL, lang);
2569 CHECK_MATCH_LANG ("a::b(a,b,c)", "a", NORMAL, lang);
2570 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::", NORMAL, lang);
2571 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::b", NORMAL, lang);
2573 CHECK_NO_MATCH_LANG ("a::", "::a", NORMAL, lang);
2574 CHECK_NO_MATCH_LANG ("::a", "::a()", NORMAL, lang);
2575 CHECK_NO_MATCH_LANG ("::", "::a", NORMAL, lang);
2576 CHECK_NO_MATCH_LANG ("a:::b", "a::b", NORMAL, lang);
2577 CHECK_NO_MATCH_LANG ("a::b()", "a::b(a)", NORMAL, lang);
2578 CHECK_NO_MATCH_LANG ("a::b(a)", "a::b()", NORMAL, lang);
2579 CHECK_NO_MATCH_LANG ("a::b(a,b)", "a::b(a,a)", NORMAL, lang);
2580 CHECK_NO_MATCH_LANG ("a::b", "a()", NORMAL, lang);
2581 CHECK_NO_MATCH_LANG ("a::b", "a::()", NORMAL, lang);
2582 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2583 CHECK_NO_MATCH_LANG ("a::b", "a(a)", NORMAL, lang);
2584 CHECK_NO_MATCH_LANG ("a::b", "a::(a)", NORMAL, lang);
2585 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2586 CHECK_NO_MATCH_LANG ("a::b", "a(a,b)", NORMAL, lang);
2587 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b)", NORMAL, lang);
2588 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b)", NORMAL, lang);
2589 CHECK_NO_MATCH_LANG ("a::b", "a(a,b,c)", NORMAL, lang);
2590 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b,c)", NORMAL, lang);
2591 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b,c)", NORMAL, lang);
2594 /* Callback for strncmp_iw_with_mode unit tests. */
2596 static void
2597 strncmp_iw_with_mode_tests ()
2599 /* Some of the following tests are nonsensical, but could be input by a
2600 deranged script (or user). */
2602 /* strncmp_iw_mode::NORMAL: strcmp()-like but ignore any whitespace... */
2604 CHECK_MATCH ("", "", NORMAL);
2605 CHECK_MATCH ("foo", "foo", NORMAL);
2606 CHECK_MATCH (" foo", "foo", NORMAL);
2607 CHECK_MATCH ("foo ", "foo", NORMAL);
2608 CHECK_MATCH (" foo ", "foo", NORMAL);
2609 CHECK_MATCH (" foo", "foo", NORMAL);
2610 CHECK_MATCH ("foo ", "foo", NORMAL);
2611 CHECK_MATCH (" foo ", "foo", NORMAL);
2612 CHECK_MATCH ("\tfoo", "foo", NORMAL);
2613 CHECK_MATCH ("foo\t", "foo", NORMAL);
2614 CHECK_MATCH ("\tfoo\t", "foo", NORMAL);
2615 CHECK_MATCH (" \tfoo \t", "foo", NORMAL);
2616 CHECK_MATCH ("\t foo\t ", "foo", NORMAL);
2617 CHECK_MATCH ("\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2618 "foo", NORMAL);
2619 CHECK_MATCH ("foo",
2620 "\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2621 NORMAL);
2622 CHECK_MATCH ("foo bar", "foo", NORMAL);
2623 CHECK_NO_MATCH ("foo", "bar", NORMAL);
2624 CHECK_NO_MATCH ("foo bar", "foobar", NORMAL);
2625 CHECK_NO_MATCH (" foo ", "bar", NORMAL);
2626 CHECK_NO_MATCH ("foo", " bar ", NORMAL);
2627 CHECK_NO_MATCH (" \t\t foo\t\t ", "\t \t \tbar\t", NORMAL);
2628 CHECK_NO_MATCH ("@!%&", "@!%&foo", NORMAL);
2630 /* ... and function parameters in STRING1. */
2631 CHECK_MATCH ("foo()", "foo()", NORMAL);
2632 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2633 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2634 CHECK_MATCH ("foo\t()", "foo()", NORMAL);
2635 CHECK_MATCH ("foo\t ()", "foo()", NORMAL);
2636 CHECK_MATCH ("foo \t()", "foo()", NORMAL);
2637 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2638 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2639 CHECK_MATCH ("foo()", "foo\t()", NORMAL);
2640 CHECK_MATCH ("foo()", "foo\t ()", NORMAL);
2641 CHECK_MATCH ("foo()", "foo \t()", NORMAL);
2642 CHECK_MATCH ("foo()", "foo()", NORMAL);
2643 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2644 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2645 CHECK_MATCH ("foo\t()", "foo\t()", NORMAL);
2646 CHECK_MATCH ("foo\t ()", "foo\t ()", NORMAL);
2647 CHECK_MATCH ("foo \t()", "foo \t()", NORMAL);
2648 CHECK_MATCH ("foo(a)", "foo(a)", NORMAL);
2649 CHECK_MATCH ("foo( a)", "foo(a)", NORMAL);
2650 CHECK_MATCH ("foo(a )", "foo(a)", NORMAL);
2651 CHECK_MATCH ("foo(\ta)", "foo(a)", NORMAL);
2652 CHECK_MATCH ("foo(a\t)", "foo(a)", NORMAL);
2653 CHECK_MATCH ("foo(\t a)", "foo(a)", NORMAL);
2654 CHECK_MATCH ("foo( \ta)", "foo(a)", NORMAL);
2655 CHECK_MATCH ("foo(a\t )", "foo(a)", NORMAL);
2656 CHECK_MATCH ("foo(a \t)", "foo(a)", NORMAL);
2657 CHECK_MATCH ("foo( a )", "foo(a)", NORMAL);
2658 CHECK_MATCH ("foo(\ta\t)", "foo(a)", NORMAL);
2659 CHECK_MATCH ("foo(\t a\t )", "foo(a)", NORMAL);
2660 CHECK_MATCH ("foo( \ta \t)", "foo(a)", NORMAL);
2661 CHECK_MATCH ("foo(a)", "foo( a)", NORMAL);
2662 CHECK_MATCH ("foo(a)", "foo(a )", NORMAL);
2663 CHECK_MATCH ("foo(a)", "foo(\ta)", NORMAL);
2664 CHECK_MATCH ("foo(a)", "foo(a\t)", NORMAL);
2665 CHECK_MATCH ("foo(a)", "foo(\t a)", NORMAL);
2666 CHECK_MATCH ("foo(a)", "foo( \ta)", NORMAL);
2667 CHECK_MATCH ("foo(a)", "foo(a\t )", NORMAL);
2668 CHECK_MATCH ("foo(a)", "foo(a \t)", NORMAL);
2669 CHECK_MATCH ("foo(a)", "foo( a )", NORMAL);
2670 CHECK_MATCH ("foo(a)", "foo(\ta\t)", NORMAL);
2671 CHECK_MATCH ("foo(a)", "foo(\t a\t )", NORMAL);
2672 CHECK_MATCH ("foo(a)", "foo( \ta \t)", NORMAL);
2673 CHECK_MATCH ("foo(a,b)", "foo(a,b)", NORMAL);
2674 CHECK_MATCH ("foo(a ,b)", "foo(a,b)", NORMAL);
2675 CHECK_MATCH ("foo(a\t,b)", "foo(a,b)", NORMAL);
2676 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2677 CHECK_MATCH ("foo(a\t,\tb)", "foo(a,b)", NORMAL);
2678 CHECK_MATCH ("foo(a \t,b)", "foo(a,b)", NORMAL);
2679 CHECK_MATCH ("foo(a\t ,b)", "foo(a,b)", NORMAL);
2680 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2681 CHECK_MATCH ("foo(a, \tb)", "foo(a,b)", NORMAL);
2682 CHECK_MATCH ("foo(a,\t b)", "foo(a,b)", NORMAL);
2683 CHECK_MATCH ("foo(a,b)", "foo(a ,b)", NORMAL);
2684 CHECK_MATCH ("foo(a,b)", "foo(a\t,b)", NORMAL);
2685 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2686 CHECK_MATCH ("foo(a,b)", "foo(a\t,\tb)", NORMAL);
2687 CHECK_MATCH ("foo(a,b)", "foo(a \t,b)", NORMAL);
2688 CHECK_MATCH ("foo(a,b)", "foo(a\t ,b)", NORMAL);
2689 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2690 CHECK_MATCH ("foo(a,b)", "foo(a, \tb)", NORMAL);
2691 CHECK_MATCH ("foo(a,b)", "foo(a,\t b)", NORMAL);
2692 CHECK_MATCH ("foo(a,b,c,d)", "foo(a,b,c,d)", NORMAL);
2693 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo(a,b,c,d)", NORMAL);
2694 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo( a , b , c , d )", NORMAL);
2695 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo", NORMAL);
2696 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo&*(a b * &)", NORMAL);
2697 CHECK_MATCH ("foo(a) b", "foo(a)", NORMAL);
2698 CHECK_MATCH ("*foo(*a&)", "*foo", NORMAL);
2699 CHECK_MATCH ("*foo(*a&)", "*foo(*a&)", NORMAL);
2700 CHECK_MATCH ("*a&b#c/^d$foo(*a&)", "*a&b#c/^d$foo", NORMAL);
2701 CHECK_MATCH ("* foo", "*foo", NORMAL);
2702 CHECK_MATCH ("foo&", "foo", NORMAL);
2703 CHECK_MATCH ("foo*", "foo", NORMAL);
2704 CHECK_MATCH ("foo.", "foo", NORMAL);
2705 CHECK_MATCH ("foo->", "foo", NORMAL);
2707 CHECK_NO_MATCH ("foo", "foo(", NORMAL);
2708 CHECK_NO_MATCH ("foo", "foo()", NORMAL);
2709 CHECK_NO_MATCH ("foo", "foo(a)", NORMAL);
2710 CHECK_NO_MATCH ("foo", "foo(a)", NORMAL);
2711 CHECK_NO_MATCH ("foo", "foo*", NORMAL);
2712 CHECK_NO_MATCH ("foo", "foo (*", NORMAL);
2713 CHECK_NO_MATCH ("foo*", "foo (*", NORMAL);
2714 CHECK_NO_MATCH ("foo *", "foo (*", NORMAL);
2715 CHECK_NO_MATCH ("foo&", "foo (*", NORMAL);
2716 CHECK_NO_MATCH ("foo &", "foo (*", NORMAL);
2717 CHECK_NO_MATCH ("foo &*", "foo (&)", NORMAL);
2718 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2719 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2720 CHECK_NO_MATCH ("foo(a*) b", "foo(a) b", NORMAL);
2721 CHECK_NO_MATCH ("foo[aqi:A](a)", "foo(b)", NORMAL);
2722 CHECK_NO_MATCH ("*foo", "foo", NORMAL);
2723 CHECK_NO_MATCH ("*foo", "foo*", NORMAL);
2724 CHECK_NO_MATCH ("*foo*", "*foo&", NORMAL);
2725 CHECK_NO_MATCH ("*foo*", "foo *", NORMAL);
2726 CHECK_NO_MATCH ("&foo", "foo", NORMAL);
2727 CHECK_NO_MATCH ("&foo", "foo&", NORMAL);
2728 CHECK_NO_MATCH ("foo&", "&foo", NORMAL);
2729 CHECK_NO_MATCH ("foo", "foo&", NORMAL);
2730 CHECK_NO_MATCH ("foo", "foo*", NORMAL);
2731 CHECK_NO_MATCH ("foo", "foo.", NORMAL);
2732 CHECK_NO_MATCH ("foo", "foo->", NORMAL);
2733 CHECK_NO_MATCH ("foo bar", "foo()", NORMAL);
2734 CHECK_NO_MATCH ("foo bar", "foo bar()", NORMAL);
2735 CHECK_NO_MATCH ("foo()", "foo(a)", NORMAL);
2736 CHECK_NO_MATCH ("*(*)&", "*(*)*", NORMAL);
2737 CHECK_NO_MATCH ("foo(a)", "foo()", NORMAL);
2738 CHECK_NO_MATCH ("foo(a)", "foo(b)", NORMAL);
2739 CHECK_NO_MATCH ("foo(a,b)", "foo(a,b,c)", NORMAL);
2740 CHECK_NO_MATCH ("foo(a\\b)", "foo()", NORMAL);
2741 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar", NORMAL);
2742 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar ( a b c \td\t)\t", NORMAL);
2744 /* Test scope operator. */
2745 check_scope_operator (language_minimal);
2746 check_scope_operator (language_cplus);
2747 check_scope_operator (language_fortran);
2748 check_scope_operator (language_rust);
2750 /* Test C++ user-defined operators. */
2751 CHECK_MATCH_LANG ("operator foo(int&)", "operator foo(int &)", NORMAL,
2752 language_cplus);
2753 CHECK_MATCH_LANG ("operator foo(int &)", "operator foo(int &)", NORMAL,
2754 language_cplus);
2755 CHECK_MATCH_LANG ("operator foo(int\t&)", "operator foo(int\t&)", NORMAL,
2756 language_cplus);
2757 CHECK_MATCH_LANG ("operator foo (int)", "operator foo(int)", NORMAL,
2758 language_cplus);
2759 CHECK_MATCH_LANG ("operator foo\t(int)", "operator foo(int)", NORMAL,
2760 language_cplus);
2761 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo(int)", NORMAL,
2762 language_cplus);
2763 CHECK_MATCH_LANG ("operator foo (int)", "operator foo \t(int)", NORMAL,
2764 language_cplus);
2765 CHECK_MATCH_LANG ("operator foo\t(int)", "operator foo \t(int)", NORMAL,
2766 language_cplus);
2767 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo \t(int)", NORMAL,
2768 language_cplus);
2770 CHECK_MATCH_LANG ("a::operator foo(int&)", "a::operator foo(int &)", NORMAL,
2771 language_cplus);
2772 CHECK_MATCH_LANG ("a :: operator foo(int &)", "a::operator foo(int &)", NORMAL,
2773 language_cplus);
2774 CHECK_MATCH_LANG ("a \t:: \toperator foo(int\t&)", "a::operator foo(int\t&)", NORMAL,
2775 language_cplus);
2776 CHECK_MATCH_LANG ("a::operator foo (int)", "a::operator foo(int)", NORMAL,
2777 language_cplus);
2778 CHECK_MATCH_LANG ("a::operator foo\t(int)", "a::operator foo(int)", NORMAL,
2779 language_cplus);
2780 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo(int)", NORMAL,
2781 language_cplus);
2782 CHECK_MATCH_LANG ("a::operator foo (int)", "a::operator foo \t(int)", NORMAL,
2783 language_cplus);
2784 CHECK_MATCH_LANG ("a::operator foo\t(int)", "a::operator foo \t(int)", NORMAL,
2785 language_cplus);
2786 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo \t(int)", NORMAL,
2787 language_cplus);
2789 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(char)", NORMAL,
2790 language_cplus);
2791 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int *)", NORMAL,
2792 language_cplus);
2793 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int &)", NORMAL,
2794 language_cplus);
2795 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int, char *)", NORMAL,
2796 language_cplus);
2797 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator bar(int)", NORMAL,
2798 language_cplus);
2800 CHECK_NO_MATCH_LANG ("a::operator b::foo(int)", "a::operator a::foo(char)", NORMAL,
2801 language_cplus);
2802 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int *)", NORMAL,
2803 language_cplus);
2804 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int &)", NORMAL,
2805 language_cplus);
2806 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int, char *)", NORMAL,
2807 language_cplus);
2808 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator bar(int)", NORMAL,
2809 language_cplus);
2811 /* Skip "[abi:cxx11]" tags in the symbol name if the lookup name
2812 doesn't include them. These are not language-specific in
2813 strncmp_iw_with_mode. */
2815 CHECK_MATCH ("foo[abi:a]", "foo", NORMAL);
2816 CHECK_MATCH ("foo[abi:a]()", "foo", NORMAL);
2817 CHECK_MATCH ("foo[abi:a](a)", "foo", NORMAL);
2818 CHECK_MATCH ("foo[abi:a](a&,b*)", "foo", NORMAL);
2819 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2820 CHECK_MATCH ("foo[abi:a](a,b) c", "foo(a,b) c", NORMAL);
2821 CHECK_MATCH ("foo[abi:a](a)", "foo(a)", NORMAL);
2822 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2823 CHECK_MATCH ("foo[abi:a]", "foo[abi:a]", NORMAL);
2824 CHECK_MATCH ("foo[ abi:a]", "foo[abi:a]", NORMAL);
2825 CHECK_MATCH ("foo[\tabi:a]", "foo[abi:a]", NORMAL);
2826 CHECK_MATCH ("foo[ \tabi:a]", "foo[abi:a]", NORMAL);
2827 CHECK_MATCH ("foo[\t abi:a]", "foo[abi:a]", NORMAL);
2828 CHECK_MATCH ("foo[abi :a]", "foo[abi:a]", NORMAL);
2829 CHECK_MATCH ("foo[abi\t:a]", "foo[abi:a]", NORMAL);
2830 CHECK_MATCH ("foo[abi \t:a]", "foo[abi:a]", NORMAL);
2831 CHECK_MATCH ("foo[abi\t :a]", "foo[abi:a]", NORMAL);
2832 CHECK_MATCH ("foo[abi:a]", "foo[ abi:a]", NORMAL);
2833 CHECK_MATCH ("foo[abi:a]", "foo[\tabi:a]", NORMAL);
2834 CHECK_MATCH ("foo[abi:a]", "foo[ \tabi:a]", NORMAL);
2835 CHECK_MATCH ("foo[abi:a]", "foo[\t abi:a]", NORMAL);
2836 CHECK_MATCH ("foo[abi:a]", "foo[abi :a]", NORMAL);
2837 CHECK_MATCH ("foo[abi:a]", "foo[abi\t:a]", NORMAL);
2838 CHECK_MATCH ("foo[abi:a]", "foo[abi \t:a]", NORMAL);
2839 CHECK_MATCH ("foo[abi:a]", "foo[abi\t :a]", NORMAL);
2840 CHECK_MATCH ("foo[abi:a]", "foo[abi:a ]", NORMAL);
2841 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t]", NORMAL);
2842 CHECK_MATCH ("foo[abi:a]", "foo[abi:a \t]", NORMAL);
2843 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t ]", NORMAL);
2844 CHECK_MATCH ("foo[abi:a,b]", "foo[abi:a,b]", NORMAL);
2845 CHECK_MATCH ("foo[abi:::]", "foo[abi:::]", NORMAL);
2846 CHECK_MATCH ("foo[abi : : : ]", "foo[abi:::]", NORMAL);
2847 CHECK_MATCH ("foo[abi:::]", "foo[abi : : : ]", NORMAL);
2848 CHECK_MATCH ("foo[ \t abi \t:\t: : \t]",
2849 "foo[ abi : \t ::]",
2850 NORMAL);
2851 CHECK_MATCH ("foo< bar< baz< quxi > > >(int)", "foo<bar<baz<quxi>>>(int)",
2852 NORMAL);
2853 CHECK_MATCH ("\tfoo<\tbar<\tbaz\t<\tquxi\t>\t>\t>(int)",
2854 "foo<bar<baz<quxi>>>(int)", NORMAL);
2855 CHECK_MATCH (" \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)",
2856 "foo<bar<baz<quxi>>>(int)", NORMAL);
2857 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2858 "foo < bar < baz < quxi > > > (int)", NORMAL);
2859 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2860 "\tfoo\t<\tbar\t<\tbaz\t<\tquxi\t>\t>\t>\t(int)", NORMAL);
2861 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2862 " \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)", NORMAL);
2863 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "fo", NORMAL);
2864 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo", NORMAL);
2865 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz>>::", NORMAL);
2866 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz> >::foo", NORMAL);
2867 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
2868 NORMAL);
2869 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", NORMAL);
2870 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar)", NORMAL);
2871 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar)", NORMAL);
2872 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar[abi:c])", NORMAL);
2873 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar[abi:c])", NORMAL);
2874 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar)", NORMAL);
2875 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c])",
2876 NORMAL);
2877 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo", NORMAL);
2878 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo()", NORMAL);
2879 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>", NORMAL);
2880 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz)", NORMAL);
2881 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:b])",
2882 NORMAL);
2883 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:A])",
2884 NORMAL);
2885 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz)",
2886 NORMAL);
2887 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:A]>(char*, baz)",
2888 NORMAL);
2889 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz[abi:b])",
2890 NORMAL);
2891 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])",
2892 "foo<bar[abi:a]>(char*, baz[abi:B])", NORMAL);
2894 CHECK_NO_MATCH ("foo", "foo[", NORMAL);
2895 CHECK_NO_MATCH ("foo", "foo[]", NORMAL);
2896 CHECK_NO_MATCH ("foo", "foo[ a]", NORMAL);
2897 CHECK_NO_MATCH ("foo", "foo[a ]", NORMAL);
2898 CHECK_NO_MATCH ("foo", "foo[ a ]", NORMAL);
2899 CHECK_NO_MATCH ("foo", "foo[\ta]", NORMAL);
2900 CHECK_NO_MATCH ("foo", "foo[a \t]", NORMAL);
2901 CHECK_NO_MATCH ("foo", "foo[a\t ]", NORMAL);
2902 CHECK_NO_MATCH ("foo", "foo[ \ta]", NORMAL);
2903 CHECK_NO_MATCH ("foo", "foo[\t a]", NORMAL);
2904 CHECK_NO_MATCH ("foo", "foo[ \ta \t]", NORMAL);
2905 CHECK_NO_MATCH ("foo", "foo[\t a\t ]", NORMAL);
2906 CHECK_NO_MATCH ("foo", "foo[abi]", NORMAL);
2907 CHECK_NO_MATCH ("foo", "foo[ abi]", NORMAL);
2908 CHECK_NO_MATCH ("foo", "foo[abi ]", NORMAL);
2909 CHECK_NO_MATCH ("foo", "foo[\tabi]", NORMAL);
2910 CHECK_NO_MATCH ("foo", "foo[abi\t]", NORMAL);
2911 CHECK_NO_MATCH ("foo", "foo[ \tabi]", NORMAL);
2912 CHECK_NO_MATCH ("foo", "foo[\t abi]", NORMAL);
2913 CHECK_NO_MATCH ("foo", "foo[abi \t]", NORMAL);
2914 CHECK_NO_MATCH ("foo", "foo[abi\t ]", NORMAL);
2915 CHECK_NO_MATCH ("foo", "foo[abi :]", NORMAL);
2916 CHECK_NO_MATCH ("foo", "foo[abi\t:]", NORMAL);
2917 CHECK_NO_MATCH ("foo", "foo[abi \t:]", NORMAL);
2918 CHECK_NO_MATCH ("foo", "foo[abi\t :]", NORMAL);
2919 CHECK_NO_MATCH ("foo", "foo[abi: ]", NORMAL);
2920 CHECK_NO_MATCH ("foo", "foo[abi:\t]", NORMAL);
2921 CHECK_NO_MATCH ("foo", "foo[abi: \t]", NORMAL);
2922 CHECK_NO_MATCH ("foo", "foo[abi:\t ]", NORMAL);
2923 CHECK_NO_MATCH ("foo", "foo[abi: a]", NORMAL);
2924 CHECK_NO_MATCH ("foo", "foo[abi:\ta]", NORMAL);
2925 CHECK_NO_MATCH ("foo", "foo[abi: \ta]", NORMAL);
2926 CHECK_NO_MATCH ("foo", "foo[abi:\t a]", NORMAL);
2927 CHECK_NO_MATCH ("foo", "foo[abi:a ]", NORMAL);
2928 CHECK_NO_MATCH ("foo", "foo[abi:a\t]", NORMAL);
2929 CHECK_NO_MATCH ("foo", "foo[abi:a \t]", NORMAL);
2930 CHECK_NO_MATCH ("foo", "foo[abi:a\t ]", NORMAL);
2931 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2932 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2933 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2934 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2935 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) c", NORMAL);
2936 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) .", NORMAL);
2937 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) *", NORMAL);
2938 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) &", NORMAL);
2939 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) c", NORMAL);
2940 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) .", NORMAL);
2941 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) *", NORMAL);
2942 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) &", NORMAL);
2943 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)c", NORMAL);
2944 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b).", NORMAL);
2945 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)*", NORMAL);
2946 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)&", NORMAL);
2947 CHECK_NO_MATCH ("foo[abi:a](a,b) d", "foo(a,b) c", NORMAL);
2948 CHECK_NO_MATCH ("foo[abi:a](a)", "foo()", NORMAL);
2949 CHECK_NO_MATCH ("foo[abi:a](a)", "foo(b)", NORMAL);
2950 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:b](a)", NORMAL);
2951 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:a](b)", NORMAL);
2952 CHECK_NO_MATCH ("foo[abi:]", "foo[abi:a]", NORMAL);
2953 CHECK_NO_MATCH ("foo[abi:", "foo[abi:a]", NORMAL);
2954 CHECK_NO_MATCH ("foo[abi:]", "foo[abi:a", NORMAL);
2955 CHECK_NO_MATCH ("foo[abi:,]", "foo[abi:a]", NORMAL);
2956 CHECK_NO_MATCH ("foo[abi:a,b]", "foo[abi:a]", NORMAL);
2957 CHECK_NO_MATCH ("foo[abi::a]", "foo[abi:a]", NORMAL);
2958 CHECK_NO_MATCH ("foo[abi:,([a]", "foo[abi:a]", NORMAL);
2960 CHECK_MATCH ("foo <a, b [, c (", "foo", NORMAL);
2961 CHECK_MATCH ("foo >a, b ], c )", "foo", NORMAL);
2962 CHECK_MATCH ("@!%&\\*", "@!%&\\*", NORMAL);
2963 CHECK_MATCH ("()", "()", NORMAL);
2964 CHECK_MATCH ("*(*)*", "*(*)*", NORMAL);
2965 CHECK_MATCH ("[]", "[]", NORMAL);
2966 CHECK_MATCH ("<>", "<>", NORMAL);
2968 /* strncmp_iw_with_mode::MATCH_PARAMS: the "strcmp_iw hack." */
2969 CHECK_MATCH ("foo2", "foo", NORMAL);
2970 CHECK_NO_MATCH ("foo2", "foo", MATCH_PARAMS);
2971 CHECK_NO_MATCH ("foo2", "foo ", MATCH_PARAMS);
2972 CHECK_NO_MATCH ("foo2", "foo\t", MATCH_PARAMS);
2973 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2974 CHECK_NO_MATCH ("foo2", "foo\t ", MATCH_PARAMS);
2975 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2976 CHECK_NO_MATCH ("foo2", " foo", MATCH_PARAMS);
2977 CHECK_NO_MATCH ("foo2", "\tfoo", MATCH_PARAMS);
2978 CHECK_NO_MATCH ("foo2", " \tfoo", MATCH_PARAMS);
2979 CHECK_NO_MATCH ("foo2", "\t foo", MATCH_PARAMS);
2980 CHECK_NO_MATCH (" foo2", "foo", MATCH_PARAMS);
2981 CHECK_NO_MATCH ("\tfoo2", "foo", MATCH_PARAMS);
2982 CHECK_NO_MATCH (" \tfoo2", "foo", MATCH_PARAMS);
2983 CHECK_NO_MATCH ("\t foo2", "foo", MATCH_PARAMS);
2984 CHECK_NO_MATCH (" foo2 ", " foo ", MATCH_PARAMS);
2985 CHECK_NO_MATCH ("\tfoo2\t", "\tfoo\t", MATCH_PARAMS);
2986 CHECK_NO_MATCH (" \tfoo2 \t", " \tfoo \t", MATCH_PARAMS);
2987 CHECK_NO_MATCH ("\t foo2\t ", "\t foo\t ", MATCH_PARAMS);
2988 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
2989 CHECK_NO_MATCH ("foo2\t", "foo", MATCH_PARAMS);
2990 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
2991 CHECK_NO_MATCH ("foo2 \t", "foo", MATCH_PARAMS);
2992 CHECK_NO_MATCH ("foo2\t ", "foo", MATCH_PARAMS);
2993 CHECK_NO_MATCH ("foo2 (args)", "foo", MATCH_PARAMS);
2994 CHECK_NO_MATCH ("foo2 (args)", "foo", MATCH_PARAMS);
2995 CHECK_NO_MATCH ("foo2\t(args)", "foo", MATCH_PARAMS);
2996 CHECK_NO_MATCH ("foo2 \t(args)", "foo", MATCH_PARAMS);
2997 CHECK_NO_MATCH ("foo2\t (args)", "foo", MATCH_PARAMS);
2998 CHECK_NO_MATCH ("foo2 ( args)", "foo", MATCH_PARAMS);
2999 CHECK_NO_MATCH ("foo2(args )", "foo", MATCH_PARAMS);
3000 CHECK_NO_MATCH ("foo2(args\t)", "foo", MATCH_PARAMS);
3001 CHECK_NO_MATCH ("foo2 (args \t)", "foo", MATCH_PARAMS);
3002 CHECK_NO_MATCH ("foo2 (args\t )", "foo", MATCH_PARAMS);
3003 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
3004 MATCH_PARAMS);
3005 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", MATCH_PARAMS);
3006 CHECK_NO_MATCH ("foo(args)@plt", "foo", MATCH_PARAMS);
3007 CHECK_NO_MATCH ("foo((())args(()))@plt", "foo", MATCH_PARAMS);
3008 CHECK_MATCH ("foo((())args(()))", "foo", MATCH_PARAMS);
3009 CHECK_MATCH ("foo(args) const", "foo", MATCH_PARAMS);
3010 CHECK_MATCH ("foo(args)const", "foo", MATCH_PARAMS);
3012 /* strncmp_iw_with_mode also supports case insensitivity. */
3014 CHECK_NO_MATCH ("FoO", "foo", NORMAL);
3015 CHECK_NO_MATCH ("FoO", "foo", MATCH_PARAMS);
3017 scoped_restore restore_case = make_scoped_restore (&case_sensitivity);
3018 case_sensitivity = case_sensitive_off;
3020 CHECK_MATCH ("FoO", "foo", NORMAL);
3021 CHECK_MATCH ("FoO", "foo", MATCH_PARAMS);
3022 CHECK_MATCH ("foo", "FoO", NORMAL);
3023 CHECK_MATCH ("foo", "FoO", MATCH_PARAMS);
3025 CHECK_MATCH ("FoO[AbI:abC]()", "foo", NORMAL);
3026 CHECK_NO_MATCH ("FoO[AbI:abC]()", "foo", MATCH_PARAMS);
3027 CHECK_MATCH ("FoO2[AbI:abC]()", "foo", NORMAL);
3028 CHECK_NO_MATCH ("FoO2[AbI:abC]()", "foo", MATCH_PARAMS);
3030 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:abC]()", NORMAL);
3031 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:AbC]()", MATCH_PARAMS);
3032 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3033 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", MATCH_PARAMS);
3034 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3035 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)",
3036 MATCH_PARAMS);
3037 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3038 NORMAL);
3039 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3040 MATCH_PARAMS);
3044 #undef MATCH
3045 #undef NO_MATCH
3046 #endif
3048 /* See utils.h. */
3051 strncmp_iw (const char *string1, const char *string2, size_t string2_len)
3053 return strncmp_iw_with_mode (string1, string2, string2_len,
3054 strncmp_iw_mode::NORMAL, language_minimal);
3057 /* See utils.h. */
3060 strcmp_iw (const char *string1, const char *string2)
3062 return strncmp_iw_with_mode (string1, string2, strlen (string2),
3063 strncmp_iw_mode::MATCH_PARAMS, language_minimal);
3066 /* This is like strcmp except that it ignores whitespace and treats
3067 '(' as the first non-NULL character in terms of ordering. Like
3068 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
3069 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
3070 according to that ordering.
3072 If a list is sorted according to this function and if you want to
3073 find names in the list that match some fixed NAME according to
3074 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
3075 where this function would put NAME.
3077 This function must be neutral to the CASE_SENSITIVITY setting as the user
3078 may choose it during later lookup. Therefore this function always sorts
3079 primarily case-insensitively and secondarily case-sensitively.
3081 Here are some examples of why using strcmp to sort is a bad idea:
3083 Whitespace example:
3085 Say your partial symtab contains: "foo<char *>", "goo". Then, if
3086 we try to do a search for "foo<char*>", strcmp will locate this
3087 after "foo<char *>" and before "goo". Then lookup_partial_symbol
3088 will start looking at strings beginning with "goo", and will never
3089 see the correct match of "foo<char *>".
3091 Parenthesis example:
3093 In practice, this is less like to be an issue, but I'll give it a
3094 shot. Let's assume that '$' is a legitimate character to occur in
3095 symbols. (Which may well even be the case on some systems.) Then
3096 say that the partial symbol table contains "foo$" and "foo(int)".
3097 strcmp will put them in this order, since '$' < '('. Now, if the
3098 user searches for "foo", then strcmp will sort "foo" before "foo$".
3099 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
3100 "foo") is false, so it won't proceed to the actual match of
3101 "foo(int)" with "foo". */
3104 strcmp_iw_ordered (const char *string1, const char *string2)
3106 const char *saved_string1 = string1, *saved_string2 = string2;
3107 enum case_sensitivity case_pass = case_sensitive_off;
3109 for (;;)
3111 /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
3112 Provide stub characters if we are already at the end of one of the
3113 strings. */
3114 char c1 = 'X', c2 = 'X';
3116 while (*string1 != '\0' && *string2 != '\0')
3118 while (ISSPACE (*string1))
3119 string1++;
3120 while (ISSPACE (*string2))
3121 string2++;
3123 switch (case_pass)
3125 case case_sensitive_off:
3126 c1 = TOLOWER ((unsigned char) *string1);
3127 c2 = TOLOWER ((unsigned char) *string2);
3128 break;
3129 case case_sensitive_on:
3130 c1 = *string1;
3131 c2 = *string2;
3132 break;
3134 if (c1 != c2)
3135 break;
3137 if (*string1 != '\0')
3139 string1++;
3140 string2++;
3144 switch (*string1)
3146 /* Characters are non-equal unless they're both '\0'; we want to
3147 make sure we get the comparison right according to our
3148 comparison in the cases where one of them is '\0' or '('. */
3149 case '\0':
3150 if (*string2 == '\0')
3151 break;
3152 else
3153 return -1;
3154 case '(':
3155 if (*string2 == '\0')
3156 return 1;
3157 else
3158 return -1;
3159 default:
3160 if (*string2 == '\0' || *string2 == '(')
3161 return 1;
3162 else if (c1 > c2)
3163 return 1;
3164 else if (c1 < c2)
3165 return -1;
3166 /* PASSTHRU */
3169 if (case_pass == case_sensitive_on)
3170 return 0;
3172 /* Otherwise the strings were equal in case insensitive way, make
3173 a more fine grained comparison in a case sensitive way. */
3175 case_pass = case_sensitive_on;
3176 string1 = saved_string1;
3177 string2 = saved_string2;
3183 static void
3184 show_debug_timestamp (struct ui_file *file, int from_tty,
3185 struct cmd_list_element *c, const char *value)
3187 gdb_printf (file, _("Timestamping debugging messages is %s.\n"),
3188 value);
3192 const char *
3193 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
3195 /* Truncate address to the size of a target address, avoiding shifts
3196 larger or equal than the width of a CORE_ADDR. The local
3197 variable ADDR_BIT stops the compiler reporting a shift overflow
3198 when it won't occur. */
3199 /* NOTE: This assumes that the significant address information is
3200 kept in the least significant bits of ADDR - the upper bits were
3201 either zero or sign extended. Should gdbarch_address_to_pointer or
3202 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
3204 int addr_bit = gdbarch_addr_bit (gdbarch);
3206 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3207 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
3208 return hex_string (addr);
3211 /* This function is described in "defs.h". */
3213 const char *
3214 print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
3216 int addr_bit = gdbarch_addr_bit (gdbarch);
3218 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3219 address &= ((CORE_ADDR) 1 << addr_bit) - 1;
3221 /* FIXME: cagney/2002-05-03: Need local_address_string() function
3222 that returns the language localized string formatted to a width
3223 based on gdbarch_addr_bit. */
3224 if (addr_bit <= 32)
3225 return hex_string_custom (address, 8);
3226 else
3227 return hex_string_custom (address, 16);
3230 /* Convert a string back into a CORE_ADDR. */
3231 CORE_ADDR
3232 string_to_core_addr (const char *my_string)
3234 CORE_ADDR addr = 0;
3236 if (my_string[0] == '0' && TOLOWER (my_string[1]) == 'x')
3238 /* Assume that it is in hex. */
3239 int i;
3241 for (i = 2; my_string[i] != '\0'; i++)
3243 if (ISDIGIT (my_string[i]))
3244 addr = (my_string[i] - '0') + (addr * 16);
3245 else if (ISXDIGIT (my_string[i]))
3246 addr = (TOLOWER (my_string[i]) - 'a' + 0xa) + (addr * 16);
3247 else
3248 error (_("invalid hex \"%s\""), my_string);
3251 else
3253 /* Assume that it is in decimal. */
3254 int i;
3256 for (i = 0; my_string[i] != '\0'; i++)
3258 if (ISDIGIT (my_string[i]))
3259 addr = (my_string[i] - '0') + (addr * 10);
3260 else
3261 error (_("invalid decimal \"%s\""), my_string);
3265 return addr;
3268 #if GDB_SELF_TEST
3270 static void
3271 gdb_realpath_check_trailer (const char *input, const char *trailer)
3273 gdb::unique_xmalloc_ptr<char> result = gdb_realpath (input);
3275 size_t len = strlen (result.get ());
3276 size_t trail_len = strlen (trailer);
3278 SELF_CHECK (len >= trail_len
3279 && strcmp (result.get () + len - trail_len, trailer) == 0);
3282 static void
3283 gdb_realpath_tests ()
3285 /* A file which contains a directory prefix. */
3286 gdb_realpath_check_trailer ("./xfullpath.exp", "/xfullpath.exp");
3287 /* A file which contains a directory prefix. */
3288 gdb_realpath_check_trailer ("../../defs.h", "/defs.h");
3289 /* A one-character filename. */
3290 gdb_realpath_check_trailer ("./a", "/a");
3291 /* A file in the root directory. */
3292 gdb_realpath_check_trailer ("/root_file_which_should_exist",
3293 "/root_file_which_should_exist");
3294 /* A file which does not have a directory prefix. */
3295 gdb_realpath_check_trailer ("xfullpath.exp", "xfullpath.exp");
3296 /* A one-char filename without any directory prefix. */
3297 gdb_realpath_check_trailer ("a", "a");
3298 /* An empty filename. */
3299 gdb_realpath_check_trailer ("", "");
3302 /* Test the gdb_argv::as_array_view method. */
3304 static void
3305 gdb_argv_as_array_view_test ()
3308 gdb_argv argv;
3310 gdb::array_view<char *> view = argv.as_array_view ();
3312 SELF_CHECK (view.data () == nullptr);
3313 SELF_CHECK (view.size () == 0);
3316 gdb_argv argv ("une bonne 50");
3318 gdb::array_view<char *> view = argv.as_array_view ();
3320 SELF_CHECK (view.size () == 3);
3321 SELF_CHECK (strcmp (view[0], "une") == 0);
3322 SELF_CHECK (strcmp (view[1], "bonne") == 0);
3323 SELF_CHECK (strcmp (view[2], "50") == 0);
3327 #endif /* GDB_SELF_TEST */
3329 /* Simple, portable version of dirname that does not modify its
3330 argument. */
3332 std::string
3333 ldirname (const char *filename)
3335 std::string dirname;
3336 const char *base = lbasename (filename);
3338 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3339 --base;
3341 if (base == filename)
3342 return dirname;
3344 dirname = std::string (filename, base - filename);
3346 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3347 create "d:./bar" later instead of the (different) "d:/bar". */
3348 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3349 && !IS_DIR_SEPARATOR (filename[0]))
3350 dirname[base++ - filename] = '.';
3352 return dirname;
3355 /* Return ARGS parsed as a valid pid, or throw an error. */
3358 parse_pid_to_attach (const char *args)
3360 unsigned long pid;
3361 char *dummy;
3363 if (!args)
3364 error_no_arg (_("process-id to attach"));
3366 dummy = (char *) args;
3367 pid = strtoul (args, &dummy, 0);
3368 /* Some targets don't set errno on errors, grrr! */
3369 if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3370 error (_("Illegal process-id: %s."), args);
3372 return pid;
3375 /* Substitute all occurrences of string FROM by string TO in *STRINGP. *STRINGP
3376 must come from xrealloc-compatible allocator and it may be updated. FROM
3377 needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
3378 located at the start or end of *STRINGP. */
3380 void
3381 substitute_path_component (char **stringp, const char *from, const char *to)
3383 char *string = *stringp, *s;
3384 const size_t from_len = strlen (from);
3385 const size_t to_len = strlen (to);
3387 for (s = string;;)
3389 s = strstr (s, from);
3390 if (s == NULL)
3391 break;
3393 if ((s == string || IS_DIR_SEPARATOR (s[-1])
3394 || s[-1] == DIRNAME_SEPARATOR)
3395 && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
3396 || s[from_len] == DIRNAME_SEPARATOR))
3398 char *string_new;
3400 string_new
3401 = (char *) xrealloc (string, (strlen (string) + to_len + 1));
3403 /* Relocate the current S pointer. */
3404 s = s - string + string_new;
3405 string = string_new;
3407 /* Replace from by to. */
3408 memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
3409 memcpy (s, to, to_len);
3411 s += to_len;
3413 else
3414 s++;
3417 *stringp = string;
3420 #ifdef HAVE_WAITPID
3422 #ifdef SIGALRM
3424 /* SIGALRM handler for waitpid_with_timeout. */
3426 static void
3427 sigalrm_handler (int signo)
3429 /* Nothing to do. */
3432 #endif
3434 /* Wrapper to wait for child PID to die with TIMEOUT.
3435 TIMEOUT is the time to stop waiting in seconds.
3436 If TIMEOUT is zero, pass WNOHANG to waitpid.
3437 Returns PID if it was successfully waited for, otherwise -1.
3439 Timeouts are currently implemented with alarm and SIGALRM.
3440 If the host does not support them, this waits "forever".
3441 It would be odd though for a host to have waitpid and not SIGALRM. */
3443 pid_t
3444 wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3446 pid_t waitpid_result;
3448 gdb_assert (pid > 0);
3449 gdb_assert (timeout >= 0);
3451 if (timeout > 0)
3453 #ifdef SIGALRM
3454 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3455 struct sigaction sa, old_sa;
3457 sa.sa_handler = sigalrm_handler;
3458 sigemptyset (&sa.sa_mask);
3459 sa.sa_flags = 0;
3460 sigaction (SIGALRM, &sa, &old_sa);
3461 #else
3462 sighandler_t ofunc;
3464 ofunc = signal (SIGALRM, sigalrm_handler);
3465 #endif
3467 alarm (timeout);
3468 #endif
3470 waitpid_result = waitpid (pid, status, 0);
3472 #ifdef SIGALRM
3473 alarm (0);
3474 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3475 sigaction (SIGALRM, &old_sa, NULL);
3476 #else
3477 signal (SIGALRM, ofunc);
3478 #endif
3479 #endif
3481 else
3482 waitpid_result = waitpid (pid, status, WNOHANG);
3484 if (waitpid_result == pid)
3485 return pid;
3486 else
3487 return -1;
3490 #endif /* HAVE_WAITPID */
3492 /* Provide fnmatch compatible function for FNM_FILE_NAME matching of host files.
3493 Both FNM_FILE_NAME and FNM_NOESCAPE must be set in FLAGS.
3495 It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3496 HAVE_CASE_INSENSITIVE_FILE_SYSTEM. */
3499 gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3501 gdb_assert ((flags & FNM_FILE_NAME) != 0);
3503 /* It is unclear how '\' escaping vs. directory separator should coexist. */
3504 gdb_assert ((flags & FNM_NOESCAPE) != 0);
3506 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3508 char *pattern_slash, *string_slash;
3510 /* Replace '\' by '/' in both strings. */
3512 pattern_slash = (char *) alloca (strlen (pattern) + 1);
3513 strcpy (pattern_slash, pattern);
3514 pattern = pattern_slash;
3515 for (; *pattern_slash != 0; pattern_slash++)
3516 if (IS_DIR_SEPARATOR (*pattern_slash))
3517 *pattern_slash = '/';
3519 string_slash = (char *) alloca (strlen (string) + 1);
3520 strcpy (string_slash, string);
3521 string = string_slash;
3522 for (; *string_slash != 0; string_slash++)
3523 if (IS_DIR_SEPARATOR (*string_slash))
3524 *string_slash = '/';
3526 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3528 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3529 flags |= FNM_CASEFOLD;
3530 #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3532 return fnmatch (pattern, string, flags);
3535 /* Return the number of path elements in PATH.
3536 / = 1
3537 /foo = 2
3538 /foo/ = 2
3539 foo/bar = 2
3540 foo/ = 1 */
3543 count_path_elements (const char *path)
3545 int count = 0;
3546 const char *p = path;
3548 if (HAS_DRIVE_SPEC (p))
3550 p = STRIP_DRIVE_SPEC (p);
3551 ++count;
3554 while (*p != '\0')
3556 if (IS_DIR_SEPARATOR (*p))
3557 ++count;
3558 ++p;
3561 /* Backup one if last character is /, unless it's the only one. */
3562 if (p > path + 1 && IS_DIR_SEPARATOR (p[-1]))
3563 --count;
3565 /* Add one for the file name, if present. */
3566 if (p > path && !IS_DIR_SEPARATOR (p[-1]))
3567 ++count;
3569 return count;
3572 /* Remove N leading path elements from PATH.
3573 N must be non-negative.
3574 If PATH has more than N path elements then return NULL.
3575 If PATH has exactly N path elements then return "".
3576 See count_path_elements for a description of how we do the counting. */
3578 const char *
3579 strip_leading_path_elements (const char *path, int n)
3581 int i = 0;
3582 const char *p = path;
3584 gdb_assert (n >= 0);
3586 if (n == 0)
3587 return p;
3589 if (HAS_DRIVE_SPEC (p))
3591 p = STRIP_DRIVE_SPEC (p);
3592 ++i;
3595 while (i < n)
3597 while (*p != '\0' && !IS_DIR_SEPARATOR (*p))
3598 ++p;
3599 if (*p == '\0')
3601 if (i + 1 == n)
3602 return "";
3603 return NULL;
3605 ++p;
3606 ++i;
3609 return p;
3612 /* See utils.h. */
3614 void
3615 copy_bitwise (gdb_byte *dest, ULONGEST dest_offset,
3616 const gdb_byte *source, ULONGEST source_offset,
3617 ULONGEST nbits, int bits_big_endian)
3619 unsigned int buf, avail;
3621 if (nbits == 0)
3622 return;
3624 if (bits_big_endian)
3626 /* Start from the end, then work backwards. */
3627 dest_offset += nbits - 1;
3628 dest += dest_offset / 8;
3629 dest_offset = 7 - dest_offset % 8;
3630 source_offset += nbits - 1;
3631 source += source_offset / 8;
3632 source_offset = 7 - source_offset % 8;
3634 else
3636 dest += dest_offset / 8;
3637 dest_offset %= 8;
3638 source += source_offset / 8;
3639 source_offset %= 8;
3642 /* Fill BUF with DEST_OFFSET bits from the destination and 8 -
3643 SOURCE_OFFSET bits from the source. */
3644 buf = *(bits_big_endian ? source-- : source++) >> source_offset;
3645 buf <<= dest_offset;
3646 buf |= *dest & ((1 << dest_offset) - 1);
3648 /* NBITS: bits yet to be written; AVAIL: BUF's fill level. */
3649 nbits += dest_offset;
3650 avail = dest_offset + 8 - source_offset;
3652 /* Flush 8 bits from BUF, if appropriate. */
3653 if (nbits >= 8 && avail >= 8)
3655 *(bits_big_endian ? dest-- : dest++) = buf;
3656 buf >>= 8;
3657 avail -= 8;
3658 nbits -= 8;
3661 /* Copy the middle part. */
3662 if (nbits >= 8)
3664 size_t len = nbits / 8;
3666 /* Use a faster method for byte-aligned copies. */
3667 if (avail == 0)
3669 if (bits_big_endian)
3671 dest -= len;
3672 source -= len;
3673 memcpy (dest + 1, source + 1, len);
3675 else
3677 memcpy (dest, source, len);
3678 dest += len;
3679 source += len;
3682 else
3684 while (len--)
3686 buf |= *(bits_big_endian ? source-- : source++) << avail;
3687 *(bits_big_endian ? dest-- : dest++) = buf;
3688 buf >>= 8;
3691 nbits %= 8;
3694 /* Write the last byte. */
3695 if (nbits)
3697 if (avail < nbits)
3698 buf |= *source << avail;
3700 buf &= (1 << nbits) - 1;
3701 *dest = (*dest & (~0U << nbits)) | buf;
3705 #if GDB_SELF_TEST
3706 static void
3707 test_assign_set_return_if_changed ()
3709 bool changed;
3710 int a;
3712 for (bool initial : { false, true })
3714 changed = initial;
3715 a = 1;
3716 assign_set_if_changed (a, 1, changed);
3717 SELF_CHECK (a == 1);
3718 SELF_CHECK (changed == initial);
3721 for (bool initial : { false, true })
3723 changed = initial;
3724 a = 1;
3725 assign_set_if_changed (a, 2, changed);
3726 SELF_CHECK (a == 2);
3727 SELF_CHECK (changed == true);
3730 a = 1;
3731 changed = assign_return_if_changed (a, 1);
3732 SELF_CHECK (a == 1);
3733 SELF_CHECK (changed == false);
3735 a = 1;
3736 assign_set_if_changed (a, 2, changed);
3737 SELF_CHECK (a == 2);
3738 SELF_CHECK (changed == true);
3740 #endif
3742 void _initialize_utils ();
3743 void
3744 _initialize_utils ()
3746 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
3747 Set number of characters where GDB should wrap lines of its output."), _("\
3748 Show number of characters where GDB should wrap lines of its output."), _("\
3749 This affects where GDB wraps its output to fit the screen width.\n\
3750 Setting this to \"unlimited\" or zero prevents GDB from wrapping its output."),
3751 set_width_command,
3752 show_chars_per_line,
3753 &setlist, &showlist);
3755 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
3756 Set number of lines in a page for GDB output pagination."), _("\
3757 Show number of lines in a page for GDB output pagination."), _("\
3758 This affects the number of lines after which GDB will pause\n\
3759 its output and ask you whether to continue.\n\
3760 Setting this to \"unlimited\" or zero causes GDB never pause during output."),
3761 set_height_command,
3762 show_lines_per_page,
3763 &setlist, &showlist);
3765 add_setshow_boolean_cmd ("pagination", class_support,
3766 &pagination_enabled, _("\
3767 Set state of GDB output pagination."), _("\
3768 Show state of GDB output pagination."), _("\
3769 When pagination is ON, GDB pauses at end of each screenful of\n\
3770 its output and asks you whether to continue.\n\
3771 Turning pagination off is an alternative to \"set height unlimited\"."),
3772 NULL,
3773 show_pagination_enabled,
3774 &setlist, &showlist);
3776 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
3777 &sevenbit_strings, _("\
3778 Set printing of 8-bit characters in strings as \\nnn."), _("\
3779 Show printing of 8-bit characters in strings as \\nnn."), NULL,
3780 NULL,
3781 show_sevenbit_strings,
3782 &setprintlist, &showprintlist);
3784 add_setshow_boolean_cmd ("timestamp", class_maintenance,
3785 &debug_timestamp, _("\
3786 Set timestamping of debugging messages."), _("\
3787 Show timestamping of debugging messages."), _("\
3788 When set, debugging messages will be marked with seconds and microseconds."),
3789 NULL,
3790 show_debug_timestamp,
3791 &setdebuglist, &showdebuglist);
3793 add_internal_problem_command (&internal_error_problem);
3794 add_internal_problem_command (&internal_warning_problem);
3795 add_internal_problem_command (&demangler_warning_problem);
3797 add_cmd ("screen", class_maintenance, &maintenance_info_screen,
3798 _("Show screen characteristics."), &maintenanceinfolist);
3800 #if GDB_SELF_TEST
3801 selftests::register_test ("gdb_realpath", gdb_realpath_tests);
3802 selftests::register_test ("gdb_argv_array_view", gdb_argv_as_array_view_test);
3803 selftests::register_test ("strncmp_iw_with_mode",
3804 strncmp_iw_with_mode_tests);
3805 selftests::register_test ("pager", test_pager);
3806 selftests::register_test ("assign_set_return_if_changed",
3807 test_assign_set_return_if_changed);
3808 #endif