arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / gdb / utils.c
bloba1bf9e46e02e519b54004d3246659895a92d7a07
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 "cli/cli-cmds.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"
83 #include "gdbsupport/gdb_tilde_expand.h"
85 void (*deprecated_error_begin_hook) (void);
87 /* Prototypes for local functions */
89 static void set_screen_size (void);
90 static void set_width (void);
92 /* Time spent in prompt_for_continue in the currently executing command
93 waiting for user to respond.
94 Initialized in make_command_stats_cleanup.
95 Modified in prompt_for_continue and defaulted_query.
96 Used in report_command_stats. */
98 static std::chrono::steady_clock::duration prompt_for_continue_wait_time;
100 /* A flag indicating whether to timestamp debugging messages. */
102 bool debug_timestamp = false;
104 /* True means that strings with character values >0x7F should be printed
105 as octal escapes. False means just print the value (e.g. it's an
106 international character, and the terminal or window can cope.) */
108 bool sevenbit_strings = false;
109 static void
110 show_sevenbit_strings (struct ui_file *file, int from_tty,
111 struct cmd_list_element *c, const char *value)
113 gdb_printf (file, _("Printing of 8-bit characters "
114 "in strings as \\nnn is %s.\n"),
115 value);
118 /* String to be printed before warning messages, if any. */
120 const char *warning_pre_print = "\nwarning: ";
122 bool pagination_enabled = true;
123 static void
124 show_pagination_enabled (struct ui_file *file, int from_tty,
125 struct cmd_list_element *c, const char *value)
127 gdb_printf (file, _("State of pagination is %s.\n"), value);
131 /* Warning hook pointer. This has to be 'static' to avoid link
132 problems with thread-locals on AIX. */
134 static thread_local warning_hook_handler warning_hook;
136 /* See utils.h. */
138 warning_hook_handler
139 get_warning_hook_handler ()
141 return warning_hook;
144 /* See utils.h. */
146 scoped_restore_warning_hook::scoped_restore_warning_hook
147 (warning_hook_handler new_handler)
148 : m_save (warning_hook)
150 warning_hook = new_handler;
153 scoped_restore_warning_hook::~scoped_restore_warning_hook ()
155 warning_hook = m_save;
158 /* Print a warning message. The first argument STRING is the warning
159 message, used as an fprintf format string, the second is the
160 va_list of arguments for that string. A warning is unfiltered (not
161 paginated) so that the user does not need to page through each
162 screen full of warnings when there are lots of them. */
164 void
165 vwarning (const char *string, va_list args)
167 if (warning_hook != nullptr)
168 warning_hook->warn (string, args);
169 else
171 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
172 if (target_supports_terminal_ours ())
174 term_state.emplace ();
175 target_terminal::ours_for_output ();
177 if (warning_pre_print)
178 gdb_puts (warning_pre_print, gdb_stderr);
179 gdb_vprintf (gdb_stderr, string, args);
180 gdb_printf (gdb_stderr, "\n");
184 /* Print an error message and return to command level.
185 The first argument STRING is the error message, used as a fprintf string,
186 and the remaining args are passed as arguments to it. */
188 void
189 verror (const char *string, va_list args)
191 throw_verror (GENERIC_ERROR, string, args);
194 /* Emit a message and abort. */
196 [[noreturn]] static void
197 abort_with_message (const char *msg)
199 if (current_ui == NULL)
200 fputs (msg, stderr);
201 else
202 gdb_puts (msg, gdb_stderr);
204 abort (); /* ARI: abort */
207 /* Dump core trying to increase the core soft limit to hard limit first. */
209 void
210 dump_core (void)
212 #ifdef HAVE_SETRLIMIT
213 struct rlimit rlim = { (rlim_t) RLIM_INFINITY, (rlim_t) RLIM_INFINITY };
215 setrlimit (RLIMIT_CORE, &rlim);
216 #endif /* HAVE_SETRLIMIT */
218 /* Ensure that the SIGABRT we're about to raise will immediately cause
219 GDB to exit and dump core, we don't want to trigger GDB's printing of
220 a backtrace to the console here. */
221 signal (SIGABRT, SIG_DFL);
223 abort (); /* ARI: abort */
226 /* Check whether GDB will be able to dump core using the dump_core
227 function. Returns zero if GDB cannot or should not dump core.
228 If LIMIT_KIND is LIMIT_CUR the user's soft limit will be respected.
229 If LIMIT_KIND is LIMIT_MAX only the hard limit will be respected. */
232 can_dump_core (enum resource_limit_kind limit_kind)
234 #ifdef HAVE_GETRLIMIT
235 struct rlimit rlim;
237 /* Be quiet and assume we can dump if an error is returned. */
238 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
239 return 1;
241 switch (limit_kind)
243 case LIMIT_CUR:
244 if (rlim.rlim_cur == 0)
245 return 0;
246 [[fallthrough]];
248 case LIMIT_MAX:
249 if (rlim.rlim_max == 0)
250 return 0;
252 #endif /* HAVE_GETRLIMIT */
254 return 1;
257 /* Print a warning that we cannot dump core. */
259 void
260 warn_cant_dump_core (const char *reason)
262 gdb_printf (gdb_stderr,
263 _("%s\nUnable to dump core, use `ulimit -c"
264 " unlimited' before executing GDB next time.\n"),
265 reason);
268 /* Check whether GDB will be able to dump core using the dump_core
269 function, and print a warning if we cannot. */
271 static int
272 can_dump_core_warn (enum resource_limit_kind limit_kind,
273 const char *reason)
275 int core_dump_allowed = can_dump_core (limit_kind);
277 if (!core_dump_allowed)
278 warn_cant_dump_core (reason);
280 return core_dump_allowed;
283 /* Allow the user to configure the debugger behavior with respect to
284 what to do when an internal problem is detected. */
286 const char internal_problem_ask[] = "ask";
287 const char internal_problem_yes[] = "yes";
288 const char internal_problem_no[] = "no";
289 static const char *const internal_problem_modes[] =
291 internal_problem_ask,
292 internal_problem_yes,
293 internal_problem_no,
294 NULL
297 /* Data structure used to control how the internal_vproblem function
298 should behave. An instance of this structure is created for each
299 problem type that GDB supports. */
301 struct internal_problem
303 /* The name of this problem type. This must not contain white space as
304 this string is used to build command names. */
305 const char *name;
307 /* When this is true then a user command is created (based on NAME) that
308 allows the SHOULD_QUIT field to be modified, otherwise, SHOULD_QUIT
309 can't be changed from its default value by the user. */
310 bool user_settable_should_quit;
312 /* Reference a value from internal_problem_modes to indicate if GDB
313 should quit when it hits a problem of this type. */
314 const char *should_quit;
316 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_DUMP_CORE. */
317 bool user_settable_should_dump_core;
319 /* Like SHOULD_QUIT, but whether GDB should dump core. */
320 const char *should_dump_core;
322 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_PRINT_BACKTRACE. */
323 bool user_settable_should_print_backtrace;
325 /* When this is true GDB will print a backtrace when a problem of this
326 type is encountered. */
327 bool should_print_backtrace;
330 /* Return true if the readline callbacks have been initialized for UI.
331 This is always true once GDB is fully initialized, but during the early
332 startup phase this is initially false. */
334 static bool
335 readline_initialized (struct ui *ui)
337 return ui->call_readline != nullptr;
340 /* Report a problem, internal to GDB, to the user. Once the problem
341 has been reported, and assuming GDB didn't quit, the caller can
342 either allow execution to resume or throw an error. */
344 static void ATTRIBUTE_PRINTF (4, 0)
345 internal_vproblem (struct internal_problem *problem,
346 const char *file, int line, const char *fmt, va_list ap)
348 static int dejavu;
349 int quit_p;
350 int dump_core_p;
351 std::string reason;
353 /* Don't allow infinite error/warning recursion. */
355 static const char msg[] = "Recursive internal problem.\n";
357 switch (dejavu)
359 case 0:
360 dejavu = 1;
361 break;
362 case 1:
363 dejavu = 2;
364 abort_with_message (msg);
365 default:
366 dejavu = 3;
367 /* Newer GLIBC versions put the warn_unused_result attribute
368 on write, but this is one of those rare cases where
369 ignoring the return value is correct. Casting to (void)
370 does not fix this problem. This is the solution suggested
371 at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509. */
372 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
373 abort (); /* ARI: abort */
374 exit (1);
378 #ifdef TUI
379 tui_disable ();
380 #endif
382 /* Create a string containing the full error/warning message. Need
383 to call query with this full string, as otherwize the reason
384 (error/warning) and question become separated. Format using a
385 style similar to a compiler error message. Include extra detail
386 so that the user knows that they are living on the edge. */
388 std::string msg = string_vprintf (fmt, ap);
389 reason = string_printf ("%s:%d: %s: %s\n"
390 "A problem internal to GDB has been detected,\n"
391 "further debugging may prove unreliable.",
392 file, line, problem->name, msg.c_str ());
395 /* Fall back to abort_with_message if gdb_stderr is not set up. */
396 if (current_ui == NULL)
398 fputs (reason.c_str (), stderr);
399 abort_with_message ("\n");
402 /* Try to get the message out and at the start of a new line. */
403 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
404 if (target_supports_terminal_ours ())
406 term_state.emplace ();
407 target_terminal::ours_for_output ();
409 if (filtered_printing_initialized ())
410 begin_line ();
412 /* Emit the message unless query will emit it below. */
413 if (problem->should_quit != internal_problem_ask
414 || !confirm
415 || !filtered_printing_initialized ()
416 || !readline_initialized (current_ui)
417 || problem->should_print_backtrace)
418 gdb_printf (gdb_stderr, "%s\n", reason.c_str ());
420 if (problem->should_print_backtrace)
421 gdb_internal_backtrace ();
423 if (problem->should_quit == internal_problem_ask)
425 /* Default (yes/batch case) is to quit GDB. When in batch mode
426 this lessens the likelihood of GDB going into an infinite
427 loop. */
428 if (!confirm || !filtered_printing_initialized ()
429 || !readline_initialized (current_ui))
430 quit_p = 1;
431 else
432 quit_p = query (_("%s\nQuit this debugging session? "),
433 reason.c_str ());
435 else if (problem->should_quit == internal_problem_yes)
436 quit_p = 1;
437 else if (problem->should_quit == internal_problem_no)
438 quit_p = 0;
439 else
440 internal_error (_("bad switch"));
442 gdb_puts (_("\nThis is a bug, please report it."), gdb_stderr);
443 if (REPORT_BUGS_TO[0])
444 gdb_printf (gdb_stderr, _(" For instructions, see:\n%ps."),
445 styled_string (file_name_style.style (),
446 REPORT_BUGS_TO));
447 gdb_puts ("\n\n", gdb_stderr);
449 if (problem->should_dump_core == internal_problem_ask)
451 if (!can_dump_core_warn (LIMIT_MAX, reason.c_str ()))
452 dump_core_p = 0;
453 else if (!filtered_printing_initialized ()
454 || !readline_initialized (current_ui))
455 dump_core_p = 1;
456 else
458 /* Default (yes/batch case) is to dump core. This leaves a GDB
459 `dropping' so that it is easier to see that something went
460 wrong in GDB. */
461 dump_core_p = query (_("%s\nCreate a core file of GDB? "),
462 reason.c_str ());
465 else if (problem->should_dump_core == internal_problem_yes)
466 dump_core_p = can_dump_core_warn (LIMIT_MAX, reason.c_str ());
467 else if (problem->should_dump_core == internal_problem_no)
468 dump_core_p = 0;
469 else
470 internal_error (_("bad switch"));
472 if (quit_p)
474 if (dump_core_p)
475 dump_core ();
476 else
477 exit (1);
479 else
481 if (dump_core_p)
483 #ifdef HAVE_WORKING_FORK
484 if (fork () == 0)
485 dump_core ();
486 #endif
490 dejavu = 0;
493 static struct internal_problem internal_error_problem = {
494 "internal-error", true, internal_problem_ask, true, internal_problem_ask,
495 true, GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON
498 void
499 internal_verror (const char *file, int line, const char *fmt, va_list ap)
501 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
502 throw_quit (_("Command aborted."));
505 static struct internal_problem internal_warning_problem = {
506 "internal-warning", true, internal_problem_ask, true, internal_problem_ask,
507 true, false
510 void
511 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
513 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
516 static struct internal_problem demangler_warning_problem = {
517 "demangler-warning", true, internal_problem_ask, false, internal_problem_no,
518 false, false
521 void
522 demangler_vwarning (const char *file, int line, const char *fmt, va_list ap)
524 internal_vproblem (&demangler_warning_problem, file, line, fmt, ap);
527 void
528 demangler_warning (const char *file, int line, const char *string, ...)
530 va_list ap;
532 va_start (ap, string);
533 demangler_vwarning (file, line, string, ap);
534 va_end (ap);
537 /* When GDB reports an internal problem (error or warning) it gives
538 the user the opportunity to quit GDB and/or create a core file of
539 the current debug session. This function registers a few commands
540 that make it possible to specify that GDB should always or never
541 quit or create a core file, without asking. The commands look
542 like:
544 maint set PROBLEM-NAME quit ask|yes|no
545 maint show PROBLEM-NAME quit
546 maint set PROBLEM-NAME corefile ask|yes|no
547 maint show PROBLEM-NAME corefile
549 Where PROBLEM-NAME is currently "internal-error" or
550 "internal-warning". */
552 static void
553 add_internal_problem_command (struct internal_problem *problem)
555 struct cmd_list_element **set_cmd_list;
556 struct cmd_list_element **show_cmd_list;
558 set_cmd_list = XNEW (struct cmd_list_element *);
559 show_cmd_list = XNEW (struct cmd_list_element *);
560 *set_cmd_list = NULL;
561 *show_cmd_list = NULL;
563 /* The add_basic_prefix_cmd and add_show_prefix_cmd functions take
564 ownership of the string passed in, which is why we don't need to free
565 set_doc and show_doc in this function. */
566 const char *set_doc
567 = xstrprintf (_("Configure what GDB does when %s is detected."),
568 problem->name).release ();
569 const char *show_doc
570 = xstrprintf (_("Show what GDB does when %s is detected."),
571 problem->name).release ();
573 add_setshow_prefix_cmd (problem->name, class_maintenance,
574 set_doc, show_doc, set_cmd_list, show_cmd_list,
575 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
577 if (problem->user_settable_should_quit)
579 std::string set_quit_doc
580 = string_printf (_("Set whether GDB should quit when an %s is "
581 "detected."), problem->name);
582 std::string show_quit_doc
583 = string_printf (_("Show whether GDB will quit when an %s is "
584 "detected."), problem->name);
585 add_setshow_enum_cmd ("quit", class_maintenance,
586 internal_problem_modes,
587 &problem->should_quit,
588 set_quit_doc.c_str (),
589 show_quit_doc.c_str (),
590 NULL, /* help_doc */
591 NULL, /* setfunc */
592 NULL, /* showfunc */
593 set_cmd_list,
594 show_cmd_list);
597 if (problem->user_settable_should_dump_core)
599 std::string set_core_doc
600 = string_printf (_("Set whether GDB should create a core file of "
601 "GDB when %s is detected."), problem->name);
602 std::string show_core_doc
603 = string_printf (_("Show whether GDB will create a core file of "
604 "GDB when %s is detected."), problem->name);
605 add_setshow_enum_cmd ("corefile", class_maintenance,
606 internal_problem_modes,
607 &problem->should_dump_core,
608 set_core_doc.c_str (),
609 show_core_doc.c_str (),
610 NULL, /* help_doc */
611 NULL, /* setfunc */
612 NULL, /* showfunc */
613 set_cmd_list,
614 show_cmd_list);
617 if (problem->user_settable_should_print_backtrace)
619 std::string set_bt_doc
620 = string_printf (_("Set whether GDB should print a backtrace of "
621 "GDB when %s is detected."), problem->name);
622 std::string show_bt_doc
623 = string_printf (_("Show whether GDB will print a backtrace of "
624 "GDB when %s is detected."), problem->name);
625 add_setshow_boolean_cmd ("backtrace", class_maintenance,
626 &problem->should_print_backtrace,
627 set_bt_doc.c_str (),
628 show_bt_doc.c_str (),
629 NULL, /* help_doc */
630 gdb_internal_backtrace_set_cmd,
631 NULL, /* showfunc */
632 set_cmd_list,
633 show_cmd_list);
637 /* Same as perror_with_name except that it prints a warning instead
638 of throwing an error. */
640 void
641 perror_warning_with_name (const char *string)
643 std::string combined = perror_string (string);
644 warning (_("%s"), combined.c_str ());
647 /* See utils.h. */
649 void
650 warning_filename_and_errno (const char *filename, int saved_errno)
652 warning (_("%ps: %s"), styled_string (file_name_style.style (), filename),
653 safe_strerror (saved_errno));
656 /* Called when a memory allocation fails, with the number of bytes of
657 memory requested in SIZE. */
659 void
660 malloc_failure (long size)
662 if (size > 0)
664 internal_error (_("virtual memory exhausted: can't allocate %ld bytes."),
665 size);
667 else
669 internal_error (_("virtual memory exhausted."));
673 /* See common/errors.h. */
675 void
676 flush_streams ()
678 gdb_stdout->flush ();
679 gdb_stderr->flush ();
682 /* My replacement for the read system call.
683 Used like `read' but keeps going if `read' returns too soon. */
686 myread (int desc, char *addr, int len)
688 int val;
689 int orglen = len;
691 while (len > 0)
693 val = read (desc, addr, len);
694 if (val < 0)
695 return val;
696 if (val == 0)
697 return orglen - len;
698 len -= val;
699 addr += val;
701 return orglen;
706 /* An RAII class that sets up to handle input and then tears down
707 during destruction. */
709 class scoped_input_handler
711 public:
713 scoped_input_handler ()
714 : m_quit_handler (&quit_handler, default_quit_handler),
715 m_ui (NULL)
717 target_terminal::ours ();
718 current_ui->register_file_handler ();
719 if (current_ui->prompt_state == PROMPT_BLOCKED)
720 m_ui = current_ui;
723 ~scoped_input_handler ()
725 if (m_ui != NULL)
726 m_ui->unregister_file_handler ();
729 DISABLE_COPY_AND_ASSIGN (scoped_input_handler);
731 private:
733 /* Save and restore the terminal state. */
734 target_terminal::scoped_restore_terminal_state m_term_state;
736 /* Save and restore the quit handler. */
737 scoped_restore_tmpl<quit_handler_ftype *> m_quit_handler;
739 /* The saved UI, if non-NULL. */
740 struct ui *m_ui;
745 /* This function supports the query, nquery, and yquery functions.
746 Ask user a y-or-n question and return 0 if answer is no, 1 if
747 answer is yes, or default the answer to the specified default
748 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
749 default answer, or '\0' for no default.
750 CTLSTR is the control string and should end in "? ". It should
751 not say how to answer, because we do that.
752 ARGS are the arguments passed along with the CTLSTR argument to
753 printf. */
755 static int ATTRIBUTE_PRINTF (1, 0)
756 defaulted_query (const char *ctlstr, const char defchar, va_list args)
758 int retval;
759 int def_value;
760 char def_answer, not_def_answer;
761 const char *y_string, *n_string;
763 /* Set up according to which answer is the default. */
764 if (defchar == '\0')
766 def_value = 1;
767 def_answer = 'Y';
768 not_def_answer = 'N';
769 y_string = "y";
770 n_string = "n";
772 else if (defchar == 'y')
774 def_value = 1;
775 def_answer = 'Y';
776 not_def_answer = 'N';
777 y_string = "[y]";
778 n_string = "n";
780 else
782 def_value = 0;
783 def_answer = 'N';
784 not_def_answer = 'Y';
785 y_string = "y";
786 n_string = "[n]";
789 /* Automatically answer the default value if the user did not want
790 prompts or the command was issued with the server prefix. */
791 if (!confirm || server_command)
792 return def_value;
794 /* If input isn't coming from the user directly, just say what
795 question we're asking, and then answer the default automatically. This
796 way, important error messages don't get lost when talking to GDB
797 over a pipe. */
798 if (current_ui->instream != current_ui->stdin_stream
799 || !current_ui->input_interactive_p ()
800 /* Restrict queries to the main UI. */
801 || current_ui != main_ui)
803 target_terminal::scoped_restore_terminal_state term_state;
804 target_terminal::ours_for_output ();
805 gdb_stdout->wrap_here (0);
806 gdb_vprintf (gdb_stdout, ctlstr, args);
808 gdb_printf (_("(%s or %s) [answered %c; "
809 "input not from terminal]\n"),
810 y_string, n_string, def_answer);
812 return def_value;
815 if (deprecated_query_hook)
817 target_terminal::scoped_restore_terminal_state term_state;
818 return deprecated_query_hook (ctlstr, args);
821 /* Format the question outside of the loop, to avoid reusing args. */
822 string_file tem (gdb_stdout->can_emit_style_escape ());
823 gdb_vprintf (&tem, ctlstr, args);
824 std::string question = tem.release ();
825 std::string prompt
826 = string_printf (_("%s%s(%s or %s) %s"),
827 annotation_level > 1 ? "\n\032\032pre-query\n" : "",
828 question.c_str (), y_string, n_string,
829 annotation_level > 1 ? "\n\032\032query\n" : "");
831 /* Used to add duration we waited for user to respond to
832 prompt_for_continue_wait_time. */
833 using namespace std::chrono;
834 steady_clock::time_point prompt_started = steady_clock::now ();
836 scoped_input_handler prepare_input;
838 while (1)
840 char *response, answer;
842 gdb_flush (gdb_stdout);
843 response = gdb_readline_wrapper (prompt.c_str ());
845 if (response == NULL) /* C-d */
847 gdb_printf ("EOF [assumed %c]\n", def_answer);
848 retval = def_value;
849 break;
852 answer = response[0];
853 xfree (response);
855 if (answer >= 'a')
856 answer -= 040;
857 /* Check answer. For the non-default, the user must specify
858 the non-default explicitly. */
859 if (answer == not_def_answer)
861 retval = !def_value;
862 break;
864 /* Otherwise, if a default was specified, the user may either
865 specify the required input or have it default by entering
866 nothing. */
867 if (answer == def_answer
868 || (defchar != '\0' && answer == '\0'))
870 retval = def_value;
871 break;
873 /* Invalid entries are not defaulted and require another selection. */
874 gdb_printf (_("Please answer %s or %s.\n"),
875 y_string, n_string);
878 /* Add time spend in this routine to prompt_for_continue_wait_time. */
879 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
881 if (annotation_level > 1)
882 gdb_printf (("\n\032\032post-query\n"));
883 return retval;
887 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
888 answer is yes, or 0 if answer is defaulted.
889 Takes three args which are given to printf to print the question.
890 The first, a control string, should end in "? ".
891 It should not say how to answer, because we do that. */
894 nquery (const char *ctlstr, ...)
896 va_list args;
897 int ret;
899 va_start (args, ctlstr);
900 ret = defaulted_query (ctlstr, 'n', args);
901 va_end (args);
902 return ret;
905 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
906 answer is yes, or 1 if answer is defaulted.
907 Takes three args which are given to printf to print the question.
908 The first, a control string, should end in "? ".
909 It should not say how to answer, because we do that. */
912 yquery (const char *ctlstr, ...)
914 va_list args;
915 int ret;
917 va_start (args, ctlstr);
918 ret = defaulted_query (ctlstr, 'y', args);
919 va_end (args);
920 return ret;
923 /* Ask user a y-or-n question and return 1 iff answer is yes.
924 Takes three args which are given to printf to print the question.
925 The first, a control string, should end in "? ".
926 It should not say how to answer, because we do that. */
929 query (const char *ctlstr, ...)
931 va_list args;
932 int ret;
934 va_start (args, ctlstr);
935 ret = defaulted_query (ctlstr, '\0', args);
936 va_end (args);
937 return ret;
940 /* A helper for parse_escape that converts a host character to a
941 target character. C is the host character. If conversion is
942 possible, then the target character is stored in *TARGET_C and the
943 function returns 1. Otherwise, the function returns 0. */
945 static int
946 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
948 char the_char = c;
949 int result = 0;
951 auto_obstack host_data;
953 convert_between_encodings (target_charset (gdbarch), host_charset (),
954 (gdb_byte *) &the_char, 1, 1,
955 &host_data, translit_none);
957 if (obstack_object_size (&host_data) == 1)
959 result = 1;
960 *target_c = *(char *) obstack_base (&host_data);
963 return result;
966 /* Parse a C escape sequence. STRING_PTR points to a variable
967 containing a pointer to the string to parse. That pointer
968 should point to the character after the \. That pointer
969 is updated past the characters we use. The value of the
970 escape sequence is returned.
972 A negative value means the sequence \ newline was seen,
973 which is supposed to be equivalent to nothing at all.
975 If \ is followed by a null character, we return a negative
976 value and leave the string pointer pointing at the null character.
978 If \ is followed by 000, we return 0 and leave the string pointer
979 after the zeros. A value of 0 does not mean end of string. */
982 parse_escape (struct gdbarch *gdbarch, const char **string_ptr)
984 int target_char = -2; /* Initialize to avoid GCC warnings. */
985 int c = *(*string_ptr)++;
987 switch (c)
989 case '\n':
990 return -2;
991 case 0:
992 (*string_ptr)--;
993 return 0;
995 case '0':
996 case '1':
997 case '2':
998 case '3':
999 case '4':
1000 case '5':
1001 case '6':
1002 case '7':
1004 int i = fromhex (c);
1005 int count = 0;
1006 while (++count < 3)
1008 c = (**string_ptr);
1009 if (ISDIGIT (c) && c != '8' && c != '9')
1011 (*string_ptr)++;
1012 i *= 8;
1013 i += fromhex (c);
1015 else
1017 break;
1020 return i;
1023 case 'a':
1024 c = '\a';
1025 break;
1026 case 'b':
1027 c = '\b';
1028 break;
1029 case 'f':
1030 c = '\f';
1031 break;
1032 case 'n':
1033 c = '\n';
1034 break;
1035 case 'r':
1036 c = '\r';
1037 break;
1038 case 't':
1039 c = '\t';
1040 break;
1041 case 'v':
1042 c = '\v';
1043 break;
1045 default:
1046 break;
1049 if (!host_char_to_target (gdbarch, c, &target_char))
1050 error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1051 " which has no equivalent\nin the `%s' character set."),
1052 c, c, target_charset (gdbarch));
1053 return target_char;
1057 /* Number of lines per page or UINT_MAX if paging is disabled. */
1058 static unsigned int lines_per_page;
1059 static void
1060 show_lines_per_page (struct ui_file *file, int from_tty,
1061 struct cmd_list_element *c, const char *value)
1063 gdb_printf (file,
1064 _("Number of lines gdb thinks are in a page is %s.\n"),
1065 value);
1068 /* Number of chars per line or UINT_MAX if line folding is disabled. */
1069 static unsigned int chars_per_line;
1070 static void
1071 show_chars_per_line (struct ui_file *file, int from_tty,
1072 struct cmd_list_element *c, const char *value)
1074 gdb_printf (file,
1075 _("Number of characters gdb thinks "
1076 "are in a line is %s.\n"),
1077 value);
1080 /* Current count of lines printed on this page, chars on this line. */
1081 static unsigned int lines_printed, chars_printed;
1083 /* True if pagination is disabled for just one command. */
1085 static bool pagination_disabled_for_command;
1087 /* Buffer and start column of buffered text, for doing smarter word-
1088 wrapping. When someone calls wrap_here(), we start buffering output
1089 that comes through gdb_puts(). If we see a newline, we just
1090 spit it out and forget about the wrap_here(). If we see another
1091 wrap_here(), we spit it out and remember the newer one. If we see
1092 the end of the line, we spit out a newline, the indent, and then
1093 the buffered output. */
1095 static bool filter_initialized = false;
1099 /* See utils.h. */
1101 int readline_hidden_cols = 0;
1103 /* Initialize the number of lines per page and chars per line. */
1105 void
1106 init_page_info (void)
1108 if (batch_flag)
1110 lines_per_page = UINT_MAX;
1111 chars_per_line = UINT_MAX;
1113 else
1114 #if defined(TUI)
1115 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1116 #endif
1118 int rows, cols;
1120 #if defined(__GO32__)
1121 rows = ScreenRows ();
1122 cols = ScreenCols ();
1123 lines_per_page = rows;
1124 chars_per_line = cols;
1125 #else
1126 /* Make sure Readline has initialized its terminal settings. */
1127 rl_reset_terminal (NULL);
1129 /* Get the screen size from Readline. */
1130 rl_get_screen_size (&rows, &cols);
1132 /* Readline:
1133 - ignores the COLUMNS variable when detecting screen width
1134 (because rl_prefer_env_winsize defaults to 0)
1135 - puts the detected screen width in the COLUMNS variable
1136 (because rl_change_environment defaults to 1)
1137 - may report one less than the detected screen width in
1138 rl_get_screen_size (when _rl_term_autowrap == 0).
1139 We could use _rl_term_autowrap, but we want to avoid introducing
1140 another dependency on readline private variables, so set
1141 readline_hidden_cols by comparing COLUMNS to cols as returned by
1142 rl_get_screen_size. */
1143 const char *columns_env_str = getenv ("COLUMNS");
1144 gdb_assert (columns_env_str != nullptr);
1145 int columns_env_val = atoi (columns_env_str);
1146 gdb_assert (columns_env_val != 0);
1147 readline_hidden_cols = columns_env_val - cols;
1148 gdb_assert (readline_hidden_cols >= 0);
1149 gdb_assert (readline_hidden_cols <= 1);
1151 lines_per_page = rows;
1152 chars_per_line = cols + readline_hidden_cols;
1154 /* Readline should have fetched the termcap entry for us.
1155 Only try to use tgetnum function if rl_get_screen_size
1156 did not return a useful value. */
1157 if (((rows <= 0) && (tgetnum ((char *) "li") < 0))
1158 /* Also disable paging if inside Emacs. $EMACS was used
1159 before Emacs v25.1, $INSIDE_EMACS is used since then. */
1160 || getenv ("EMACS") || getenv ("INSIDE_EMACS"))
1162 /* The number of lines per page is not mentioned in the terminal
1163 description or EMACS environment variable is set. This probably
1164 means that paging is not useful, so disable paging. */
1165 lines_per_page = UINT_MAX;
1168 /* If the output is not a terminal, don't paginate it. */
1169 if (!gdb_stdout->isatty ())
1170 lines_per_page = UINT_MAX;
1171 #endif
1174 /* We handle SIGWINCH ourselves. */
1175 rl_catch_sigwinch = 0;
1177 set_screen_size ();
1178 set_width ();
1181 /* Return nonzero if filtered printing is initialized. */
1183 filtered_printing_initialized (void)
1185 return filter_initialized;
1188 set_batch_flag_and_restore_page_info::set_batch_flag_and_restore_page_info ()
1189 : m_save_lines_per_page (lines_per_page),
1190 m_save_chars_per_line (chars_per_line),
1191 m_save_batch_flag (batch_flag)
1193 batch_flag = 1;
1194 init_page_info ();
1197 set_batch_flag_and_restore_page_info::~set_batch_flag_and_restore_page_info ()
1199 batch_flag = m_save_batch_flag;
1200 chars_per_line = m_save_chars_per_line;
1201 lines_per_page = m_save_lines_per_page;
1203 set_screen_size ();
1204 set_width ();
1207 /* An approximation of SQRT(INT_MAX) that is:
1208 - cheap to calculate,
1209 - guaranteed to be smaller than SQRT(INT_MAX), such that
1210 sqrt_int_max * sqrt_int_max doesn't overflow, and
1211 - "close enough" to SQRT(INT_MAX), for instance for INT_MAX == 2147483647,
1212 SQRT(INT_MAX) is ~46341 and sqrt_int_max == 32767. */
1214 static const int sqrt_int_max = INT_MAX >> (sizeof (int) * 8 / 2);
1216 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1218 static void
1219 set_screen_size (void)
1221 int rows = lines_per_page;
1222 int cols = chars_per_line;
1224 /* If we get 0 or negative ROWS or COLS, treat as "infinite" size.
1225 A negative number can be seen here with the "set width/height"
1226 commands and either:
1228 - the user specified "unlimited", which maps to UINT_MAX, or
1229 - the user specified some number between INT_MAX and UINT_MAX.
1231 Cap "infinity" to approximately sqrt(INT_MAX) so that we don't
1232 overflow in rl_set_screen_size, which multiplies rows and columns
1233 to compute the number of characters on the screen. */
1235 if (rows <= 0 || rows > sqrt_int_max)
1237 rows = sqrt_int_max;
1238 lines_per_page = UINT_MAX;
1241 if (cols <= 0 || cols > sqrt_int_max)
1243 cols = sqrt_int_max;
1244 chars_per_line = UINT_MAX;
1247 /* Update Readline's idea of the terminal size. */
1248 rl_set_screen_size (rows, cols);
1251 /* Reinitialize WRAP_BUFFER. */
1253 static void
1254 set_width (void)
1256 if (chars_per_line == 0)
1257 init_page_info ();
1259 filter_initialized = true;
1262 static void
1263 set_width_command (const char *args, int from_tty, struct cmd_list_element *c)
1265 set_screen_size ();
1266 set_width ();
1269 static void
1270 set_height_command (const char *args, int from_tty, struct cmd_list_element *c)
1272 set_screen_size ();
1275 /* See utils.h. */
1277 void
1278 set_screen_width_and_height (int width, int height)
1280 lines_per_page = height;
1281 chars_per_line = width;
1283 set_screen_size ();
1284 set_width ();
1287 /* Import termcap variable UP (instead of readline private variable
1288 _rl_term_up, which we're trying to avoid, see PR build/10723). The UP
1289 variable doesn't seem be part of the regular termcap interface, but rather
1290 curses-specific. But if it's missing in the termcap library, then readline
1291 provides a fallback version. Let's assume the fallback is not part of the
1292 private readline interface. */
1293 extern "C" char *UP;
1295 /* Implement "maint info screen". */
1297 static void
1298 maintenance_info_screen (const char *args, int from_tty)
1300 int rows, cols;
1301 rl_get_screen_size (&rows, &cols);
1303 gdb_printf (gdb_stdout,
1304 _("Number of characters gdb thinks "
1305 "are in a line is %u%s.\n"),
1306 chars_per_line,
1307 chars_per_line == UINT_MAX ? " (unlimited)" : "");
1309 gdb_printf (gdb_stdout,
1310 _("Number of characters readline reports "
1311 "are in a line is %d%s.\n"),
1312 cols,
1313 (cols == sqrt_int_max
1314 ? " (unlimited)"
1315 : (cols == sqrt_int_max - 1
1316 ? " (unlimited - 1)"
1317 : "")));
1319 #ifdef HAVE_LIBCURSES
1320 gdb_printf (gdb_stdout,
1321 _("Number of characters curses thinks "
1322 "are in a line is %d.\n"),
1323 COLS);
1324 #endif
1326 gdb_printf (gdb_stdout,
1327 _("Number of characters environment thinks "
1328 "are in a line is %s (COLUMNS).\n"),
1329 getenv ("COLUMNS"));
1331 gdb_printf (gdb_stdout,
1332 _("Number of lines gdb thinks are in a page is %u%s.\n"),
1333 lines_per_page,
1334 lines_per_page == UINT_MAX ? " (unlimited)" : "");
1336 gdb_printf (gdb_stdout,
1337 _("Number of lines readline reports "
1338 "are in a page is %d%s.\n"),
1339 rows,
1340 rows == sqrt_int_max ? " (unlimited)" : "");
1342 #ifdef HAVE_LIBCURSES
1343 gdb_printf (gdb_stdout,
1344 _("Number of lines curses thinks "
1345 "are in a page is %d.\n"),
1346 LINES);
1347 #endif
1349 gdb_printf (gdb_stdout,
1350 _("Number of lines environment thinks "
1351 "are in a page is %s (LINES).\n"),
1352 getenv ("LINES"));
1354 bool have_up = UP != nullptr && *UP != '\0';
1356 /* Fetch value of readline variable horizontal-scroll-mode. */
1357 const char *horizontal_scroll_mode_value
1358 = rl_variable_value ("horizontal-scroll-mode");
1359 bool force_horizontal_scroll_mode
1360 = (horizontal_scroll_mode_value != nullptr
1361 && strcmp (horizontal_scroll_mode_value, "on") == 0);
1363 const char *mode = nullptr;
1364 const char *reason = nullptr;
1365 if (batch_flag)
1367 mode = "unsupported";
1368 reason = "gdb batch mode";
1370 else if (!have_up)
1372 mode = "unsupported";
1373 reason = "terminal is not Cursor Up capable";
1375 else if (force_horizontal_scroll_mode)
1377 mode = "disabled";
1378 reason = "horizontal-scroll-mode";
1380 else if (readline_hidden_cols)
1382 mode = "readline";
1383 reason = "terminal is not auto wrap capable, last column reserved";
1385 else
1387 mode = "terminal";
1388 reason = "terminal is auto wrap capable";
1391 gdb_printf (gdb_stdout, _("Readline wrapping mode: %s (%s).\n"), mode,
1392 reason);
1395 void
1396 pager_file::emit_style_escape (const ui_file_style &style)
1398 if (can_emit_style_escape () && style != m_applied_style)
1400 m_applied_style = style;
1401 if (m_paging)
1402 m_stream->emit_style_escape (style);
1403 else
1404 m_wrap_buffer.append (style.to_ansi ());
1408 /* See pager.h. */
1410 void
1411 pager_file::reset_style ()
1413 if (can_emit_style_escape ())
1415 m_applied_style = ui_file_style ();
1416 m_wrap_buffer.append (m_applied_style.to_ansi ());
1420 /* Wait, so the user can read what's on the screen. Prompt the user
1421 to continue by pressing RETURN. 'q' is also provided because
1422 telling users what to do in the prompt is more user-friendly than
1423 expecting them to think of Ctrl-C/SIGINT. */
1425 void
1426 pager_file::prompt_for_continue ()
1428 char cont_prompt[120];
1429 /* Used to add duration we waited for user to respond to
1430 prompt_for_continue_wait_time. */
1431 using namespace std::chrono;
1432 steady_clock::time_point prompt_started = steady_clock::now ();
1433 bool disable_pagination = pagination_disabled_for_command;
1435 scoped_restore save_paging = make_scoped_restore (&m_paging, true);
1437 /* Clear the current styling. */
1438 m_stream->emit_style_escape (ui_file_style ());
1440 if (annotation_level > 1)
1441 m_stream->puts (("\n\032\032pre-prompt-for-continue\n"));
1443 strcpy (cont_prompt,
1444 "--Type <RET> for more, q to quit, "
1445 "c to continue without paging--");
1446 if (annotation_level > 1)
1447 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1449 /* We must do this *before* we call gdb_readline_wrapper, else it
1450 will eventually call us -- thinking that we're trying to print
1451 beyond the end of the screen. */
1452 reinitialize_more_filter ();
1454 scoped_input_handler prepare_input;
1456 /* Call gdb_readline_wrapper, not readline, in order to keep an
1457 event loop running. */
1458 gdb::unique_xmalloc_ptr<char> ignore (gdb_readline_wrapper (cont_prompt));
1460 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1461 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
1463 if (annotation_level > 1)
1464 m_stream->puts (("\n\032\032post-prompt-for-continue\n"));
1466 if (ignore != NULL)
1468 char *p = ignore.get ();
1470 while (*p == ' ' || *p == '\t')
1471 ++p;
1472 if (p[0] == 'q')
1473 /* Do not call quit here; there is no possibility of SIGINT. */
1474 throw_quit ("Quit");
1475 if (p[0] == 'c')
1476 disable_pagination = true;
1479 /* Now we have to do this again, so that GDB will know that it doesn't
1480 need to save the ---Type <return>--- line at the top of the screen. */
1481 reinitialize_more_filter ();
1482 pagination_disabled_for_command = disable_pagination;
1484 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1487 /* Initialize timer to keep track of how long we waited for the user. */
1489 void
1490 reset_prompt_for_continue_wait_time (void)
1492 using namespace std::chrono;
1494 prompt_for_continue_wait_time = steady_clock::duration::zero ();
1497 /* Fetch the cumulative time spent in prompt_for_continue. */
1499 std::chrono::steady_clock::duration
1500 get_prompt_for_continue_wait_time ()
1502 return prompt_for_continue_wait_time;
1505 /* Reinitialize filter; ie. tell it to reset to original values. */
1507 void
1508 reinitialize_more_filter (void)
1510 lines_printed = 0;
1511 chars_printed = 0;
1512 pagination_disabled_for_command = false;
1515 void
1516 pager_file::flush_wrap_buffer ()
1518 if (!m_paging && !m_wrap_buffer.empty ())
1520 m_stream->puts (m_wrap_buffer.c_str ());
1521 m_wrap_buffer.clear ();
1525 void
1526 pager_file::flush ()
1528 flush_wrap_buffer ();
1529 m_stream->flush ();
1532 /* See utils.h. */
1534 void
1535 gdb_flush (struct ui_file *stream)
1537 stream->flush ();
1540 /* See utils.h. */
1543 get_chars_per_line ()
1545 return chars_per_line;
1548 /* See ui-file.h. */
1550 void
1551 pager_file::wrap_here (int indent)
1553 /* This should have been allocated, but be paranoid anyway. */
1554 gdb_assert (filter_initialized);
1556 flush_wrap_buffer ();
1557 if (chars_per_line == UINT_MAX) /* No line overflow checking. */
1559 m_wrap_column = 0;
1561 else if (chars_printed >= chars_per_line)
1563 this->puts ("\n");
1564 if (indent != 0)
1565 this->puts (n_spaces (indent));
1566 m_wrap_column = 0;
1568 else
1570 m_wrap_column = chars_printed;
1571 m_wrap_indent = indent;
1572 m_wrap_style = m_applied_style;
1576 /* Print input string to gdb_stdout arranging strings in columns of n
1577 chars. String can be right or left justified in the column. Never
1578 prints trailing spaces. String should never be longer than width.
1579 FIXME: this could be useful for the EXAMINE command, which
1580 currently doesn't tabulate very well. */
1582 void
1583 puts_tabular (char *string, int width, int right)
1585 int spaces = 0;
1586 int stringlen;
1587 char *spacebuf;
1589 gdb_assert (chars_per_line > 0);
1590 if (chars_per_line == UINT_MAX)
1592 gdb_puts (string);
1593 gdb_puts ("\n");
1594 return;
1597 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
1598 gdb_puts ("\n");
1600 if (width >= chars_per_line)
1601 width = chars_per_line - 1;
1603 stringlen = strlen (string);
1605 if (chars_printed > 0)
1606 spaces = width - (chars_printed - 1) % width - 1;
1607 if (right)
1608 spaces += width - stringlen;
1610 spacebuf = (char *) alloca (spaces + 1);
1611 spacebuf[spaces] = '\0';
1612 while (spaces--)
1613 spacebuf[spaces] = ' ';
1615 gdb_puts (spacebuf);
1616 gdb_puts (string);
1620 /* Ensure that whatever gets printed next, using the filtered output
1621 commands, starts at the beginning of the line. I.e. if there is
1622 any pending output for the current line, flush it and start a new
1623 line. Otherwise do nothing. */
1625 void
1626 begin_line (void)
1628 if (chars_printed > 0)
1630 gdb_puts ("\n");
1634 void
1635 pager_file::puts (const char *linebuffer)
1637 const char *lineptr;
1639 if (linebuffer == 0)
1640 return;
1642 /* Don't do any filtering or wrapping if both are disabled. */
1643 if (batch_flag
1644 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
1645 || top_level_interpreter () == NULL
1646 || top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
1648 flush_wrap_buffer ();
1649 m_stream->puts (linebuffer);
1650 return;
1653 auto buffer_clearer
1654 = make_scope_exit ([&] ()
1656 m_wrap_buffer.clear ();
1657 m_wrap_column = 0;
1658 m_wrap_indent = 0;
1661 /* If the user does "set height 1" then the pager will exhibit weird
1662 behavior. This is pathological, though, so don't allow it. */
1663 const unsigned int lines_allowed = (lines_per_page > 1
1664 ? lines_per_page - 1
1665 : 1);
1667 /* Go through and output each character. Show line extension
1668 when this is necessary; prompt user for new page when this is
1669 necessary. */
1671 lineptr = linebuffer;
1672 while (*lineptr)
1674 /* Possible new page. Note that PAGINATION_DISABLED_FOR_COMMAND
1675 might be set during this loop, so we must continue to check
1676 it here. */
1677 if (pagination_enabled
1678 && !pagination_disabled_for_command
1679 && lines_printed >= lines_allowed)
1680 prompt_for_continue ();
1682 while (*lineptr && *lineptr != '\n')
1684 int skip_bytes;
1686 /* Print a single line. */
1687 if (*lineptr == '\t')
1689 m_wrap_buffer.push_back ('\t');
1690 /* Shifting right by 3 produces the number of tab stops
1691 we have already passed, and then adding one and
1692 shifting left 3 advances to the next tab stop. */
1693 chars_printed = ((chars_printed >> 3) + 1) << 3;
1694 lineptr++;
1696 else if (*lineptr == '\033'
1697 && skip_ansi_escape (lineptr, &skip_bytes))
1699 m_wrap_buffer.append (lineptr, skip_bytes);
1700 /* Note that we don't consider this a character, so we
1701 don't increment chars_printed here. */
1702 lineptr += skip_bytes;
1704 else if (*lineptr == '\r')
1706 m_wrap_buffer.push_back (*lineptr);
1707 chars_printed = 0;
1708 lineptr++;
1710 else
1712 m_wrap_buffer.push_back (*lineptr);
1713 chars_printed++;
1714 lineptr++;
1717 if (chars_printed >= chars_per_line)
1719 unsigned int save_chars = chars_printed;
1721 /* If we change the style, below, we'll want to reset it
1722 before continuing to print. If there is no wrap
1723 column, then we'll only reset the style if the pager
1724 prompt is given; and to avoid emitting style
1725 sequences in the middle of a run of text, we track
1726 this as well. */
1727 ui_file_style save_style = m_applied_style;
1728 bool did_paginate = false;
1730 chars_printed = 0;
1731 lines_printed++;
1732 if (m_wrap_column)
1734 /* We are about to insert a newline at an historic
1735 location in the WRAP_BUFFER. Before we do we want to
1736 restore the default style. To know if we actually
1737 need to insert an escape sequence we must restore the
1738 current applied style to how it was at the WRAP_COLUMN
1739 location. */
1740 m_applied_style = m_wrap_style;
1741 m_stream->emit_style_escape (ui_file_style ());
1742 /* If we aren't actually wrapping, don't output
1743 newline -- if chars_per_line is right, we
1744 probably just overflowed anyway; if it's wrong,
1745 let us keep going. */
1746 m_stream->puts ("\n");
1748 else
1749 this->flush_wrap_buffer ();
1751 /* Possible new page. Note that
1752 PAGINATION_DISABLED_FOR_COMMAND might be set during
1753 this loop, so we must continue to check it here. */
1754 if (pagination_enabled
1755 && !pagination_disabled_for_command
1756 && lines_printed >= lines_allowed)
1758 prompt_for_continue ();
1759 did_paginate = true;
1762 /* Now output indentation and wrapped string. */
1763 if (m_wrap_column)
1765 m_stream->puts (n_spaces (m_wrap_indent));
1767 /* Having finished inserting the wrapping we should
1768 restore the style as it was at the WRAP_COLUMN. */
1769 m_stream->emit_style_escape (m_wrap_style);
1771 /* The WRAP_BUFFER will still contain content, and that
1772 content might set some alternative style. Restore
1773 APPLIED_STYLE as it was before we started wrapping,
1774 this reflects the current style for the last character
1775 in WRAP_BUFFER. */
1776 m_applied_style = save_style;
1778 /* Note that this can set chars_printed > chars_per_line
1779 if we are printing a long string. */
1780 chars_printed = m_wrap_indent + (save_chars - m_wrap_column);
1781 m_wrap_column = 0; /* And disable fancy wrap */
1783 else if (did_paginate)
1784 m_stream->emit_style_escape (save_style);
1788 if (*lineptr == '\n')
1790 chars_printed = 0;
1791 wrap_here (0); /* Spit out chars, cancel further wraps. */
1792 lines_printed++;
1793 m_stream->puts ("\n");
1794 lineptr++;
1798 buffer_clearer.release ();
1801 void
1802 pager_file::write (const char *buf, long length_buf)
1804 /* We have to make a string here because the pager uses
1805 skip_ansi_escape, which requires NUL-termination. */
1806 std::string str (buf, length_buf);
1807 this->puts (str.c_str ());
1810 #if GDB_SELF_TEST
1812 /* Test that disabling the pager does not also disable word
1813 wrapping. */
1815 static void
1816 test_pager ()
1818 string_file *strfile = new string_file ();
1819 pager_file pager (strfile);
1821 /* Make sure the pager is disabled. */
1822 scoped_restore save_enabled
1823 = make_scoped_restore (&pagination_enabled, false);
1824 scoped_restore save_disabled
1825 = make_scoped_restore (&pagination_disabled_for_command, false);
1826 scoped_restore save_batch
1827 = make_scoped_restore (&batch_flag, false);
1828 scoped_restore save_lines
1829 = make_scoped_restore (&lines_per_page, 50);
1830 /* Make it easy to word wrap. */
1831 scoped_restore save_chars
1832 = make_scoped_restore (&chars_per_line, 15);
1833 scoped_restore save_printed
1834 = make_scoped_restore (&chars_printed, 0);
1836 pager.puts ("aaaaaaaaaaaa");
1837 pager.wrap_here (2);
1838 pager.puts ("bbbbbbbbbbbb\n");
1840 SELF_CHECK (strfile->string () == "aaaaaaaaaaaa\n bbbbbbbbbbbb\n");
1843 #endif /* GDB_SELF_TEST */
1845 void
1846 gdb_puts (const char *linebuffer, struct ui_file *stream)
1848 stream->puts (linebuffer);
1851 void
1852 gdb_puts (const std::string &s, ui_file *stream)
1854 gdb_puts (s.c_str (), stream);
1857 /* See utils.h. */
1859 void
1860 fputs_styled (const char *linebuffer, const ui_file_style &style,
1861 struct ui_file *stream)
1863 stream->emit_style_escape (style);
1864 gdb_puts (linebuffer, stream);
1865 stream->emit_style_escape (ui_file_style ());
1868 /* See utils.h. */
1870 void
1871 fputs_highlighted (const char *str, const compiled_regex &highlight,
1872 struct ui_file *stream)
1874 regmatch_t pmatch;
1876 while (*str && highlight.exec (str, 1, &pmatch, 0) == 0)
1878 size_t n_highlight = pmatch.rm_eo - pmatch.rm_so;
1880 /* Output the part before pmatch with current style. */
1881 while (pmatch.rm_so > 0)
1883 gdb_putc (*str, stream);
1884 pmatch.rm_so--;
1885 str++;
1888 /* Output pmatch with the highlight style. */
1889 stream->emit_style_escape (highlight_style.style ());
1890 while (n_highlight > 0)
1892 gdb_putc (*str, stream);
1893 n_highlight--;
1894 str++;
1896 stream->emit_style_escape (ui_file_style ());
1899 /* Output the trailing part of STR not matching HIGHLIGHT. */
1900 if (*str)
1901 gdb_puts (str, stream);
1904 void
1905 gdb_putc (int c)
1907 return gdb_stdout->putc (c);
1910 void
1911 gdb_putc (int c, struct ui_file *stream)
1913 return stream->putc (c);
1916 void
1917 gdb_vprintf (struct ui_file *stream, const char *format, va_list args)
1919 stream->vprintf (format, args);
1922 void
1923 gdb_vprintf (const char *format, va_list args)
1925 gdb_stdout->vprintf (format, args);
1928 void
1929 gdb_printf (struct ui_file *stream, const char *format, ...)
1931 va_list args;
1933 va_start (args, format);
1934 gdb_vprintf (stream, format, args);
1935 va_end (args);
1938 /* See utils.h. */
1940 void
1941 fprintf_styled (struct ui_file *stream, const ui_file_style &style,
1942 const char *format, ...)
1944 va_list args;
1946 stream->emit_style_escape (style);
1947 va_start (args, format);
1948 gdb_vprintf (stream, format, args);
1949 va_end (args);
1950 stream->emit_style_escape (ui_file_style ());
1953 void
1954 gdb_printf (const char *format, ...)
1956 va_list args;
1958 va_start (args, format);
1959 gdb_vprintf (gdb_stdout, format, args);
1960 va_end (args);
1964 void
1965 printf_unfiltered (const char *format, ...)
1967 va_list args;
1969 va_start (args, format);
1970 string_file file (gdb_stdout->can_emit_style_escape ());
1971 file.vprintf (format, args);
1972 gdb_stdout->puts_unfiltered (file.string ().c_str ());
1973 va_end (args);
1976 /* Easy -- but watch out!
1978 This routine is *not* a replacement for puts()! puts() appends a newline.
1979 This one doesn't, and had better not! */
1981 void
1982 gdb_puts (const char *string)
1984 gdb_stdout->puts (string);
1987 /* Return a pointer to N spaces and a null. The pointer is good
1988 until the next call to here. */
1989 const char *
1990 n_spaces (int n)
1992 char *t;
1993 static char *spaces = 0;
1994 static int max_spaces = -1;
1996 if (n > max_spaces)
1998 xfree (spaces);
1999 spaces = (char *) xmalloc (n + 1);
2000 for (t = spaces + n; t != spaces;)
2001 *--t = ' ';
2002 spaces[n] = '\0';
2003 max_spaces = n;
2006 return spaces + max_spaces - n;
2009 /* Print N spaces. */
2010 void
2011 print_spaces (int n, struct ui_file *stream)
2013 gdb_puts (n_spaces (n), stream);
2016 /* C++/ObjC demangler stuff. */
2018 /* fprintf_symbol attempts to demangle NAME, a symbol in language
2019 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2020 If the name is not mangled, or the language for the name is unknown, or
2021 demangling is off, the name is printed in its "raw" form. */
2023 void
2024 fprintf_symbol (struct ui_file *stream, const char *name,
2025 enum language lang, int arg_mode)
2027 if (name != NULL)
2029 /* If user wants to see raw output, no problem. */
2030 if (!demangle)
2032 gdb_puts (name, stream);
2034 else
2036 gdb::unique_xmalloc_ptr<char> demangled
2037 = language_def (lang)->demangle_symbol (name, arg_mode);
2038 gdb_puts (demangled ? demangled.get () : name, stream);
2043 /* True if CH is a character that can be part of a symbol name. I.e.,
2044 either a number, a letter, or a '_'. */
2046 static bool
2047 valid_identifier_name_char (int ch)
2049 return (ISALNUM (ch) || ch == '_');
2052 /* Skip to end of token, or to END, whatever comes first. Input is
2053 assumed to be a C++ operator name. */
2055 static const char *
2056 cp_skip_operator_token (const char *token, const char *end)
2058 const char *p = token;
2059 while (p != end && !ISSPACE (*p) && *p != '(')
2061 if (valid_identifier_name_char (*p))
2063 while (p != end && valid_identifier_name_char (*p))
2064 p++;
2065 return p;
2067 else
2069 /* Note, ordered such that among ops that share a prefix,
2070 longer comes first. This is so that the loop below can
2071 bail on first match. */
2072 static const char *ops[] =
2074 "[",
2075 "]",
2076 "~",
2077 ",",
2078 "-=", "--", "->", "-",
2079 "+=", "++", "+",
2080 "*=", "*",
2081 "/=", "/",
2082 "%=", "%",
2083 "|=", "||", "|",
2084 "&=", "&&", "&",
2085 "^=", "^",
2086 "!=", "!",
2087 "<<=", "<=", "<<", "<",
2088 ">>=", ">=", ">>", ">",
2089 "==", "=",
2092 for (const char *op : ops)
2094 size_t oplen = strlen (op);
2095 size_t lencmp = std::min<size_t> (oplen, end - p);
2097 if (strncmp (p, op, lencmp) == 0)
2098 return p + lencmp;
2100 /* Some unidentified character. Return it. */
2101 return p + 1;
2105 return p;
2108 /* Advance STRING1/STRING2 past whitespace. */
2110 static void
2111 skip_ws (const char *&string1, const char *&string2, const char *end_str2)
2113 while (ISSPACE (*string1))
2114 string1++;
2115 while (string2 < end_str2 && ISSPACE (*string2))
2116 string2++;
2119 /* True if STRING points at the start of a C++ operator name. START
2120 is the start of the string that STRING points to, hence when
2121 reading backwards, we must not read any character before START. */
2123 static bool
2124 cp_is_operator (const char *string, const char *start)
2126 return ((string == start
2127 || !valid_identifier_name_char (string[-1]))
2128 && strncmp (string, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
2129 && !valid_identifier_name_char (string[CP_OPERATOR_LEN]));
2132 /* If *NAME points at an ABI tag, skip it and return true. Otherwise
2133 leave *NAME unmodified and return false. (see GCC's abi_tag
2134 attribute), such names are demangled as e.g.,
2135 "function[abi:cxx11]()". */
2137 static bool
2138 skip_abi_tag (const char **name)
2140 const char *p = *name;
2142 if (startswith (p, "[abi:"))
2144 p += 5;
2146 while (valid_identifier_name_char (*p))
2147 p++;
2149 if (*p == ']')
2151 p++;
2152 *name = p;
2153 return true;
2156 return false;
2159 /* If *NAME points at a template parameter list, skip it and return true.
2160 Otherwise do nothing and return false. */
2162 static bool
2163 skip_template_parameter_list (const char **name)
2165 const char *p = *name;
2167 if (*p == '<')
2169 const char *template_param_list_end = find_toplevel_char (p + 1, '>');
2171 if (template_param_list_end == NULL)
2172 return false;
2174 p = template_param_list_end + 1;
2176 /* Skip any whitespace that might occur after the closing of the
2177 parameter list, but only if it is the end of parameter list. */
2178 const char *q = p;
2179 while (ISSPACE (*q))
2180 ++q;
2181 if (*q == '>')
2182 p = q;
2183 *name = p;
2184 return true;
2187 return false;
2190 /* See utils.h. */
2193 strncmp_iw_with_mode (const char *string1, const char *string2,
2194 size_t string2_len, strncmp_iw_mode mode,
2195 enum language language,
2196 completion_match_for_lcd *match_for_lcd,
2197 bool ignore_template_params)
2199 const char *string1_start = string1;
2200 const char *end_str2 = string2 + string2_len;
2201 bool skip_spaces = true;
2202 bool have_colon_op = (language == language_cplus
2203 || language == language_rust
2204 || language == language_fortran);
2206 gdb_assert (match_for_lcd == nullptr || match_for_lcd->empty ());
2208 while (1)
2210 if (skip_spaces
2211 || ((ISSPACE (*string1) && !valid_identifier_name_char (*string2))
2212 || (ISSPACE (*string2) && !valid_identifier_name_char (*string1))))
2214 skip_ws (string1, string2, end_str2);
2215 skip_spaces = false;
2218 /* Skip [abi:cxx11] tags in the symbol name if the lookup name
2219 doesn't include them. E.g.:
2221 string1: function[abi:cxx1](int)
2222 string2: function
2224 string1: function[abi:cxx1](int)
2225 string2: function(int)
2227 string1: Struct[abi:cxx1]::function()
2228 string2: Struct::function()
2230 string1: function(Struct[abi:cxx1], int)
2231 string2: function(Struct, int)
2233 if (string2 == end_str2
2234 || (*string2 != '[' && !valid_identifier_name_char (*string2)))
2236 const char *abi_start = string1;
2238 /* There can be more than one tag. */
2239 while (*string1 == '[' && skip_abi_tag (&string1))
2242 if (match_for_lcd != NULL && abi_start != string1)
2243 match_for_lcd->mark_ignored_range (abi_start, string1);
2245 while (ISSPACE (*string1))
2246 string1++;
2249 /* Skip template parameters in STRING1 if STRING2 does not contain
2250 any. E.g.:
2252 Case 1: User is looking for all functions named "foo".
2253 string1: foo <...> (...)
2254 string2: foo
2256 Case 2: User is looking for all methods named "foo" in all template
2257 class instantiations.
2258 string1: Foo<...>::foo <...> (...)
2259 string2: Foo::foo (...)
2261 Case 3: User is looking for a specific overload of a template
2262 function or method.
2263 string1: foo<...>
2264 string2: foo(...)
2266 Case 4: User is looking for a specific overload of a specific
2267 template instantiation.
2268 string1: foo<A> (...)
2269 string2: foo<B> (...)
2271 Case 5: User is looking wild parameter match.
2272 string1: foo<A<a<b<...> > > > (...)
2273 string2: foo<A
2275 if (language == language_cplus && ignore_template_params
2276 && *string1 == '<' && *string2 != '<')
2278 /* Skip any parameter list in STRING1. */
2279 const char *template_start = string1;
2281 if (skip_template_parameter_list (&string1))
2283 /* Don't mark the parameter list ignored if the user didn't
2284 try to ignore it. [Case #5 above] */
2285 if (*string2 != '\0'
2286 && match_for_lcd != NULL && template_start != string1)
2287 match_for_lcd->mark_ignored_range (template_start, string1);
2291 if (*string1 == '\0' || string2 == end_str2)
2292 break;
2294 /* Handle the :: operator. */
2295 if (have_colon_op && string1[0] == ':' && string1[1] == ':')
2297 if (*string2 != ':')
2298 return 1;
2300 string1++;
2301 string2++;
2303 if (string2 == end_str2)
2304 break;
2306 if (*string2 != ':')
2307 return 1;
2309 string1++;
2310 string2++;
2312 while (ISSPACE (*string1))
2313 string1++;
2314 while (string2 < end_str2 && ISSPACE (*string2))
2315 string2++;
2316 continue;
2319 /* Handle C++ user-defined operators. */
2320 else if (language == language_cplus
2321 && *string1 == 'o')
2323 if (cp_is_operator (string1, string1_start))
2325 /* An operator name in STRING1. Check STRING2. */
2326 size_t cmplen
2327 = std::min<size_t> (CP_OPERATOR_LEN, end_str2 - string2);
2328 if (strncmp (string1, string2, cmplen) != 0)
2329 return 1;
2331 string1 += cmplen;
2332 string2 += cmplen;
2334 if (string2 != end_str2)
2336 /* Check for "operatorX" in STRING2. */
2337 if (valid_identifier_name_char (*string2))
2338 return 1;
2340 skip_ws (string1, string2, end_str2);
2343 /* Handle operator(). */
2344 if (*string1 == '(')
2346 if (string2 == end_str2)
2348 if (mode == strncmp_iw_mode::NORMAL)
2349 return 0;
2350 else
2352 /* Don't break for the regular return at the
2353 bottom, because "operator" should not
2354 match "operator()", since this open
2355 parentheses is not the parameter list
2356 start. */
2357 return *string1 != '\0';
2361 if (*string1 != *string2)
2362 return 1;
2364 string1++;
2365 string2++;
2368 while (1)
2370 skip_ws (string1, string2, end_str2);
2372 /* Skip to end of token, or to END, whatever comes
2373 first. */
2374 const char *end_str1 = string1 + strlen (string1);
2375 const char *p1 = cp_skip_operator_token (string1, end_str1);
2376 const char *p2 = cp_skip_operator_token (string2, end_str2);
2378 cmplen = std::min (p1 - string1, p2 - string2);
2379 if (p2 == end_str2)
2381 if (strncmp (string1, string2, cmplen) != 0)
2382 return 1;
2384 else
2386 if (p1 - string1 != p2 - string2)
2387 return 1;
2388 if (strncmp (string1, string2, cmplen) != 0)
2389 return 1;
2392 string1 += cmplen;
2393 string2 += cmplen;
2395 if (*string1 == '\0' || string2 == end_str2)
2396 break;
2397 if (*string1 == '(' || *string2 == '(')
2398 break;
2400 /* If STRING1 or STRING2 starts with a template
2401 parameter list, break out of operator processing. */
2402 skip_ws (string1, string2, end_str2);
2403 if (*string1 == '<' || *string2 == '<')
2404 break;
2407 continue;
2411 if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2412 break;
2413 if (case_sensitivity == case_sensitive_off
2414 && (TOLOWER ((unsigned char) *string1)
2415 != TOLOWER ((unsigned char) *string2)))
2416 break;
2418 /* If we see any non-whitespace, non-identifier-name character
2419 (any of "()<>*&" etc.), then skip spaces the next time
2420 around. */
2421 if (!ISSPACE (*string1) && !valid_identifier_name_char (*string1))
2422 skip_spaces = true;
2424 string1++;
2425 string2++;
2428 if (string2 == end_str2)
2430 if (mode == strncmp_iw_mode::NORMAL)
2432 /* Strip abi tag markers from the matched symbol name.
2433 Usually the ABI marker will be found on function name
2434 (automatically added because the function returns an
2435 object marked with an ABI tag). However, it's also
2436 possible to see a marker in one of the function
2437 parameters, for example.
2439 string2 (lookup name):
2440 func
2441 symbol name:
2442 function(some_struct[abi:cxx11], int)
2444 and for completion LCD computation we want to say that
2445 the match was for:
2446 function(some_struct, int)
2448 if (match_for_lcd != NULL)
2450 while ((string1 = strstr (string1, "[abi:")) != NULL)
2452 const char *abi_start = string1;
2454 /* There can be more than one tag. */
2455 while (skip_abi_tag (&string1) && *string1 == '[')
2458 if (abi_start != string1)
2459 match_for_lcd->mark_ignored_range (abi_start, string1);
2463 return 0;
2465 else
2467 if (*string1 == '(')
2469 int p_count = 0;
2473 if (*string1 == '(')
2474 ++p_count;
2475 else if (*string1 == ')')
2476 --p_count;
2477 ++string1;
2479 while (*string1 != '\0' && p_count > 0);
2481 /* There maybe things like 'const' after the parameters,
2482 which we do want to ignore. However, if there's an '@'
2483 then this likely indicates something like '@plt' which we
2484 should not ignore. */
2485 return *string1 == '@';
2488 return *string1 == '\0' ? 0 : 1;
2492 else
2493 return 1;
2496 #if GDB_SELF_TEST
2498 /* Unit tests for strncmp_iw_with_mode. */
2500 #define CHECK_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2501 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2502 strncmp_iw_mode::MODE, \
2503 (LANG), (LCD)) == 0)
2505 #define CHECK_MATCH_LANG(S1, S2, MODE, LANG) \
2506 CHECK_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2508 #define CHECK_MATCH(S1, S2, MODE) \
2509 CHECK_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2511 #define CHECK_NO_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2512 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2513 strncmp_iw_mode::MODE, \
2514 (LANG)) != 0)
2516 #define CHECK_NO_MATCH_LANG(S1, S2, MODE, LANG) \
2517 CHECK_NO_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2519 #define CHECK_NO_MATCH(S1, S2, MODE) \
2520 CHECK_NO_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2522 static void
2523 check_scope_operator (enum language lang)
2525 CHECK_MATCH_LANG ("::", "::", NORMAL, lang);
2526 CHECK_MATCH_LANG ("::foo", "::", NORMAL, lang);
2527 CHECK_MATCH_LANG ("::foo", "::foo", NORMAL, lang);
2528 CHECK_MATCH_LANG (" :: foo ", "::foo", NORMAL, lang);
2529 CHECK_MATCH_LANG ("a::b", "a ::b", NORMAL, lang);
2530 CHECK_MATCH_LANG ("a::b", "a\t::b", NORMAL, lang);
2531 CHECK_MATCH_LANG ("a::b", "a \t::b", NORMAL, lang);
2532 CHECK_MATCH_LANG ("a::b", "a\t ::b", NORMAL, lang);
2533 CHECK_MATCH_LANG ("a::b", "a:: b", NORMAL, lang);
2534 CHECK_MATCH_LANG ("a::b", "a::\tb", NORMAL, lang);
2535 CHECK_MATCH_LANG ("a::b", "a:: \tb", NORMAL, lang);
2536 CHECK_MATCH_LANG ("a::b", "a::\t b", NORMAL, lang);
2537 CHECK_MATCH_LANG ("a::b", "a :: b", NORMAL, lang);
2538 CHECK_MATCH_LANG ("a::b", "a ::\tb", NORMAL, lang);
2539 CHECK_MATCH_LANG ("a::b", "a\t:: b", NORMAL, lang);
2540 CHECK_MATCH_LANG ("a::b", "a \t::\t b", NORMAL, lang);
2541 CHECK_MATCH_LANG ("a ::b", "a::b", NORMAL, lang);
2542 CHECK_MATCH_LANG ("a\t::b", "a::b", NORMAL, lang);
2543 CHECK_MATCH_LANG ("a \t::b", "a::b", NORMAL, lang);
2544 CHECK_MATCH_LANG ("a\t ::b", "a::b", NORMAL, lang);
2545 CHECK_MATCH_LANG ("a:: b", "a::b", NORMAL, lang);
2546 CHECK_MATCH_LANG ("a::\tb", "a::b", NORMAL, lang);
2547 CHECK_MATCH_LANG ("a:: \tb", "a::b", NORMAL, lang);
2548 CHECK_MATCH_LANG ("a::\t b", "a::b", NORMAL, lang);
2549 CHECK_MATCH_LANG ("a :: b", "a::b", NORMAL, lang);
2550 CHECK_MATCH_LANG ("a ::\tb", "a::b", NORMAL, lang);
2551 CHECK_MATCH_LANG ("a\t:: b", "a::b", NORMAL, lang);
2552 CHECK_MATCH_LANG ("a \t::\t b", "a::b", NORMAL, lang);
2553 CHECK_MATCH_LANG ("a::b::c", "a::b::c", NORMAL, lang);
2554 CHECK_MATCH_LANG (" a:: b:: c", "a::b::c", NORMAL, lang);
2555 CHECK_MATCH_LANG ("a::b::c", " a:: b:: c", NORMAL, lang);
2556 CHECK_MATCH_LANG ("a ::b ::c", "a::b::c", NORMAL, lang);
2557 CHECK_MATCH_LANG ("a::b::c", "a :: b:: c", NORMAL, lang);
2558 CHECK_MATCH_LANG ("\ta::\tb::\tc", "\ta::\tb::\tc", NORMAL, lang);
2559 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a\t::b\t::c\t", NORMAL, lang);
2560 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", " \ta:: \tb:: \tc", NORMAL, lang);
2561 CHECK_MATCH_LANG ("\t a::\t b::\t c", "\t a::\t b::\t c", NORMAL, lang);
2562 CHECK_MATCH_LANG ("a::b::c", "\ta::\tb::\tc", NORMAL, lang);
2563 CHECK_MATCH_LANG ("a::b::c", "a\t::b\t::c\t", NORMAL, lang);
2564 CHECK_MATCH_LANG ("a::b::c", " \ta:: \tb:: \tc", NORMAL, lang);
2565 CHECK_MATCH_LANG ("a::b::c", "\t a::\t b::\t c", NORMAL, lang);
2566 CHECK_MATCH_LANG ("\ta::\tb::\tc", "a::b::c", NORMAL, lang);
2567 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a::b::c", NORMAL, lang);
2568 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", "a::b::c", NORMAL, lang);
2569 CHECK_MATCH_LANG ("\t a::\t b::\t c", "a::b::c", NORMAL, lang);
2570 CHECK_MATCH_LANG ("a :: b:: c\t", "\ta :: b\t:: c\t\t", NORMAL, lang);
2571 CHECK_MATCH_LANG (" a::\t \t b:: c\t", "\ta ::b:: c\t\t",
2572 NORMAL, lang);
2573 CHECK_MATCH_LANG ("a :: b :: \t\t\tc\t",
2574 "\t\t\t\ta :: \t\t\t b \t\t::c",
2575 NORMAL, lang);
2576 CHECK_MATCH_LANG ("a::b()", "a", NORMAL, lang);
2577 CHECK_MATCH_LANG ("a::b()", "a::", NORMAL, lang);
2578 CHECK_MATCH_LANG ("a::b()", "a::b", NORMAL, lang);
2579 CHECK_MATCH_LANG ("a::b(a)", "a", NORMAL, lang);
2580 CHECK_MATCH_LANG ("a::b(a)", "a::", NORMAL, lang);
2581 CHECK_MATCH_LANG ("a::b(a)", "a::b", NORMAL, lang);
2582 CHECK_MATCH_LANG ("a::b(a,b)", "a", NORMAL, lang);
2583 CHECK_MATCH_LANG ("a::b(a,b)", "a::", NORMAL, lang);
2584 CHECK_MATCH_LANG ("a::b(a,b)", "a::b", NORMAL, lang);
2585 CHECK_MATCH_LANG ("a::b(a,b,c)", "a", NORMAL, lang);
2586 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::", NORMAL, lang);
2587 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::b", NORMAL, lang);
2589 CHECK_NO_MATCH_LANG ("a::", "::a", NORMAL, lang);
2590 CHECK_NO_MATCH_LANG ("::a", "::a()", NORMAL, lang);
2591 CHECK_NO_MATCH_LANG ("::", "::a", NORMAL, lang);
2592 CHECK_NO_MATCH_LANG ("a:::b", "a::b", NORMAL, lang);
2593 CHECK_NO_MATCH_LANG ("a::b()", "a::b(a)", NORMAL, lang);
2594 CHECK_NO_MATCH_LANG ("a::b(a)", "a::b()", NORMAL, lang);
2595 CHECK_NO_MATCH_LANG ("a::b(a,b)", "a::b(a,a)", NORMAL, lang);
2596 CHECK_NO_MATCH_LANG ("a::b", "a()", NORMAL, lang);
2597 CHECK_NO_MATCH_LANG ("a::b", "a::()", NORMAL, lang);
2598 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2599 CHECK_NO_MATCH_LANG ("a::b", "a(a)", NORMAL, lang);
2600 CHECK_NO_MATCH_LANG ("a::b", "a::(a)", NORMAL, lang);
2601 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2602 CHECK_NO_MATCH_LANG ("a::b", "a(a,b)", NORMAL, lang);
2603 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b)", NORMAL, lang);
2604 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b)", NORMAL, lang);
2605 CHECK_NO_MATCH_LANG ("a::b", "a(a,b,c)", NORMAL, lang);
2606 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b,c)", NORMAL, lang);
2607 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b,c)", NORMAL, lang);
2610 /* Callback for strncmp_iw_with_mode unit tests. */
2612 static void
2613 strncmp_iw_with_mode_tests ()
2615 /* Some of the following tests are nonsensical, but could be input by a
2616 deranged script (or user). */
2618 /* strncmp_iw_mode::NORMAL: strcmp()-like but ignore any whitespace... */
2620 CHECK_MATCH ("", "", NORMAL);
2621 CHECK_MATCH ("foo", "foo", NORMAL);
2622 CHECK_MATCH (" foo", "foo", NORMAL);
2623 CHECK_MATCH ("foo ", "foo", NORMAL);
2624 CHECK_MATCH (" foo ", "foo", NORMAL);
2625 CHECK_MATCH (" foo", "foo", NORMAL);
2626 CHECK_MATCH ("foo ", "foo", NORMAL);
2627 CHECK_MATCH (" foo ", "foo", NORMAL);
2628 CHECK_MATCH ("\tfoo", "foo", NORMAL);
2629 CHECK_MATCH ("foo\t", "foo", NORMAL);
2630 CHECK_MATCH ("\tfoo\t", "foo", NORMAL);
2631 CHECK_MATCH (" \tfoo \t", "foo", NORMAL);
2632 CHECK_MATCH ("\t foo\t ", "foo", NORMAL);
2633 CHECK_MATCH ("\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2634 "foo", NORMAL);
2635 CHECK_MATCH ("foo",
2636 "\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2637 NORMAL);
2638 CHECK_MATCH ("foo bar", "foo", NORMAL);
2639 CHECK_NO_MATCH ("foo", "bar", NORMAL);
2640 CHECK_NO_MATCH ("foo bar", "foobar", NORMAL);
2641 CHECK_NO_MATCH (" foo ", "bar", NORMAL);
2642 CHECK_NO_MATCH ("foo", " bar ", NORMAL);
2643 CHECK_NO_MATCH (" \t\t foo\t\t ", "\t \t \tbar\t", NORMAL);
2644 CHECK_NO_MATCH ("@!%&", "@!%&foo", NORMAL);
2646 /* ... and function parameters in STRING1. */
2647 CHECK_MATCH ("foo()", "foo()", NORMAL);
2648 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2649 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2650 CHECK_MATCH ("foo\t()", "foo()", NORMAL);
2651 CHECK_MATCH ("foo\t ()", "foo()", NORMAL);
2652 CHECK_MATCH ("foo \t()", "foo()", NORMAL);
2653 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2654 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2655 CHECK_MATCH ("foo()", "foo\t()", NORMAL);
2656 CHECK_MATCH ("foo()", "foo\t ()", NORMAL);
2657 CHECK_MATCH ("foo()", "foo \t()", NORMAL);
2658 CHECK_MATCH ("foo()", "foo()", NORMAL);
2659 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2660 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2661 CHECK_MATCH ("foo\t()", "foo\t()", NORMAL);
2662 CHECK_MATCH ("foo\t ()", "foo\t ()", NORMAL);
2663 CHECK_MATCH ("foo \t()", "foo \t()", NORMAL);
2664 CHECK_MATCH ("foo(a)", "foo(a)", NORMAL);
2665 CHECK_MATCH ("foo( a)", "foo(a)", NORMAL);
2666 CHECK_MATCH ("foo(a )", "foo(a)", NORMAL);
2667 CHECK_MATCH ("foo(\ta)", "foo(a)", NORMAL);
2668 CHECK_MATCH ("foo(a\t)", "foo(a)", NORMAL);
2669 CHECK_MATCH ("foo(\t a)", "foo(a)", NORMAL);
2670 CHECK_MATCH ("foo( \ta)", "foo(a)", NORMAL);
2671 CHECK_MATCH ("foo(a\t )", "foo(a)", NORMAL);
2672 CHECK_MATCH ("foo(a \t)", "foo(a)", NORMAL);
2673 CHECK_MATCH ("foo( a )", "foo(a)", NORMAL);
2674 CHECK_MATCH ("foo(\ta\t)", "foo(a)", NORMAL);
2675 CHECK_MATCH ("foo(\t a\t )", "foo(a)", NORMAL);
2676 CHECK_MATCH ("foo( \ta \t)", "foo(a)", NORMAL);
2677 CHECK_MATCH ("foo(a)", "foo( a)", NORMAL);
2678 CHECK_MATCH ("foo(a)", "foo(a )", NORMAL);
2679 CHECK_MATCH ("foo(a)", "foo(\ta)", NORMAL);
2680 CHECK_MATCH ("foo(a)", "foo(a\t)", NORMAL);
2681 CHECK_MATCH ("foo(a)", "foo(\t a)", NORMAL);
2682 CHECK_MATCH ("foo(a)", "foo( \ta)", NORMAL);
2683 CHECK_MATCH ("foo(a)", "foo(a\t )", NORMAL);
2684 CHECK_MATCH ("foo(a)", "foo(a \t)", NORMAL);
2685 CHECK_MATCH ("foo(a)", "foo( a )", NORMAL);
2686 CHECK_MATCH ("foo(a)", "foo(\ta\t)", NORMAL);
2687 CHECK_MATCH ("foo(a)", "foo(\t a\t )", NORMAL);
2688 CHECK_MATCH ("foo(a)", "foo( \ta \t)", NORMAL);
2689 CHECK_MATCH ("foo(a,b)", "foo(a,b)", NORMAL);
2690 CHECK_MATCH ("foo(a ,b)", "foo(a,b)", NORMAL);
2691 CHECK_MATCH ("foo(a\t,b)", "foo(a,b)", NORMAL);
2692 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2693 CHECK_MATCH ("foo(a\t,\tb)", "foo(a,b)", NORMAL);
2694 CHECK_MATCH ("foo(a \t,b)", "foo(a,b)", NORMAL);
2695 CHECK_MATCH ("foo(a\t ,b)", "foo(a,b)", NORMAL);
2696 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2697 CHECK_MATCH ("foo(a, \tb)", "foo(a,b)", NORMAL);
2698 CHECK_MATCH ("foo(a,\t b)", "foo(a,b)", NORMAL);
2699 CHECK_MATCH ("foo(a,b)", "foo(a ,b)", NORMAL);
2700 CHECK_MATCH ("foo(a,b)", "foo(a\t,b)", NORMAL);
2701 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2702 CHECK_MATCH ("foo(a,b)", "foo(a\t,\tb)", NORMAL);
2703 CHECK_MATCH ("foo(a,b)", "foo(a \t,b)", NORMAL);
2704 CHECK_MATCH ("foo(a,b)", "foo(a\t ,b)", NORMAL);
2705 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2706 CHECK_MATCH ("foo(a,b)", "foo(a, \tb)", NORMAL);
2707 CHECK_MATCH ("foo(a,b)", "foo(a,\t b)", NORMAL);
2708 CHECK_MATCH ("foo(a,b,c,d)", "foo(a,b,c,d)", NORMAL);
2709 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo(a,b,c,d)", NORMAL);
2710 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo( a , b , c , d )", NORMAL);
2711 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo", NORMAL);
2712 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo&*(a b * &)", NORMAL);
2713 CHECK_MATCH ("foo(a) b", "foo(a)", NORMAL);
2714 CHECK_MATCH ("*foo(*a&)", "*foo", NORMAL);
2715 CHECK_MATCH ("*foo(*a&)", "*foo(*a&)", NORMAL);
2716 CHECK_MATCH ("*a&b#c/^d$foo(*a&)", "*a&b#c/^d$foo", NORMAL);
2717 CHECK_MATCH ("* foo", "*foo", NORMAL);
2718 CHECK_MATCH ("foo&", "foo", NORMAL);
2719 CHECK_MATCH ("foo*", "foo", NORMAL);
2720 CHECK_MATCH ("foo.", "foo", NORMAL);
2721 CHECK_MATCH ("foo->", "foo", NORMAL);
2723 CHECK_NO_MATCH ("foo", "foo(", NORMAL);
2724 CHECK_NO_MATCH ("foo", "foo()", NORMAL);
2725 CHECK_NO_MATCH ("foo", "foo(a)", NORMAL);
2726 CHECK_NO_MATCH ("foo", "foo(a)", 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 &*", "foo (&)", NORMAL);
2734 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2735 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2736 CHECK_NO_MATCH ("foo(a*) b", "foo(a) b", NORMAL);
2737 CHECK_NO_MATCH ("foo[aqi:A](a)", "foo(b)", NORMAL);
2738 CHECK_NO_MATCH ("*foo", "foo", NORMAL);
2739 CHECK_NO_MATCH ("*foo", "foo*", NORMAL);
2740 CHECK_NO_MATCH ("*foo*", "*foo&", NORMAL);
2741 CHECK_NO_MATCH ("*foo*", "foo *", NORMAL);
2742 CHECK_NO_MATCH ("&foo", "foo", NORMAL);
2743 CHECK_NO_MATCH ("&foo", "foo&", NORMAL);
2744 CHECK_NO_MATCH ("foo&", "&foo", NORMAL);
2745 CHECK_NO_MATCH ("foo", "foo&", NORMAL);
2746 CHECK_NO_MATCH ("foo", "foo*", NORMAL);
2747 CHECK_NO_MATCH ("foo", "foo.", NORMAL);
2748 CHECK_NO_MATCH ("foo", "foo->", NORMAL);
2749 CHECK_NO_MATCH ("foo bar", "foo()", NORMAL);
2750 CHECK_NO_MATCH ("foo bar", "foo bar()", NORMAL);
2751 CHECK_NO_MATCH ("foo()", "foo(a)", NORMAL);
2752 CHECK_NO_MATCH ("*(*)&", "*(*)*", NORMAL);
2753 CHECK_NO_MATCH ("foo(a)", "foo()", NORMAL);
2754 CHECK_NO_MATCH ("foo(a)", "foo(b)", NORMAL);
2755 CHECK_NO_MATCH ("foo(a,b)", "foo(a,b,c)", NORMAL);
2756 CHECK_NO_MATCH ("foo(a\\b)", "foo()", NORMAL);
2757 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar", NORMAL);
2758 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar ( a b c \td\t)\t", NORMAL);
2760 /* Test scope operator. */
2761 check_scope_operator (language_minimal);
2762 check_scope_operator (language_cplus);
2763 check_scope_operator (language_fortran);
2764 check_scope_operator (language_rust);
2766 /* Test C++ user-defined operators. */
2767 CHECK_MATCH_LANG ("operator foo(int&)", "operator foo(int &)", NORMAL,
2768 language_cplus);
2769 CHECK_MATCH_LANG ("operator foo(int &)", "operator foo(int &)", NORMAL,
2770 language_cplus);
2771 CHECK_MATCH_LANG ("operator foo(int\t&)", "operator foo(int\t&)", NORMAL,
2772 language_cplus);
2773 CHECK_MATCH_LANG ("operator foo (int)", "operator foo(int)", NORMAL,
2774 language_cplus);
2775 CHECK_MATCH_LANG ("operator foo\t(int)", "operator foo(int)", NORMAL,
2776 language_cplus);
2777 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo(int)", NORMAL,
2778 language_cplus);
2779 CHECK_MATCH_LANG ("operator foo (int)", "operator foo \t(int)", NORMAL,
2780 language_cplus);
2781 CHECK_MATCH_LANG ("operator foo\t(int)", "operator foo \t(int)", NORMAL,
2782 language_cplus);
2783 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo \t(int)", NORMAL,
2784 language_cplus);
2786 CHECK_MATCH_LANG ("a::operator foo(int&)", "a::operator foo(int &)", NORMAL,
2787 language_cplus);
2788 CHECK_MATCH_LANG ("a :: operator foo(int &)", "a::operator foo(int &)", NORMAL,
2789 language_cplus);
2790 CHECK_MATCH_LANG ("a \t:: \toperator foo(int\t&)", "a::operator foo(int\t&)", NORMAL,
2791 language_cplus);
2792 CHECK_MATCH_LANG ("a::operator foo (int)", "a::operator foo(int)", NORMAL,
2793 language_cplus);
2794 CHECK_MATCH_LANG ("a::operator foo\t(int)", "a::operator foo(int)", NORMAL,
2795 language_cplus);
2796 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo(int)", NORMAL,
2797 language_cplus);
2798 CHECK_MATCH_LANG ("a::operator foo (int)", "a::operator foo \t(int)", NORMAL,
2799 language_cplus);
2800 CHECK_MATCH_LANG ("a::operator foo\t(int)", "a::operator foo \t(int)", NORMAL,
2801 language_cplus);
2802 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo \t(int)", NORMAL,
2803 language_cplus);
2805 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(char)", NORMAL,
2806 language_cplus);
2807 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int *)", NORMAL,
2808 language_cplus);
2809 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int &)", NORMAL,
2810 language_cplus);
2811 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int, char *)", NORMAL,
2812 language_cplus);
2813 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator bar(int)", NORMAL,
2814 language_cplus);
2816 CHECK_NO_MATCH_LANG ("a::operator b::foo(int)", "a::operator a::foo(char)", NORMAL,
2817 language_cplus);
2818 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int *)", NORMAL,
2819 language_cplus);
2820 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int &)", NORMAL,
2821 language_cplus);
2822 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int, char *)", NORMAL,
2823 language_cplus);
2824 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator bar(int)", NORMAL,
2825 language_cplus);
2827 /* Skip "[abi:cxx11]" tags in the symbol name if the lookup name
2828 doesn't include them. These are not language-specific in
2829 strncmp_iw_with_mode. */
2831 CHECK_MATCH ("foo[abi:a]", "foo", NORMAL);
2832 CHECK_MATCH ("foo[abi:a]()", "foo", NORMAL);
2833 CHECK_MATCH ("foo[abi:a](a)", "foo", NORMAL);
2834 CHECK_MATCH ("foo[abi:a](a&,b*)", "foo", NORMAL);
2835 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2836 CHECK_MATCH ("foo[abi:a](a,b) c", "foo(a,b) c", NORMAL);
2837 CHECK_MATCH ("foo[abi:a](a)", "foo(a)", NORMAL);
2838 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2839 CHECK_MATCH ("foo[abi:a]", "foo[abi:a]", NORMAL);
2840 CHECK_MATCH ("foo[ abi:a]", "foo[abi:a]", NORMAL);
2841 CHECK_MATCH ("foo[\tabi:a]", "foo[abi:a]", NORMAL);
2842 CHECK_MATCH ("foo[ \tabi:a]", "foo[abi:a]", NORMAL);
2843 CHECK_MATCH ("foo[\t abi:a]", "foo[abi:a]", NORMAL);
2844 CHECK_MATCH ("foo[abi :a]", "foo[abi:a]", NORMAL);
2845 CHECK_MATCH ("foo[abi\t:a]", "foo[abi:a]", NORMAL);
2846 CHECK_MATCH ("foo[abi \t:a]", "foo[abi:a]", NORMAL);
2847 CHECK_MATCH ("foo[abi\t :a]", "foo[abi:a]", NORMAL);
2848 CHECK_MATCH ("foo[abi:a]", "foo[ abi:a]", NORMAL);
2849 CHECK_MATCH ("foo[abi:a]", "foo[\tabi:a]", NORMAL);
2850 CHECK_MATCH ("foo[abi:a]", "foo[ \tabi:a]", NORMAL);
2851 CHECK_MATCH ("foo[abi:a]", "foo[\t abi:a]", NORMAL);
2852 CHECK_MATCH ("foo[abi:a]", "foo[abi :a]", NORMAL);
2853 CHECK_MATCH ("foo[abi:a]", "foo[abi\t:a]", NORMAL);
2854 CHECK_MATCH ("foo[abi:a]", "foo[abi \t:a]", NORMAL);
2855 CHECK_MATCH ("foo[abi:a]", "foo[abi\t :a]", NORMAL);
2856 CHECK_MATCH ("foo[abi:a]", "foo[abi:a ]", NORMAL);
2857 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t]", NORMAL);
2858 CHECK_MATCH ("foo[abi:a]", "foo[abi:a \t]", NORMAL);
2859 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t ]", NORMAL);
2860 CHECK_MATCH ("foo[abi:a,b]", "foo[abi:a,b]", NORMAL);
2861 CHECK_MATCH ("foo[abi:::]", "foo[abi:::]", NORMAL);
2862 CHECK_MATCH ("foo[abi : : : ]", "foo[abi:::]", NORMAL);
2863 CHECK_MATCH ("foo[abi:::]", "foo[abi : : : ]", NORMAL);
2864 CHECK_MATCH ("foo[ \t abi \t:\t: : \t]",
2865 "foo[ abi : \t ::]",
2866 NORMAL);
2867 CHECK_MATCH ("foo< bar< baz< quxi > > >(int)", "foo<bar<baz<quxi>>>(int)",
2868 NORMAL);
2869 CHECK_MATCH ("\tfoo<\tbar<\tbaz\t<\tquxi\t>\t>\t>(int)",
2870 "foo<bar<baz<quxi>>>(int)", NORMAL);
2871 CHECK_MATCH (" \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)",
2872 "foo<bar<baz<quxi>>>(int)", NORMAL);
2873 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2874 "foo < bar < baz < quxi > > > (int)", NORMAL);
2875 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2876 "\tfoo\t<\tbar\t<\tbaz\t<\tquxi\t>\t>\t>\t(int)", NORMAL);
2877 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2878 " \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)", NORMAL);
2879 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "fo", NORMAL);
2880 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo", NORMAL);
2881 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz>>::", NORMAL);
2882 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz> >::foo", NORMAL);
2883 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
2884 NORMAL);
2885 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", NORMAL);
2886 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar)", NORMAL);
2887 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar)", NORMAL);
2888 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar[abi:c])", NORMAL);
2889 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar[abi:c])", NORMAL);
2890 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar)", NORMAL);
2891 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c])",
2892 NORMAL);
2893 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo", NORMAL);
2894 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo()", NORMAL);
2895 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>", NORMAL);
2896 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz)", NORMAL);
2897 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:b])",
2898 NORMAL);
2899 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:A])",
2900 NORMAL);
2901 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz)",
2902 NORMAL);
2903 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:A]>(char*, baz)",
2904 NORMAL);
2905 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz[abi:b])",
2906 NORMAL);
2907 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])",
2908 "foo<bar[abi:a]>(char*, baz[abi:B])", NORMAL);
2910 CHECK_NO_MATCH ("foo", "foo[", NORMAL);
2911 CHECK_NO_MATCH ("foo", "foo[]", NORMAL);
2912 CHECK_NO_MATCH ("foo", "foo[ a]", NORMAL);
2913 CHECK_NO_MATCH ("foo", "foo[a ]", NORMAL);
2914 CHECK_NO_MATCH ("foo", "foo[ a ]", NORMAL);
2915 CHECK_NO_MATCH ("foo", "foo[\ta]", NORMAL);
2916 CHECK_NO_MATCH ("foo", "foo[a \t]", NORMAL);
2917 CHECK_NO_MATCH ("foo", "foo[a\t ]", NORMAL);
2918 CHECK_NO_MATCH ("foo", "foo[ \ta]", NORMAL);
2919 CHECK_NO_MATCH ("foo", "foo[\t a]", NORMAL);
2920 CHECK_NO_MATCH ("foo", "foo[ \ta \t]", NORMAL);
2921 CHECK_NO_MATCH ("foo", "foo[\t a\t ]", NORMAL);
2922 CHECK_NO_MATCH ("foo", "foo[abi]", NORMAL);
2923 CHECK_NO_MATCH ("foo", "foo[ abi]", NORMAL);
2924 CHECK_NO_MATCH ("foo", "foo[abi ]", NORMAL);
2925 CHECK_NO_MATCH ("foo", "foo[\tabi]", NORMAL);
2926 CHECK_NO_MATCH ("foo", "foo[abi\t]", NORMAL);
2927 CHECK_NO_MATCH ("foo", "foo[ \tabi]", NORMAL);
2928 CHECK_NO_MATCH ("foo", "foo[\t abi]", NORMAL);
2929 CHECK_NO_MATCH ("foo", "foo[abi \t]", NORMAL);
2930 CHECK_NO_MATCH ("foo", "foo[abi\t ]", NORMAL);
2931 CHECK_NO_MATCH ("foo", "foo[abi :]", NORMAL);
2932 CHECK_NO_MATCH ("foo", "foo[abi\t:]", NORMAL);
2933 CHECK_NO_MATCH ("foo", "foo[abi \t:]", NORMAL);
2934 CHECK_NO_MATCH ("foo", "foo[abi\t :]", NORMAL);
2935 CHECK_NO_MATCH ("foo", "foo[abi: ]", NORMAL);
2936 CHECK_NO_MATCH ("foo", "foo[abi:\t]", NORMAL);
2937 CHECK_NO_MATCH ("foo", "foo[abi: \t]", NORMAL);
2938 CHECK_NO_MATCH ("foo", "foo[abi:\t ]", NORMAL);
2939 CHECK_NO_MATCH ("foo", "foo[abi: a]", NORMAL);
2940 CHECK_NO_MATCH ("foo", "foo[abi:\ta]", NORMAL);
2941 CHECK_NO_MATCH ("foo", "foo[abi: \ta]", NORMAL);
2942 CHECK_NO_MATCH ("foo", "foo[abi:\t a]", NORMAL);
2943 CHECK_NO_MATCH ("foo", "foo[abi:a ]", NORMAL);
2944 CHECK_NO_MATCH ("foo", "foo[abi:a\t]", NORMAL);
2945 CHECK_NO_MATCH ("foo", "foo[abi:a \t]", NORMAL);
2946 CHECK_NO_MATCH ("foo", "foo[abi:a\t ]", NORMAL);
2947 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2948 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2949 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2950 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2951 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) c", NORMAL);
2952 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) .", NORMAL);
2953 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) *", NORMAL);
2954 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) &", NORMAL);
2955 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) c", NORMAL);
2956 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) .", NORMAL);
2957 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) *", NORMAL);
2958 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) &", NORMAL);
2959 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)c", NORMAL);
2960 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b).", NORMAL);
2961 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)*", NORMAL);
2962 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)&", NORMAL);
2963 CHECK_NO_MATCH ("foo[abi:a](a,b) d", "foo(a,b) c", NORMAL);
2964 CHECK_NO_MATCH ("foo[abi:a](a)", "foo()", NORMAL);
2965 CHECK_NO_MATCH ("foo[abi:a](a)", "foo(b)", NORMAL);
2966 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:b](a)", NORMAL);
2967 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:a](b)", NORMAL);
2968 CHECK_NO_MATCH ("foo[abi:]", "foo[abi:a]", NORMAL);
2969 CHECK_NO_MATCH ("foo[abi:", "foo[abi:a]", NORMAL);
2970 CHECK_NO_MATCH ("foo[abi:]", "foo[abi:a", NORMAL);
2971 CHECK_NO_MATCH ("foo[abi:,]", "foo[abi:a]", NORMAL);
2972 CHECK_NO_MATCH ("foo[abi:a,b]", "foo[abi:a]", NORMAL);
2973 CHECK_NO_MATCH ("foo[abi::a]", "foo[abi:a]", NORMAL);
2974 CHECK_NO_MATCH ("foo[abi:,([a]", "foo[abi:a]", NORMAL);
2976 CHECK_MATCH ("foo <a, b [, c (", "foo", NORMAL);
2977 CHECK_MATCH ("foo >a, b ], c )", "foo", NORMAL);
2978 CHECK_MATCH ("@!%&\\*", "@!%&\\*", NORMAL);
2979 CHECK_MATCH ("()", "()", NORMAL);
2980 CHECK_MATCH ("*(*)*", "*(*)*", NORMAL);
2981 CHECK_MATCH ("[]", "[]", NORMAL);
2982 CHECK_MATCH ("<>", "<>", NORMAL);
2984 /* strncmp_iw_with_mode::MATCH_PARAMS: the "strcmp_iw hack." */
2985 CHECK_MATCH ("foo2", "foo", NORMAL);
2986 CHECK_NO_MATCH ("foo2", "foo", MATCH_PARAMS);
2987 CHECK_NO_MATCH ("foo2", "foo ", MATCH_PARAMS);
2988 CHECK_NO_MATCH ("foo2", "foo\t", MATCH_PARAMS);
2989 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2990 CHECK_NO_MATCH ("foo2", "foo\t ", MATCH_PARAMS);
2991 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2992 CHECK_NO_MATCH ("foo2", " foo", MATCH_PARAMS);
2993 CHECK_NO_MATCH ("foo2", "\tfoo", MATCH_PARAMS);
2994 CHECK_NO_MATCH ("foo2", " \tfoo", MATCH_PARAMS);
2995 CHECK_NO_MATCH ("foo2", "\t foo", MATCH_PARAMS);
2996 CHECK_NO_MATCH (" foo2", "foo", MATCH_PARAMS);
2997 CHECK_NO_MATCH ("\tfoo2", "foo", MATCH_PARAMS);
2998 CHECK_NO_MATCH (" \tfoo2", "foo", MATCH_PARAMS);
2999 CHECK_NO_MATCH ("\t foo2", "foo", MATCH_PARAMS);
3000 CHECK_NO_MATCH (" foo2 ", " foo ", MATCH_PARAMS);
3001 CHECK_NO_MATCH ("\tfoo2\t", "\tfoo\t", MATCH_PARAMS);
3002 CHECK_NO_MATCH (" \tfoo2 \t", " \tfoo \t", MATCH_PARAMS);
3003 CHECK_NO_MATCH ("\t foo2\t ", "\t foo\t ", MATCH_PARAMS);
3004 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
3005 CHECK_NO_MATCH ("foo2\t", "foo", MATCH_PARAMS);
3006 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
3007 CHECK_NO_MATCH ("foo2 \t", "foo", MATCH_PARAMS);
3008 CHECK_NO_MATCH ("foo2\t ", "foo", MATCH_PARAMS);
3009 CHECK_NO_MATCH ("foo2 (args)", "foo", MATCH_PARAMS);
3010 CHECK_NO_MATCH ("foo2 (args)", "foo", MATCH_PARAMS);
3011 CHECK_NO_MATCH ("foo2\t(args)", "foo", MATCH_PARAMS);
3012 CHECK_NO_MATCH ("foo2 \t(args)", "foo", MATCH_PARAMS);
3013 CHECK_NO_MATCH ("foo2\t (args)", "foo", MATCH_PARAMS);
3014 CHECK_NO_MATCH ("foo2 ( args)", "foo", MATCH_PARAMS);
3015 CHECK_NO_MATCH ("foo2(args )", "foo", MATCH_PARAMS);
3016 CHECK_NO_MATCH ("foo2(args\t)", "foo", MATCH_PARAMS);
3017 CHECK_NO_MATCH ("foo2 (args \t)", "foo", MATCH_PARAMS);
3018 CHECK_NO_MATCH ("foo2 (args\t )", "foo", MATCH_PARAMS);
3019 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
3020 MATCH_PARAMS);
3021 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", MATCH_PARAMS);
3022 CHECK_NO_MATCH ("foo(args)@plt", "foo", MATCH_PARAMS);
3023 CHECK_NO_MATCH ("foo((())args(()))@plt", "foo", MATCH_PARAMS);
3024 CHECK_MATCH ("foo((())args(()))", "foo", MATCH_PARAMS);
3025 CHECK_MATCH ("foo(args) const", "foo", MATCH_PARAMS);
3026 CHECK_MATCH ("foo(args)const", "foo", MATCH_PARAMS);
3028 /* strncmp_iw_with_mode also supports case insensitivity. */
3030 CHECK_NO_MATCH ("FoO", "foo", NORMAL);
3031 CHECK_NO_MATCH ("FoO", "foo", MATCH_PARAMS);
3033 scoped_restore restore_case = make_scoped_restore (&case_sensitivity);
3034 case_sensitivity = case_sensitive_off;
3036 CHECK_MATCH ("FoO", "foo", NORMAL);
3037 CHECK_MATCH ("FoO", "foo", MATCH_PARAMS);
3038 CHECK_MATCH ("foo", "FoO", NORMAL);
3039 CHECK_MATCH ("foo", "FoO", MATCH_PARAMS);
3041 CHECK_MATCH ("FoO[AbI:abC]()", "foo", NORMAL);
3042 CHECK_NO_MATCH ("FoO[AbI:abC]()", "foo", MATCH_PARAMS);
3043 CHECK_MATCH ("FoO2[AbI:abC]()", "foo", NORMAL);
3044 CHECK_NO_MATCH ("FoO2[AbI:abC]()", "foo", MATCH_PARAMS);
3046 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:abC]()", NORMAL);
3047 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:AbC]()", MATCH_PARAMS);
3048 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3049 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", MATCH_PARAMS);
3050 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3051 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)",
3052 MATCH_PARAMS);
3053 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3054 NORMAL);
3055 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3056 MATCH_PARAMS);
3060 #undef MATCH
3061 #undef NO_MATCH
3062 #endif
3064 /* See utils.h. */
3067 strncmp_iw (const char *string1, const char *string2, size_t string2_len)
3069 return strncmp_iw_with_mode (string1, string2, string2_len,
3070 strncmp_iw_mode::NORMAL, language_minimal);
3073 /* See utils.h. */
3076 strcmp_iw (const char *string1, const char *string2)
3078 return strncmp_iw_with_mode (string1, string2, strlen (string2),
3079 strncmp_iw_mode::MATCH_PARAMS, language_minimal);
3082 /* This is like strcmp except that it ignores whitespace and treats
3083 '(' as the first non-NULL character in terms of ordering. Like
3084 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
3085 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
3086 according to that ordering.
3088 If a list is sorted according to this function and if you want to
3089 find names in the list that match some fixed NAME according to
3090 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
3091 where this function would put NAME.
3093 This function must be neutral to the CASE_SENSITIVITY setting as the user
3094 may choose it during later lookup. Therefore this function always sorts
3095 primarily case-insensitively and secondarily case-sensitively.
3097 Here are some examples of why using strcmp to sort is a bad idea:
3099 Whitespace example:
3101 Say your partial symtab contains: "foo<char *>", "goo". Then, if
3102 we try to do a search for "foo<char*>", strcmp will locate this
3103 after "foo<char *>" and before "goo". Then lookup_partial_symbol
3104 will start looking at strings beginning with "goo", and will never
3105 see the correct match of "foo<char *>".
3107 Parenthesis example:
3109 In practice, this is less like to be an issue, but I'll give it a
3110 shot. Let's assume that '$' is a legitimate character to occur in
3111 symbols. (Which may well even be the case on some systems.) Then
3112 say that the partial symbol table contains "foo$" and "foo(int)".
3113 strcmp will put them in this order, since '$' < '('. Now, if the
3114 user searches for "foo", then strcmp will sort "foo" before "foo$".
3115 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
3116 "foo") is false, so it won't proceed to the actual match of
3117 "foo(int)" with "foo". */
3120 strcmp_iw_ordered (const char *string1, const char *string2)
3122 const char *saved_string1 = string1, *saved_string2 = string2;
3123 enum case_sensitivity case_pass = case_sensitive_off;
3125 for (;;)
3127 /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
3128 Provide stub characters if we are already at the end of one of the
3129 strings. */
3130 char c1 = 'X', c2 = 'X';
3132 while (*string1 != '\0' && *string2 != '\0')
3134 while (ISSPACE (*string1))
3135 string1++;
3136 while (ISSPACE (*string2))
3137 string2++;
3139 switch (case_pass)
3141 case case_sensitive_off:
3142 c1 = TOLOWER ((unsigned char) *string1);
3143 c2 = TOLOWER ((unsigned char) *string2);
3144 break;
3145 case case_sensitive_on:
3146 c1 = *string1;
3147 c2 = *string2;
3148 break;
3150 if (c1 != c2)
3151 break;
3153 if (*string1 != '\0')
3155 string1++;
3156 string2++;
3160 switch (*string1)
3162 /* Characters are non-equal unless they're both '\0'; we want to
3163 make sure we get the comparison right according to our
3164 comparison in the cases where one of them is '\0' or '('. */
3165 case '\0':
3166 if (*string2 == '\0')
3167 break;
3168 else
3169 return -1;
3170 case '(':
3171 if (*string2 == '\0')
3172 return 1;
3173 else
3174 return -1;
3175 default:
3176 if (*string2 == '\0' || *string2 == '(')
3177 return 1;
3178 else if (c1 > c2)
3179 return 1;
3180 else if (c1 < c2)
3181 return -1;
3182 /* PASSTHRU */
3185 if (case_pass == case_sensitive_on)
3186 return 0;
3188 /* Otherwise the strings were equal in case insensitive way, make
3189 a more fine grained comparison in a case sensitive way. */
3191 case_pass = case_sensitive_on;
3192 string1 = saved_string1;
3193 string2 = saved_string2;
3199 static void
3200 show_debug_timestamp (struct ui_file *file, int from_tty,
3201 struct cmd_list_element *c, const char *value)
3203 gdb_printf (file, _("Timestamping debugging messages is %s.\n"),
3204 value);
3208 const char *
3209 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
3211 /* Truncate address to the size of a target address, avoiding shifts
3212 larger or equal than the width of a CORE_ADDR. The local
3213 variable ADDR_BIT stops the compiler reporting a shift overflow
3214 when it won't occur. */
3215 /* NOTE: This assumes that the significant address information is
3216 kept in the least significant bits of ADDR - the upper bits were
3217 either zero or sign extended. Should gdbarch_address_to_pointer or
3218 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
3220 int addr_bit = gdbarch_addr_bit (gdbarch);
3222 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3223 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
3224 return hex_string (addr);
3227 /* This function is described in "defs.h". */
3229 const char *
3230 print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
3232 int addr_bit = gdbarch_addr_bit (gdbarch);
3234 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3235 address &= ((CORE_ADDR) 1 << addr_bit) - 1;
3237 /* FIXME: cagney/2002-05-03: Need local_address_string() function
3238 that returns the language localized string formatted to a width
3239 based on gdbarch_addr_bit. */
3240 if (addr_bit <= 32)
3241 return hex_string_custom (address, 8);
3242 else
3243 return hex_string_custom (address, 16);
3246 /* Convert a string back into a CORE_ADDR. */
3247 CORE_ADDR
3248 string_to_core_addr (const char *my_string)
3250 CORE_ADDR addr = 0;
3252 if (my_string[0] == '0' && TOLOWER (my_string[1]) == 'x')
3254 /* Assume that it is in hex. */
3255 int i;
3257 for (i = 2; my_string[i] != '\0'; i++)
3259 if (ISDIGIT (my_string[i]))
3260 addr = (my_string[i] - '0') + (addr * 16);
3261 else if (ISXDIGIT (my_string[i]))
3262 addr = (TOLOWER (my_string[i]) - 'a' + 0xa) + (addr * 16);
3263 else
3264 error (_("invalid hex \"%s\""), my_string);
3267 else
3269 /* Assume that it is in decimal. */
3270 int i;
3272 for (i = 0; my_string[i] != '\0'; i++)
3274 if (ISDIGIT (my_string[i]))
3275 addr = (my_string[i] - '0') + (addr * 10);
3276 else
3277 error (_("invalid decimal \"%s\""), my_string);
3281 return addr;
3284 #if GDB_SELF_TEST
3286 static void
3287 gdb_realpath_check_trailer (const char *input, const char *trailer)
3289 gdb::unique_xmalloc_ptr<char> result = gdb_realpath (input);
3291 size_t len = strlen (result.get ());
3292 size_t trail_len = strlen (trailer);
3294 SELF_CHECK (len >= trail_len
3295 && strcmp (result.get () + len - trail_len, trailer) == 0);
3298 static void
3299 gdb_realpath_tests ()
3301 /* A file which contains a directory prefix. */
3302 gdb_realpath_check_trailer ("./xfullpath.exp", "/xfullpath.exp");
3303 /* A file which contains a directory prefix. */
3304 gdb_realpath_check_trailer ("../../defs.h", "/defs.h");
3305 /* A one-character filename. */
3306 gdb_realpath_check_trailer ("./a", "/a");
3307 /* A file in the root directory. */
3308 gdb_realpath_check_trailer ("/root_file_which_should_exist",
3309 "/root_file_which_should_exist");
3310 /* A file which does not have a directory prefix. */
3311 gdb_realpath_check_trailer ("xfullpath.exp", "xfullpath.exp");
3312 /* A one-char filename without any directory prefix. */
3313 gdb_realpath_check_trailer ("a", "a");
3314 /* An empty filename. */
3315 gdb_realpath_check_trailer ("", "");
3318 /* Test the gdb_argv::as_array_view method. */
3320 static void
3321 gdb_argv_as_array_view_test ()
3324 gdb_argv argv;
3326 gdb::array_view<char *> view = argv.as_array_view ();
3328 SELF_CHECK (view.data () == nullptr);
3329 SELF_CHECK (view.size () == 0);
3332 gdb_argv argv ("une bonne 50");
3334 gdb::array_view<char *> view = argv.as_array_view ();
3336 SELF_CHECK (view.size () == 3);
3337 SELF_CHECK (strcmp (view[0], "une") == 0);
3338 SELF_CHECK (strcmp (view[1], "bonne") == 0);
3339 SELF_CHECK (strcmp (view[2], "50") == 0);
3343 #endif /* GDB_SELF_TEST */
3345 /* Simple, portable version of dirname that does not modify its
3346 argument. */
3348 std::string
3349 ldirname (const char *filename)
3351 std::string dirname;
3352 const char *base = lbasename (filename);
3354 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3355 --base;
3357 if (base == filename)
3358 return dirname;
3360 dirname = std::string (filename, base - filename);
3362 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3363 create "d:./bar" later instead of the (different) "d:/bar". */
3364 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3365 && !IS_DIR_SEPARATOR (filename[0]))
3366 dirname[base++ - filename] = '.';
3368 return dirname;
3371 /* Return ARGS parsed as a valid pid, or throw an error. */
3374 parse_pid_to_attach (const char *args)
3376 unsigned long pid;
3377 char *dummy;
3379 if (!args)
3380 error_no_arg (_("process-id to attach"));
3382 dummy = (char *) args;
3383 pid = strtoul (args, &dummy, 0);
3384 /* Some targets don't set errno on errors, grrr! */
3385 if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3386 error (_("Illegal process-id: %s."), args);
3388 return pid;
3391 /* Substitute all occurrences of string FROM by string TO in *STRINGP. *STRINGP
3392 must come from xrealloc-compatible allocator and it may be updated. FROM
3393 needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
3394 located at the start or end of *STRINGP. */
3396 void
3397 substitute_path_component (char **stringp, const char *from, const char *to)
3399 char *string = *stringp, *s;
3400 const size_t from_len = strlen (from);
3401 const size_t to_len = strlen (to);
3403 for (s = string;;)
3405 s = strstr (s, from);
3406 if (s == NULL)
3407 break;
3409 if ((s == string || IS_DIR_SEPARATOR (s[-1])
3410 || s[-1] == DIRNAME_SEPARATOR)
3411 && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
3412 || s[from_len] == DIRNAME_SEPARATOR))
3414 char *string_new;
3416 string_new
3417 = (char *) xrealloc (string, (strlen (string) + to_len + 1));
3419 /* Relocate the current S pointer. */
3420 s = s - string + string_new;
3421 string = string_new;
3423 /* Replace from by to. */
3424 memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
3425 memcpy (s, to, to_len);
3427 s += to_len;
3429 else
3430 s++;
3433 *stringp = string;
3436 #ifdef HAVE_WAITPID
3438 #ifdef SIGALRM
3440 /* SIGALRM handler for waitpid_with_timeout. */
3442 static void
3443 sigalrm_handler (int signo)
3445 /* Nothing to do. */
3448 #endif
3450 /* Wrapper to wait for child PID to die with TIMEOUT.
3451 TIMEOUT is the time to stop waiting in seconds.
3452 If TIMEOUT is zero, pass WNOHANG to waitpid.
3453 Returns PID if it was successfully waited for, otherwise -1.
3455 Timeouts are currently implemented with alarm and SIGALRM.
3456 If the host does not support them, this waits "forever".
3457 It would be odd though for a host to have waitpid and not SIGALRM. */
3459 pid_t
3460 wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3462 pid_t waitpid_result;
3464 gdb_assert (pid > 0);
3465 gdb_assert (timeout >= 0);
3467 if (timeout > 0)
3469 #ifdef SIGALRM
3470 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3471 struct sigaction sa, old_sa;
3473 sa.sa_handler = sigalrm_handler;
3474 sigemptyset (&sa.sa_mask);
3475 sa.sa_flags = 0;
3476 sigaction (SIGALRM, &sa, &old_sa);
3477 #else
3478 sighandler_t ofunc;
3480 ofunc = signal (SIGALRM, sigalrm_handler);
3481 #endif
3483 alarm (timeout);
3484 #endif
3486 waitpid_result = waitpid (pid, status, 0);
3488 #ifdef SIGALRM
3489 alarm (0);
3490 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3491 sigaction (SIGALRM, &old_sa, NULL);
3492 #else
3493 signal (SIGALRM, ofunc);
3494 #endif
3495 #endif
3497 else
3498 waitpid_result = waitpid (pid, status, WNOHANG);
3500 if (waitpid_result == pid)
3501 return pid;
3502 else
3503 return -1;
3506 #endif /* HAVE_WAITPID */
3508 /* Provide fnmatch compatible function for FNM_FILE_NAME matching of host files.
3509 Both FNM_FILE_NAME and FNM_NOESCAPE must be set in FLAGS.
3511 It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3512 HAVE_CASE_INSENSITIVE_FILE_SYSTEM. */
3515 gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3517 gdb_assert ((flags & FNM_FILE_NAME) != 0);
3519 /* It is unclear how '\' escaping vs. directory separator should coexist. */
3520 gdb_assert ((flags & FNM_NOESCAPE) != 0);
3522 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3524 char *pattern_slash, *string_slash;
3526 /* Replace '\' by '/' in both strings. */
3528 pattern_slash = (char *) alloca (strlen (pattern) + 1);
3529 strcpy (pattern_slash, pattern);
3530 pattern = pattern_slash;
3531 for (; *pattern_slash != 0; pattern_slash++)
3532 if (IS_DIR_SEPARATOR (*pattern_slash))
3533 *pattern_slash = '/';
3535 string_slash = (char *) alloca (strlen (string) + 1);
3536 strcpy (string_slash, string);
3537 string = string_slash;
3538 for (; *string_slash != 0; string_slash++)
3539 if (IS_DIR_SEPARATOR (*string_slash))
3540 *string_slash = '/';
3542 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3544 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3545 flags |= FNM_CASEFOLD;
3546 #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3548 return fnmatch (pattern, string, flags);
3551 /* Return the number of path elements in PATH.
3552 / = 1
3553 /foo = 2
3554 /foo/ = 2
3555 foo/bar = 2
3556 foo/ = 1 */
3559 count_path_elements (const char *path)
3561 int count = 0;
3562 const char *p = path;
3564 if (HAS_DRIVE_SPEC (p))
3566 p = STRIP_DRIVE_SPEC (p);
3567 ++count;
3570 while (*p != '\0')
3572 if (IS_DIR_SEPARATOR (*p))
3573 ++count;
3574 ++p;
3577 /* Backup one if last character is /, unless it's the only one. */
3578 if (p > path + 1 && IS_DIR_SEPARATOR (p[-1]))
3579 --count;
3581 /* Add one for the file name, if present. */
3582 if (p > path && !IS_DIR_SEPARATOR (p[-1]))
3583 ++count;
3585 return count;
3588 /* Remove N leading path elements from PATH.
3589 N must be non-negative.
3590 If PATH has more than N path elements then return NULL.
3591 If PATH has exactly N path elements then return "".
3592 See count_path_elements for a description of how we do the counting. */
3594 const char *
3595 strip_leading_path_elements (const char *path, int n)
3597 int i = 0;
3598 const char *p = path;
3600 gdb_assert (n >= 0);
3602 if (n == 0)
3603 return p;
3605 if (HAS_DRIVE_SPEC (p))
3607 p = STRIP_DRIVE_SPEC (p);
3608 ++i;
3611 while (i < n)
3613 while (*p != '\0' && !IS_DIR_SEPARATOR (*p))
3614 ++p;
3615 if (*p == '\0')
3617 if (i + 1 == n)
3618 return "";
3619 return NULL;
3621 ++p;
3622 ++i;
3625 return p;
3628 /* See utils.h. */
3630 void
3631 copy_bitwise (gdb_byte *dest, ULONGEST dest_offset,
3632 const gdb_byte *source, ULONGEST source_offset,
3633 ULONGEST nbits, int bits_big_endian)
3635 unsigned int buf, avail;
3637 if (nbits == 0)
3638 return;
3640 if (bits_big_endian)
3642 /* Start from the end, then work backwards. */
3643 dest_offset += nbits - 1;
3644 dest += dest_offset / 8;
3645 dest_offset = 7 - dest_offset % 8;
3646 source_offset += nbits - 1;
3647 source += source_offset / 8;
3648 source_offset = 7 - source_offset % 8;
3650 else
3652 dest += dest_offset / 8;
3653 dest_offset %= 8;
3654 source += source_offset / 8;
3655 source_offset %= 8;
3658 /* Fill BUF with DEST_OFFSET bits from the destination and 8 -
3659 SOURCE_OFFSET bits from the source. */
3660 buf = *(bits_big_endian ? source-- : source++) >> source_offset;
3661 buf <<= dest_offset;
3662 buf |= *dest & ((1 << dest_offset) - 1);
3664 /* NBITS: bits yet to be written; AVAIL: BUF's fill level. */
3665 nbits += dest_offset;
3666 avail = dest_offset + 8 - source_offset;
3668 /* Flush 8 bits from BUF, if appropriate. */
3669 if (nbits >= 8 && avail >= 8)
3671 *(bits_big_endian ? dest-- : dest++) = buf;
3672 buf >>= 8;
3673 avail -= 8;
3674 nbits -= 8;
3677 /* Copy the middle part. */
3678 if (nbits >= 8)
3680 size_t len = nbits / 8;
3682 /* Use a faster method for byte-aligned copies. */
3683 if (avail == 0)
3685 if (bits_big_endian)
3687 dest -= len;
3688 source -= len;
3689 memcpy (dest + 1, source + 1, len);
3691 else
3693 memcpy (dest, source, len);
3694 dest += len;
3695 source += len;
3698 else
3700 while (len--)
3702 buf |= *(bits_big_endian ? source-- : source++) << avail;
3703 *(bits_big_endian ? dest-- : dest++) = buf;
3704 buf >>= 8;
3707 nbits %= 8;
3710 /* Write the last byte. */
3711 if (nbits)
3713 if (avail < nbits)
3714 buf |= *source << avail;
3716 buf &= (1 << nbits) - 1;
3717 *dest = (*dest & (~0U << nbits)) | buf;
3721 /* See utils.h. */
3723 std::string
3724 extract_single_filename_arg (const char *args)
3726 if (args == nullptr)
3727 return {};
3729 std::string filename = extract_string_maybe_quoted (&args);
3730 args = skip_spaces (args);
3731 if (*args != '\0')
3732 error (_("Junk after filename \"%s\": %s"), filename.c_str (), args);
3733 if (!filename.empty ())
3734 filename = gdb_tilde_expand (filename.c_str ());
3735 return filename;
3738 #if GDB_SELF_TEST
3739 static void
3740 test_assign_set_return_if_changed ()
3742 bool changed;
3743 int a;
3745 for (bool initial : { false, true })
3747 changed = initial;
3748 a = 1;
3749 assign_set_if_changed (a, 1, changed);
3750 SELF_CHECK (a == 1);
3751 SELF_CHECK (changed == initial);
3754 for (bool initial : { false, true })
3756 changed = initial;
3757 a = 1;
3758 assign_set_if_changed (a, 2, changed);
3759 SELF_CHECK (a == 2);
3760 SELF_CHECK (changed == true);
3763 a = 1;
3764 changed = assign_return_if_changed (a, 1);
3765 SELF_CHECK (a == 1);
3766 SELF_CHECK (changed == false);
3768 a = 1;
3769 assign_set_if_changed (a, 2, changed);
3770 SELF_CHECK (a == 2);
3771 SELF_CHECK (changed == true);
3773 #endif
3775 void _initialize_utils ();
3776 void
3777 _initialize_utils ()
3779 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
3780 Set number of characters where GDB should wrap lines of its output."), _("\
3781 Show number of characters where GDB should wrap lines of its output."), _("\
3782 This affects where GDB wraps its output to fit the screen width.\n\
3783 Setting this to \"unlimited\" or zero prevents GDB from wrapping its output."),
3784 set_width_command,
3785 show_chars_per_line,
3786 &setlist, &showlist);
3788 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
3789 Set number of lines in a page for GDB output pagination."), _("\
3790 Show number of lines in a page for GDB output pagination."), _("\
3791 This affects the number of lines after which GDB will pause\n\
3792 its output and ask you whether to continue.\n\
3793 Setting this to \"unlimited\" or zero causes GDB never pause during output."),
3794 set_height_command,
3795 show_lines_per_page,
3796 &setlist, &showlist);
3798 add_setshow_boolean_cmd ("pagination", class_support,
3799 &pagination_enabled, _("\
3800 Set state of GDB output pagination."), _("\
3801 Show state of GDB output pagination."), _("\
3802 When pagination is ON, GDB pauses at end of each screenful of\n\
3803 its output and asks you whether to continue.\n\
3804 Turning pagination off is an alternative to \"set height unlimited\"."),
3805 NULL,
3806 show_pagination_enabled,
3807 &setlist, &showlist);
3809 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
3810 &sevenbit_strings, _("\
3811 Set printing of 8-bit characters in strings as \\nnn."), _("\
3812 Show printing of 8-bit characters in strings as \\nnn."), NULL,
3813 NULL,
3814 show_sevenbit_strings,
3815 &setprintlist, &showprintlist);
3817 add_setshow_boolean_cmd ("timestamp", class_maintenance,
3818 &debug_timestamp, _("\
3819 Set timestamping of debugging messages."), _("\
3820 Show timestamping of debugging messages."), _("\
3821 When set, debugging messages will be marked with seconds and microseconds."),
3822 NULL,
3823 show_debug_timestamp,
3824 &setdebuglist, &showdebuglist);
3826 add_internal_problem_command (&internal_error_problem);
3827 add_internal_problem_command (&internal_warning_problem);
3828 add_internal_problem_command (&demangler_warning_problem);
3830 add_cmd ("screen", class_maintenance, &maintenance_info_screen,
3831 _("Show screen characteristics."), &maintenanceinfolist);
3833 #if GDB_SELF_TEST
3834 selftests::register_test ("gdb_realpath", gdb_realpath_tests);
3835 selftests::register_test ("gdb_argv_array_view", gdb_argv_as_array_view_test);
3836 selftests::register_test ("strncmp_iw_with_mode",
3837 strncmp_iw_with_mode_tests);
3838 selftests::register_test ("pager", test_pager);
3839 selftests::register_test ("assign_set_return_if_changed",
3840 test_assign_set_return_if_changed);
3841 #endif