More updated translations
[binutils-gdb.git] / gdb / utils.c
blob4027d4f26c38449d593cfd871c994738cf78d493
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 "gdbsupport/scoped_signal_handler.h"
23 #include "event-top.h"
24 #include "gdbthread.h"
25 #include "fnmatch.h"
26 #include "gdb_bfd.h"
27 #ifdef HAVE_SYS_RESOURCE_H
28 #include <sys/resource.h>
29 #endif /* HAVE_SYS_RESOURCE_H */
31 #ifdef TUI
32 /* For tui_get_command_dimension and tui_disable. */
33 #include "tui/tui.h"
34 #endif
36 #ifdef __GO32__
37 #include <pc.h>
38 #endif
40 #include <signal.h>
41 #include "cli/cli-cmds.h"
42 #include "serial.h"
43 #include "bfd.h"
44 #include "target.h"
45 #include "gdb-demangle.h"
46 #include "expression.h"
47 #include "language.h"
48 #include "charset.h"
49 #include "annotate.h"
50 #include "filenames.h"
51 #include "symfile.h"
52 #include "gdbsupport/gdb_obstack.h"
53 #include "gdbcore.h"
54 #include "top.h"
55 #include "ui.h"
56 #include "main.h"
57 #include "solist.h"
59 #include "inferior.h"
61 #include "gdb_curses.h"
63 #include "readline/readline.h"
65 #include <chrono>
67 #include "interps.h"
68 #include "gdbsupport/gdb_regex.h"
69 #include "gdbsupport/job-control.h"
70 #include "gdbsupport/selftest.h"
71 #include <optional>
72 #include "cp-support.h"
73 #include <algorithm>
74 #include "gdbsupport/pathstuff.h"
75 #include "cli/cli-style.h"
76 #include "gdbsupport/scope-exit.h"
77 #include "gdbarch.h"
78 #include "cli-out.h"
79 #include "gdbsupport/gdb-safe-ctype.h"
80 #include "bt-utils.h"
81 #include "gdbsupport/buildargv.h"
82 #include "pager.h"
83 #include "run-on-main-thread.h"
84 #include "gdbsupport/gdb_tilde_expand.h"
85 #include "gdbsupport/eintr.h"
87 void (*deprecated_error_begin_hook) (void);
89 /* Prototypes for local functions */
91 static void set_screen_size (void);
92 static void set_width (void);
94 /* Time spent in prompt_for_continue in the currently executing command
95 waiting for user to respond.
96 Initialized in make_command_stats_cleanup.
97 Modified in prompt_for_continue and defaulted_query.
98 Used in report_command_stats. */
100 static std::chrono::steady_clock::duration prompt_for_continue_wait_time;
102 /* A flag indicating whether to timestamp debugging messages. */
104 bool debug_timestamp = false;
106 /* True means that strings with character values >0x7F should be printed
107 as octal escapes. False means just print the value (e.g. it's an
108 international character, and the terminal or window can cope.) */
110 bool sevenbit_strings = false;
111 static void
112 show_sevenbit_strings (struct ui_file *file, int from_tty,
113 struct cmd_list_element *c, const char *value)
115 gdb_printf (file, _("Printing of 8-bit characters "
116 "in strings as \\nnn is %s.\n"),
117 value);
120 /* String to be printed before warning messages, if any. */
122 const char *warning_pre_print = "\nwarning: ";
124 bool pagination_enabled = true;
125 static void
126 show_pagination_enabled (struct ui_file *file, int from_tty,
127 struct cmd_list_element *c, const char *value)
129 gdb_printf (file, _("State of pagination is %s.\n"), value);
133 /* Warning hook pointer. This has to be 'static' to avoid link
134 problems with thread-locals on AIX. */
136 static thread_local warning_hook_handler warning_hook;
138 /* See utils.h. */
140 warning_hook_handler
141 get_warning_hook_handler ()
143 return warning_hook;
146 /* See utils.h. */
148 scoped_restore_warning_hook::scoped_restore_warning_hook
149 (warning_hook_handler new_handler)
150 : m_save (warning_hook)
152 warning_hook = new_handler;
155 scoped_restore_warning_hook::~scoped_restore_warning_hook ()
157 warning_hook = m_save;
160 /* Print a warning message. The first argument STRING is the warning
161 message, used as an fprintf format string, the second is the
162 va_list of arguments for that string. A warning is unfiltered (not
163 paginated) so that the user does not need to page through each
164 screen full of warnings when there are lots of them. */
166 void
167 vwarning (const char *string, va_list args)
169 if (warning_hook != nullptr)
170 warning_hook->warn (string, args);
171 else
173 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
174 if (target_supports_terminal_ours ())
176 term_state.emplace ();
177 target_terminal::ours_for_output ();
179 if (warning_pre_print)
180 gdb_puts (warning_pre_print, gdb_stderr);
181 gdb_vprintf (gdb_stderr, string, args);
182 gdb_printf (gdb_stderr, "\n");
186 /* Print an error message and return to command level.
187 The first argument STRING is the error message, used as a fprintf string,
188 and the remaining args are passed as arguments to it. */
190 void
191 verror (const char *string, va_list args)
193 throw_verror (GENERIC_ERROR, string, args);
196 /* Emit a message and abort. */
198 [[noreturn]] static void
199 abort_with_message (const char *msg)
201 if (current_ui == NULL)
202 fputs (msg, stderr);
203 else
204 gdb_puts (msg, gdb_stderr);
206 abort (); /* ARI: abort */
209 /* Dump core trying to increase the core soft limit to hard limit first. */
211 void
212 dump_core (void)
214 #ifdef HAVE_SETRLIMIT
215 struct rlimit rlim = { (rlim_t) RLIM_INFINITY, (rlim_t) RLIM_INFINITY };
217 setrlimit (RLIMIT_CORE, &rlim);
218 #endif /* HAVE_SETRLIMIT */
220 /* Ensure that the SIGABRT we're about to raise will immediately cause
221 GDB to exit and dump core, we don't want to trigger GDB's printing of
222 a backtrace to the console here. */
223 signal (SIGABRT, SIG_DFL);
225 abort (); /* ARI: abort */
228 /* Check whether GDB will be able to dump core using the dump_core
229 function. Returns zero if GDB cannot or should not dump core.
230 If LIMIT_KIND is LIMIT_CUR the user's soft limit will be respected.
231 If LIMIT_KIND is LIMIT_MAX only the hard limit will be respected. */
234 can_dump_core (enum resource_limit_kind limit_kind)
236 #ifdef HAVE_GETRLIMIT
237 struct rlimit rlim;
239 /* Be quiet and assume we can dump if an error is returned. */
240 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
241 return 1;
243 switch (limit_kind)
245 case LIMIT_CUR:
246 if (rlim.rlim_cur == 0)
247 return 0;
248 [[fallthrough]];
250 case LIMIT_MAX:
251 if (rlim.rlim_max == 0)
252 return 0;
254 #endif /* HAVE_GETRLIMIT */
256 return 1;
259 /* Print a warning that we cannot dump core. */
261 void
262 warn_cant_dump_core (const char *reason)
264 gdb_printf (gdb_stderr,
265 _("%s\nUnable to dump core, use `ulimit -c"
266 " unlimited' before executing GDB next time.\n"),
267 reason);
270 /* Check whether GDB will be able to dump core using the dump_core
271 function, and print a warning if we cannot. */
273 static int
274 can_dump_core_warn (enum resource_limit_kind limit_kind,
275 const char *reason)
277 int core_dump_allowed = can_dump_core (limit_kind);
279 if (!core_dump_allowed)
280 warn_cant_dump_core (reason);
282 return core_dump_allowed;
285 /* Allow the user to configure the debugger behavior with respect to
286 what to do when an internal problem is detected. */
288 const char internal_problem_ask[] = "ask";
289 const char internal_problem_yes[] = "yes";
290 const char internal_problem_no[] = "no";
291 static const char *const internal_problem_modes[] =
293 internal_problem_ask,
294 internal_problem_yes,
295 internal_problem_no,
296 NULL
299 /* Data structure used to control how the internal_vproblem function
300 should behave. An instance of this structure is created for each
301 problem type that GDB supports. */
303 struct internal_problem
305 /* The name of this problem type. This must not contain white space as
306 this string is used to build command names. */
307 const char *name;
309 /* When this is true then a user command is created (based on NAME) that
310 allows the SHOULD_QUIT field to be modified, otherwise, SHOULD_QUIT
311 can't be changed from its default value by the user. */
312 bool user_settable_should_quit;
314 /* Reference a value from internal_problem_modes to indicate if GDB
315 should quit when it hits a problem of this type. */
316 const char *should_quit;
318 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_DUMP_CORE. */
319 bool user_settable_should_dump_core;
321 /* Like SHOULD_QUIT, but whether GDB should dump core. */
322 const char *should_dump_core;
324 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_PRINT_BACKTRACE. */
325 bool user_settable_should_print_backtrace;
327 /* When this is true GDB will print a backtrace when a problem of this
328 type is encountered. */
329 bool should_print_backtrace;
332 /* Return true if the readline callbacks have been initialized for UI.
333 This is always true once GDB is fully initialized, but during the early
334 startup phase this is initially false. */
336 static bool
337 readline_initialized (struct ui *ui)
339 return ui->call_readline != nullptr;
342 /* Report a problem, internal to GDB, to the user. Once the problem
343 has been reported, and assuming GDB didn't quit, the caller can
344 either allow execution to resume or throw an error. */
346 static void ATTRIBUTE_PRINTF (4, 0)
347 internal_vproblem (struct internal_problem *problem,
348 const char *file, int line, const char *fmt, va_list ap)
350 static int dejavu;
351 int quit_p;
352 int dump_core_p;
353 std::string reason;
355 /* Don't allow infinite error/warning recursion. */
357 static const char msg[] = "Recursive internal problem.\n";
359 switch (dejavu)
361 case 0:
362 dejavu = 1;
363 break;
364 case 1:
365 dejavu = 2;
366 abort_with_message (msg);
367 default:
368 dejavu = 3;
369 /* Newer GLIBC versions put the warn_unused_result attribute
370 on write, but this is one of those rare cases where
371 ignoring the return value is correct. Casting to (void)
372 does not fix this problem. This is the solution suggested
373 at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509. */
374 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
375 abort (); /* ARI: abort */
376 exit (1);
380 #ifdef TUI
381 tui_disable ();
382 #endif
384 /* Create a string containing the full error/warning message. Need
385 to call query with this full string, as otherwize the reason
386 (error/warning) and question become separated. Format using a
387 style similar to a compiler error message. Include extra detail
388 so that the user knows that they are living on the edge. */
390 std::string msg = string_vprintf (fmt, ap);
391 reason = string_printf ("%s:%d: %s: %s\n"
392 "A problem internal to GDB has been detected,\n"
393 "further debugging may prove unreliable.",
394 file, line, problem->name, msg.c_str ());
397 /* Fall back to abort_with_message if gdb_stderr is not set up. */
398 if (current_ui == NULL)
400 fputs (reason.c_str (), stderr);
401 abort_with_message ("\n");
404 /* Try to get the message out and at the start of a new line. */
405 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
406 if (target_supports_terminal_ours ())
408 term_state.emplace ();
409 target_terminal::ours_for_output ();
411 if (filtered_printing_initialized ())
412 begin_line ();
414 /* Emit the message unless query will emit it below. */
415 if (problem->should_quit != internal_problem_ask
416 || !confirm
417 || !filtered_printing_initialized ()
418 || !readline_initialized (current_ui)
419 || problem->should_print_backtrace)
420 gdb_printf (gdb_stderr, "%s\n", reason.c_str ());
422 if (problem->should_print_backtrace)
423 gdb_internal_backtrace ();
425 if (problem->should_quit == internal_problem_ask)
427 /* Default (yes/batch case) is to quit GDB. When in batch mode
428 this lessens the likelihood of GDB going into an infinite
429 loop. */
430 if (!confirm || !filtered_printing_initialized ()
431 || !readline_initialized (current_ui))
432 quit_p = 1;
433 else
434 quit_p = query (_("%s\nQuit this debugging session? "),
435 reason.c_str ());
437 else if (problem->should_quit == internal_problem_yes)
438 quit_p = 1;
439 else if (problem->should_quit == internal_problem_no)
440 quit_p = 0;
441 else
442 internal_error (_("bad switch"));
444 gdb_puts (_("\nThis is a bug, please report it."), gdb_stderr);
445 if (REPORT_BUGS_TO[0])
446 gdb_printf (gdb_stderr, _(" For instructions, see:\n%ps."),
447 styled_string (file_name_style.style (),
448 REPORT_BUGS_TO));
449 gdb_puts ("\n\n", gdb_stderr);
451 if (problem->should_dump_core == internal_problem_ask)
453 if (!can_dump_core_warn (LIMIT_MAX, reason.c_str ()))
454 dump_core_p = 0;
455 else if (!filtered_printing_initialized ()
456 || !readline_initialized (current_ui))
457 dump_core_p = 1;
458 else
460 /* Default (yes/batch case) is to dump core. This leaves a GDB
461 `dropping' so that it is easier to see that something went
462 wrong in GDB. */
463 dump_core_p = query (_("%s\nCreate a core file of GDB? "),
464 reason.c_str ());
467 else if (problem->should_dump_core == internal_problem_yes)
468 dump_core_p = can_dump_core_warn (LIMIT_MAX, reason.c_str ());
469 else if (problem->should_dump_core == internal_problem_no)
470 dump_core_p = 0;
471 else
472 internal_error (_("bad switch"));
474 if (quit_p)
476 if (dump_core_p)
477 dump_core ();
478 else
479 exit (1);
481 else
483 if (dump_core_p)
485 #ifdef HAVE_WORKING_FORK
486 if (fork () == 0)
487 dump_core ();
488 #endif
492 dejavu = 0;
495 static struct internal_problem internal_error_problem = {
496 "internal-error", true, internal_problem_ask, true, internal_problem_ask,
497 true, GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON
500 void
501 internal_verror (const char *file, int line, const char *fmt, va_list ap)
503 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
504 throw_quit (_("Command aborted."));
507 static struct internal_problem internal_warning_problem = {
508 "internal-warning", true, internal_problem_ask, true, internal_problem_ask,
509 true, false
512 void
513 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
515 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
518 static struct internal_problem demangler_warning_problem = {
519 "demangler-warning", true, internal_problem_ask, false, internal_problem_no,
520 false, false
523 void
524 demangler_vwarning (const char *file, int line, const char *fmt, va_list ap)
526 internal_vproblem (&demangler_warning_problem, file, line, fmt, ap);
529 void
530 demangler_warning (const char *file, int line, const char *string, ...)
532 va_list ap;
534 va_start (ap, string);
535 demangler_vwarning (file, line, string, ap);
536 va_end (ap);
539 /* When GDB reports an internal problem (error or warning) it gives
540 the user the opportunity to quit GDB and/or create a core file of
541 the current debug session. This function registers a few commands
542 that make it possible to specify that GDB should always or never
543 quit or create a core file, without asking. The commands look
544 like:
546 maint set PROBLEM-NAME quit ask|yes|no
547 maint show PROBLEM-NAME quit
548 maint set PROBLEM-NAME corefile ask|yes|no
549 maint show PROBLEM-NAME corefile
551 Where PROBLEM-NAME is currently "internal-error" or
552 "internal-warning". */
554 static void
555 add_internal_problem_command (struct internal_problem *problem)
557 struct cmd_list_element **set_cmd_list;
558 struct cmd_list_element **show_cmd_list;
560 set_cmd_list = XNEW (struct cmd_list_element *);
561 show_cmd_list = XNEW (struct cmd_list_element *);
562 *set_cmd_list = NULL;
563 *show_cmd_list = NULL;
565 /* The add_basic_prefix_cmd and add_show_prefix_cmd functions take
566 ownership of the string passed in, which is why we don't need to free
567 set_doc and show_doc in this function. */
568 const char *set_doc
569 = xstrprintf (_("Configure what GDB does when %s is detected."),
570 problem->name).release ();
571 const char *show_doc
572 = xstrprintf (_("Show what GDB does when %s is detected."),
573 problem->name).release ();
575 add_setshow_prefix_cmd (problem->name, class_maintenance,
576 set_doc, show_doc, set_cmd_list, show_cmd_list,
577 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
579 if (problem->user_settable_should_quit)
581 std::string set_quit_doc
582 = string_printf (_("Set whether GDB should quit when an %s is "
583 "detected."), problem->name);
584 std::string show_quit_doc
585 = string_printf (_("Show whether GDB will quit when an %s is "
586 "detected."), problem->name);
587 add_setshow_enum_cmd ("quit", class_maintenance,
588 internal_problem_modes,
589 &problem->should_quit,
590 set_quit_doc.c_str (),
591 show_quit_doc.c_str (),
592 NULL, /* help_doc */
593 NULL, /* setfunc */
594 NULL, /* showfunc */
595 set_cmd_list,
596 show_cmd_list);
599 if (problem->user_settable_should_dump_core)
601 std::string set_core_doc
602 = string_printf (_("Set whether GDB should dump core "
603 "when %s is detected."), problem->name);
604 std::string show_core_doc
605 = string_printf (_("Show whether GDB should dump core "
606 "when %s is detected."), problem->name);
607 add_setshow_enum_cmd ("corefile", class_maintenance,
608 internal_problem_modes,
609 &problem->should_dump_core,
610 set_core_doc.c_str (),
611 show_core_doc.c_str (),
612 NULL, /* help_doc */
613 NULL, /* setfunc */
614 NULL, /* showfunc */
615 set_cmd_list,
616 show_cmd_list);
619 if (problem->user_settable_should_print_backtrace)
621 std::string set_bt_doc
622 = string_printf (_("Set whether GDB should show backtrace "
623 "when %s is detected."), problem->name);
624 std::string show_bt_doc
625 = string_printf (_("Show whether GDB should show backtrace "
626 "when %s is detected."), problem->name);
627 add_setshow_boolean_cmd ("backtrace", class_maintenance,
628 &problem->should_print_backtrace,
629 set_bt_doc.c_str (),
630 show_bt_doc.c_str (),
631 NULL, /* help_doc */
632 gdb_internal_backtrace_set_cmd,
633 NULL, /* showfunc */
634 set_cmd_list,
635 show_cmd_list);
639 /* Same as perror_with_name except that it prints a warning instead
640 of throwing an error. */
642 void
643 perror_warning_with_name (const char *string)
645 std::string combined = perror_string (string);
646 warning (_("%s"), combined.c_str ());
649 /* See utils.h. */
651 void
652 warning_filename_and_errno (const char *filename, int saved_errno)
654 warning (_("%ps: %s"), styled_string (file_name_style.style (), filename),
655 safe_strerror (saved_errno));
658 /* Called when a memory allocation fails, with the number of bytes of
659 memory requested in SIZE. */
661 void
662 malloc_failure (long size)
664 if (size > 0)
666 internal_error (_("virtual memory exhausted: can't allocate %ld bytes."),
667 size);
669 else
671 internal_error (_("virtual memory exhausted."));
675 /* See common/errors.h. */
677 void
678 flush_streams ()
680 gdb_stdout->flush ();
681 gdb_stderr->flush ();
684 /* My replacement for the read system call.
685 Used like `read' but keeps going if `read' returns too soon. */
688 myread (int desc, char *addr, int len)
690 int val;
691 int orglen = len;
693 while (len > 0)
695 val = read (desc, addr, len);
696 if (val < 0)
697 return val;
698 if (val == 0)
699 return orglen - len;
700 len -= val;
701 addr += val;
703 return orglen;
708 /* An RAII class that sets up to handle input and then tears down
709 during destruction. */
711 class scoped_input_handler
713 public:
715 scoped_input_handler ()
716 : m_quit_handler (&quit_handler, default_quit_handler),
717 m_ui (NULL)
719 target_terminal::ours ();
720 current_ui->register_file_handler ();
721 if (current_ui->prompt_state == PROMPT_BLOCKED)
722 m_ui = current_ui;
725 ~scoped_input_handler ()
727 if (m_ui != NULL)
728 m_ui->unregister_file_handler ();
731 DISABLE_COPY_AND_ASSIGN (scoped_input_handler);
733 private:
735 /* Save and restore the terminal state. */
736 target_terminal::scoped_restore_terminal_state m_term_state;
738 /* Save and restore the quit handler. */
739 scoped_restore_tmpl<quit_handler_ftype *> m_quit_handler;
741 /* The saved UI, if non-NULL. */
742 struct ui *m_ui;
747 /* This function supports the query, nquery, and yquery functions.
748 Ask user a y-or-n question and return 0 if answer is no, 1 if
749 answer is yes, or default the answer to the specified default
750 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
751 default answer, or '\0' for no default.
752 CTLSTR is the control string and should end in "? ". It should
753 not say how to answer, because we do that.
754 ARGS are the arguments passed along with the CTLSTR argument to
755 printf. */
757 static int ATTRIBUTE_PRINTF (1, 0)
758 defaulted_query (const char *ctlstr, const char defchar, va_list args)
760 int retval;
761 int def_value;
762 char def_answer, not_def_answer;
763 const char *y_string, *n_string;
765 /* Set up according to which answer is the default. */
766 if (defchar == '\0')
768 def_value = 1;
769 def_answer = 'Y';
770 not_def_answer = 'N';
771 y_string = "y";
772 n_string = "n";
774 else if (defchar == 'y')
776 def_value = 1;
777 def_answer = 'Y';
778 not_def_answer = 'N';
779 y_string = "[y]";
780 n_string = "n";
782 else
784 def_value = 0;
785 def_answer = 'N';
786 not_def_answer = 'Y';
787 y_string = "y";
788 n_string = "[n]";
791 /* Automatically answer the default value if the user did not want
792 prompts or the command was issued with the server prefix. */
793 if (!confirm || server_command)
794 return def_value;
796 /* If input isn't coming from the user directly, just say what
797 question we're asking, and then answer the default automatically. This
798 way, important error messages don't get lost when talking to GDB
799 over a pipe. */
800 if (current_ui->instream != current_ui->stdin_stream
801 || !current_ui->input_interactive_p ()
802 /* Restrict queries to the main UI. */
803 || current_ui != main_ui)
805 target_terminal::scoped_restore_terminal_state term_state;
806 target_terminal::ours_for_output ();
807 gdb_stdout->wrap_here (0);
808 gdb_vprintf (gdb_stdout, ctlstr, args);
810 gdb_printf (_("(%s or %s) [answered %c; "
811 "input not from terminal]\n"),
812 y_string, n_string, def_answer);
814 return def_value;
817 if (deprecated_query_hook)
819 target_terminal::scoped_restore_terminal_state term_state;
820 return deprecated_query_hook (ctlstr, args);
823 /* Format the question outside of the loop, to avoid reusing args. */
824 string_file tem (gdb_stdout->can_emit_style_escape ());
825 gdb_vprintf (&tem, ctlstr, args);
826 std::string question = tem.release ();
827 std::string prompt
828 = string_printf (_("%s%s(%s or %s) %s"),
829 annotation_level > 1 ? "\n\032\032pre-query\n" : "",
830 question.c_str (), y_string, n_string,
831 annotation_level > 1 ? "\n\032\032query\n" : "");
833 /* Used to add duration we waited for user to respond to
834 prompt_for_continue_wait_time. */
835 using namespace std::chrono;
836 steady_clock::time_point prompt_started = steady_clock::now ();
838 scoped_input_handler prepare_input;
840 while (1)
842 char *response, answer;
844 gdb_flush (gdb_stdout);
845 response = gdb_readline_wrapper (prompt.c_str ());
847 if (response == NULL) /* C-d */
849 gdb_printf ("EOF [assumed %c]\n", def_answer);
850 retval = def_value;
851 break;
854 answer = response[0];
855 xfree (response);
857 if (answer >= 'a')
858 answer -= 040;
859 /* Check answer. For the non-default, the user must specify
860 the non-default explicitly. */
861 if (answer == not_def_answer)
863 retval = !def_value;
864 break;
866 /* Otherwise, if a default was specified, the user may either
867 specify the required input or have it default by entering
868 nothing. */
869 if (answer == def_answer
870 || (defchar != '\0' && answer == '\0'))
872 retval = def_value;
873 break;
875 /* Invalid entries are not defaulted and require another selection. */
876 gdb_printf (_("Please answer %s or %s.\n"),
877 y_string, n_string);
880 /* Add time spend in this routine to prompt_for_continue_wait_time. */
881 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
883 if (annotation_level > 1)
884 gdb_printf (("\n\032\032post-query\n"));
885 return retval;
889 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
890 answer is yes, or 0 if answer is defaulted.
891 Takes three args which are given to printf to print the question.
892 The first, a control string, should end in "? ".
893 It should not say how to answer, because we do that. */
896 nquery (const char *ctlstr, ...)
898 va_list args;
899 int ret;
901 va_start (args, ctlstr);
902 ret = defaulted_query (ctlstr, 'n', args);
903 va_end (args);
904 return ret;
907 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
908 answer is yes, or 1 if answer is defaulted.
909 Takes three args which are given to printf to print the question.
910 The first, a control string, should end in "? ".
911 It should not say how to answer, because we do that. */
914 yquery (const char *ctlstr, ...)
916 va_list args;
917 int ret;
919 va_start (args, ctlstr);
920 ret = defaulted_query (ctlstr, 'y', args);
921 va_end (args);
922 return ret;
925 /* Ask user a y-or-n question and return 1 iff answer is yes.
926 Takes three args which are given to printf to print the question.
927 The first, a control string, should end in "? ".
928 It should not say how to answer, because we do that. */
931 query (const char *ctlstr, ...)
933 va_list args;
934 int ret;
936 va_start (args, ctlstr);
937 ret = defaulted_query (ctlstr, '\0', args);
938 va_end (args);
939 return ret;
942 /* A helper for parse_escape that converts a host character to a
943 target character. C is the host character. If conversion is
944 possible, then the target character is stored in *TARGET_C and the
945 function returns 1. Otherwise, the function returns 0. */
947 static int
948 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
950 char the_char = c;
951 int result = 0;
953 auto_obstack host_data;
955 convert_between_encodings (target_charset (gdbarch), host_charset (),
956 (gdb_byte *) &the_char, 1, 1,
957 &host_data, translit_none);
959 if (obstack_object_size (&host_data) == 1)
961 result = 1;
962 *target_c = *(char *) obstack_base (&host_data);
965 return result;
968 /* Parse a C escape sequence. STRING_PTR points to a variable
969 containing a pointer to the string to parse. That pointer
970 should point to the character after the \. That pointer
971 is updated past the characters we use. The value of the
972 escape sequence is returned.
974 A negative value means the sequence \ newline was seen,
975 which is supposed to be equivalent to nothing at all.
977 If \ is followed by a null character, we return a negative
978 value and leave the string pointer pointing at the null character.
980 If \ is followed by 000, we return 0 and leave the string pointer
981 after the zeros. A value of 0 does not mean end of string. */
984 parse_escape (struct gdbarch *gdbarch, const char **string_ptr)
986 int target_char = -2; /* Initialize to avoid GCC warnings. */
987 int c = *(*string_ptr)++;
989 switch (c)
991 case '\n':
992 return -2;
993 case 0:
994 (*string_ptr)--;
995 return 0;
997 case '0':
998 case '1':
999 case '2':
1000 case '3':
1001 case '4':
1002 case '5':
1003 case '6':
1004 case '7':
1006 int i = fromhex (c);
1007 int count = 0;
1008 while (++count < 3)
1010 c = (**string_ptr);
1011 if (ISDIGIT (c) && c != '8' && c != '9')
1013 (*string_ptr)++;
1014 i *= 8;
1015 i += fromhex (c);
1017 else
1019 break;
1022 return i;
1025 case 'a':
1026 c = '\a';
1027 break;
1028 case 'b':
1029 c = '\b';
1030 break;
1031 case 'f':
1032 c = '\f';
1033 break;
1034 case 'n':
1035 c = '\n';
1036 break;
1037 case 'r':
1038 c = '\r';
1039 break;
1040 case 't':
1041 c = '\t';
1042 break;
1043 case 'v':
1044 c = '\v';
1045 break;
1047 default:
1048 break;
1051 if (!host_char_to_target (gdbarch, c, &target_char))
1052 error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1053 " which has no equivalent\nin the `%s' character set."),
1054 c, c, target_charset (gdbarch));
1055 return target_char;
1059 /* Number of lines per page or UINT_MAX if paging is disabled. */
1060 static unsigned int lines_per_page;
1061 static void
1062 show_lines_per_page (struct ui_file *file, int from_tty,
1063 struct cmd_list_element *c, const char *value)
1065 gdb_printf (file,
1066 _("Number of lines gdb thinks are in a page is %s.\n"),
1067 value);
1070 /* Number of chars per line or UINT_MAX if line folding is disabled. */
1071 static unsigned int chars_per_line;
1072 static void
1073 show_chars_per_line (struct ui_file *file, int from_tty,
1074 struct cmd_list_element *c, const char *value)
1076 gdb_printf (file,
1077 _("Number of characters gdb thinks "
1078 "are in a line is %s.\n"),
1079 value);
1082 /* Current count of lines printed on this page, chars on this line. */
1083 static unsigned int lines_printed, chars_printed;
1085 /* True if pagination is disabled for just one command. */
1087 static bool pagination_disabled_for_command;
1089 /* Buffer and start column of buffered text, for doing smarter word-
1090 wrapping. When someone calls wrap_here(), we start buffering output
1091 that comes through gdb_puts(). If we see a newline, we just
1092 spit it out and forget about the wrap_here(). If we see another
1093 wrap_here(), we spit it out and remember the newer one. If we see
1094 the end of the line, we spit out a newline, the indent, and then
1095 the buffered output. */
1097 static bool filter_initialized = false;
1101 /* See utils.h. */
1103 int readline_hidden_cols = 0;
1105 /* Initialize the number of lines per page and chars per line. */
1107 void
1108 init_page_info (void)
1110 if (batch_flag)
1112 lines_per_page = UINT_MAX;
1113 chars_per_line = UINT_MAX;
1115 else
1116 #if defined(TUI)
1117 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1118 #endif
1120 int rows, cols;
1122 #if defined(__GO32__)
1123 rows = ScreenRows ();
1124 cols = ScreenCols ();
1125 lines_per_page = rows;
1126 chars_per_line = cols;
1127 #else
1128 /* Make sure Readline has initialized its terminal settings. */
1129 rl_reset_terminal (NULL);
1131 /* Get the screen size from Readline. */
1132 rl_get_screen_size (&rows, &cols);
1134 /* Readline:
1135 - ignores the COLUMNS variable when detecting screen width
1136 (because rl_prefer_env_winsize defaults to 0)
1137 - puts the detected screen width in the COLUMNS variable
1138 (because rl_change_environment defaults to 1)
1139 - may report one less than the detected screen width in
1140 rl_get_screen_size (when _rl_term_autowrap == 0).
1141 We could use _rl_term_autowrap, but we want to avoid introducing
1142 another dependency on readline private variables, so set
1143 readline_hidden_cols by comparing COLUMNS to cols as returned by
1144 rl_get_screen_size. */
1145 const char *columns_env_str = getenv ("COLUMNS");
1146 gdb_assert (columns_env_str != nullptr);
1147 int columns_env_val = atoi (columns_env_str);
1148 gdb_assert (columns_env_val != 0);
1149 readline_hidden_cols = columns_env_val - cols;
1150 gdb_assert (readline_hidden_cols >= 0);
1151 gdb_assert (readline_hidden_cols <= 1);
1153 lines_per_page = rows;
1154 chars_per_line = cols + readline_hidden_cols;
1156 /* Readline should have fetched the termcap entry for us.
1157 Only try to use tgetnum function if rl_get_screen_size
1158 did not return a useful value. */
1159 if (((rows <= 0) && (tgetnum ((char *) "li") < 0))
1160 /* Also disable paging if inside Emacs. $EMACS was used
1161 before Emacs v25.1, $INSIDE_EMACS is used since then. */
1162 || getenv ("EMACS") || getenv ("INSIDE_EMACS"))
1164 /* The number of lines per page is not mentioned in the terminal
1165 description or EMACS environment variable is set. This probably
1166 means that paging is not useful, so disable paging. */
1167 lines_per_page = UINT_MAX;
1170 /* If the output is not a terminal, don't paginate it. */
1171 if (!gdb_stdout->isatty ())
1172 lines_per_page = UINT_MAX;
1173 #endif
1176 /* We handle SIGWINCH ourselves. */
1177 rl_catch_sigwinch = 0;
1179 set_screen_size ();
1180 set_width ();
1183 /* Return nonzero if filtered printing is initialized. */
1185 filtered_printing_initialized (void)
1187 return filter_initialized;
1190 set_batch_flag_and_restore_page_info::set_batch_flag_and_restore_page_info ()
1191 : m_save_lines_per_page (lines_per_page),
1192 m_save_chars_per_line (chars_per_line),
1193 m_save_batch_flag (batch_flag)
1195 batch_flag = 1;
1196 init_page_info ();
1199 set_batch_flag_and_restore_page_info::~set_batch_flag_and_restore_page_info ()
1201 batch_flag = m_save_batch_flag;
1202 chars_per_line = m_save_chars_per_line;
1203 lines_per_page = m_save_lines_per_page;
1205 set_screen_size ();
1206 set_width ();
1209 /* An approximation of SQRT(INT_MAX) that is:
1210 - cheap to calculate,
1211 - guaranteed to be smaller than SQRT(INT_MAX), such that
1212 sqrt_int_max * sqrt_int_max doesn't overflow, and
1213 - "close enough" to SQRT(INT_MAX), for instance for INT_MAX == 2147483647,
1214 SQRT(INT_MAX) is ~46341 and sqrt_int_max == 32767. */
1216 static const int sqrt_int_max = INT_MAX >> (sizeof (int) * 8 / 2);
1218 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1220 static void
1221 set_screen_size (void)
1223 int rows = lines_per_page;
1224 int cols = chars_per_line;
1226 /* If we get 0 or negative ROWS or COLS, treat as "infinite" size.
1227 A negative number can be seen here with the "set width/height"
1228 commands and either:
1230 - the user specified "unlimited", which maps to UINT_MAX, or
1231 - the user specified some number between INT_MAX and UINT_MAX.
1233 Cap "infinity" to approximately sqrt(INT_MAX) so that we don't
1234 overflow in rl_set_screen_size, which multiplies rows and columns
1235 to compute the number of characters on the screen. */
1237 if (rows <= 0 || rows > sqrt_int_max)
1239 rows = sqrt_int_max;
1240 lines_per_page = UINT_MAX;
1243 if (cols <= 0 || cols > sqrt_int_max)
1245 cols = sqrt_int_max;
1246 chars_per_line = UINT_MAX;
1249 /* Update Readline's idea of the terminal size. */
1250 rl_set_screen_size (rows, cols);
1253 /* Reinitialize WRAP_BUFFER. */
1255 static void
1256 set_width (void)
1258 if (chars_per_line == 0)
1259 init_page_info ();
1261 filter_initialized = true;
1264 static void
1265 set_width_command (const char *args, int from_tty, struct cmd_list_element *c)
1267 set_screen_size ();
1268 set_width ();
1271 static void
1272 set_height_command (const char *args, int from_tty, struct cmd_list_element *c)
1274 set_screen_size ();
1277 /* See utils.h. */
1279 void
1280 set_screen_width_and_height (int width, int height)
1282 lines_per_page = height;
1283 chars_per_line = width;
1285 set_screen_size ();
1286 set_width ();
1289 /* Import termcap variable UP (instead of readline private variable
1290 _rl_term_up, which we're trying to avoid, see PR build/10723). The UP
1291 variable doesn't seem be part of the regular termcap interface, but rather
1292 curses-specific. But if it's missing in the termcap library, then readline
1293 provides a fallback version. Let's assume the fallback is not part of the
1294 private readline interface. */
1295 extern "C" char *UP;
1297 /* Implement "maint info screen". */
1299 static void
1300 maintenance_info_screen (const char *args, int from_tty)
1302 int rows, cols;
1303 rl_get_screen_size (&rows, &cols);
1305 gdb_printf (gdb_stdout,
1306 _("Number of characters gdb thinks "
1307 "are in a line is %u%s.\n"),
1308 chars_per_line,
1309 chars_per_line == UINT_MAX ? " (unlimited)" : "");
1311 gdb_printf (gdb_stdout,
1312 _("Number of characters readline reports "
1313 "are in a line is %d%s.\n"),
1314 cols,
1315 (cols == sqrt_int_max
1316 ? " (unlimited)"
1317 : (cols == sqrt_int_max - 1
1318 ? " (unlimited - 1)"
1319 : "")));
1321 #ifdef HAVE_LIBCURSES
1322 gdb_printf (gdb_stdout,
1323 _("Number of characters curses thinks "
1324 "are in a line is %d.\n"),
1325 COLS);
1326 #endif
1328 gdb_printf (gdb_stdout,
1329 _("Number of characters environment thinks "
1330 "are in a line is %s (COLUMNS).\n"),
1331 getenv ("COLUMNS"));
1333 gdb_printf (gdb_stdout,
1334 _("Number of lines gdb thinks are in a page is %u%s.\n"),
1335 lines_per_page,
1336 lines_per_page == UINT_MAX ? " (unlimited)" : "");
1338 gdb_printf (gdb_stdout,
1339 _("Number of lines readline reports "
1340 "are in a page is %d%s.\n"),
1341 rows,
1342 rows == sqrt_int_max ? " (unlimited)" : "");
1344 #ifdef HAVE_LIBCURSES
1345 gdb_printf (gdb_stdout,
1346 _("Number of lines curses thinks "
1347 "are in a page is %d.\n"),
1348 LINES);
1349 #endif
1351 gdb_printf (gdb_stdout,
1352 _("Number of lines environment thinks "
1353 "are in a page is %s (LINES).\n"),
1354 getenv ("LINES"));
1356 bool have_up = UP != nullptr && *UP != '\0';
1358 /* Fetch value of readline variable horizontal-scroll-mode. */
1359 const char *horizontal_scroll_mode_value
1360 = rl_variable_value ("horizontal-scroll-mode");
1361 bool force_horizontal_scroll_mode
1362 = (horizontal_scroll_mode_value != nullptr
1363 && strcmp (horizontal_scroll_mode_value, "on") == 0);
1365 const char *mode = nullptr;
1366 const char *reason = nullptr;
1367 if (batch_flag)
1369 mode = "unsupported";
1370 reason = "gdb batch mode";
1372 else if (!have_up)
1374 mode = "unsupported";
1375 reason = "terminal is not Cursor Up capable";
1377 else if (force_horizontal_scroll_mode)
1379 mode = "disabled";
1380 reason = "horizontal-scroll-mode";
1382 else if (readline_hidden_cols)
1384 mode = "readline";
1385 reason = "terminal is not auto wrap capable, last column reserved";
1387 else
1389 mode = "terminal";
1390 reason = "terminal is auto wrap capable";
1393 gdb_printf (gdb_stdout, _("Readline wrapping mode: %s (%s).\n"), mode,
1394 reason);
1397 void
1398 pager_file::emit_style_escape (const ui_file_style &style)
1400 if (can_emit_style_escape () && style != m_applied_style)
1402 m_applied_style = style;
1403 if (m_paging)
1404 m_stream->emit_style_escape (style);
1405 else
1406 m_wrap_buffer.append (style.to_ansi ());
1410 /* See pager.h. */
1412 void
1413 pager_file::reset_style ()
1415 if (can_emit_style_escape ())
1417 m_applied_style = ui_file_style ();
1418 m_wrap_buffer.append (m_applied_style.to_ansi ());
1422 /* Wait, so the user can read what's on the screen. Prompt the user
1423 to continue by pressing RETURN. 'q' is also provided because
1424 telling users what to do in the prompt is more user-friendly than
1425 expecting them to think of Ctrl-C/SIGINT. */
1427 void
1428 pager_file::prompt_for_continue ()
1430 char cont_prompt[120];
1431 /* Used to add duration we waited for user to respond to
1432 prompt_for_continue_wait_time. */
1433 using namespace std::chrono;
1434 steady_clock::time_point prompt_started = steady_clock::now ();
1435 bool disable_pagination = pagination_disabled_for_command;
1437 scoped_restore save_paging = make_scoped_restore (&m_paging, true);
1439 /* Clear the current styling. */
1440 m_stream->emit_style_escape (ui_file_style ());
1442 if (annotation_level > 1)
1443 m_stream->puts (("\n\032\032pre-prompt-for-continue\n"));
1445 strcpy (cont_prompt,
1446 "--Type <RET> for more, q to quit, "
1447 "c to continue without paging--");
1448 if (annotation_level > 1)
1449 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1451 /* We must do this *before* we call gdb_readline_wrapper, else it
1452 will eventually call us -- thinking that we're trying to print
1453 beyond the end of the screen. */
1454 reinitialize_more_filter ();
1456 scoped_input_handler prepare_input;
1458 /* Call gdb_readline_wrapper, not readline, in order to keep an
1459 event loop running. */
1460 gdb::unique_xmalloc_ptr<char> ignore (gdb_readline_wrapper (cont_prompt));
1462 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1463 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
1465 if (annotation_level > 1)
1466 m_stream->puts (("\n\032\032post-prompt-for-continue\n"));
1468 if (ignore != NULL)
1470 char *p = ignore.get ();
1472 while (*p == ' ' || *p == '\t')
1473 ++p;
1474 if (p[0] == 'q')
1475 /* Do not call quit here; there is no possibility of SIGINT. */
1476 throw_quit ("Quit");
1477 if (p[0] == 'c')
1478 disable_pagination = true;
1481 /* Now we have to do this again, so that GDB will know that it doesn't
1482 need to save the ---Type <return>--- line at the top of the screen. */
1483 reinitialize_more_filter ();
1484 pagination_disabled_for_command = disable_pagination;
1486 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1489 /* Initialize timer to keep track of how long we waited for the user. */
1491 void
1492 reset_prompt_for_continue_wait_time (void)
1494 using namespace std::chrono;
1496 prompt_for_continue_wait_time = steady_clock::duration::zero ();
1499 /* Fetch the cumulative time spent in prompt_for_continue. */
1501 std::chrono::steady_clock::duration
1502 get_prompt_for_continue_wait_time ()
1504 return prompt_for_continue_wait_time;
1507 /* Reinitialize filter; ie. tell it to reset to original values. */
1509 void
1510 reinitialize_more_filter (void)
1512 lines_printed = 0;
1513 chars_printed = 0;
1514 pagination_disabled_for_command = false;
1517 void
1518 pager_file::flush_wrap_buffer ()
1520 if (!m_paging && !m_wrap_buffer.empty ())
1522 m_stream->puts (m_wrap_buffer.c_str ());
1523 m_wrap_buffer.clear ();
1527 void
1528 pager_file::flush ()
1530 flush_wrap_buffer ();
1531 m_stream->flush ();
1534 /* See utils.h. */
1536 void
1537 gdb_flush (struct ui_file *stream)
1539 stream->flush ();
1542 /* See utils.h. */
1545 get_chars_per_line ()
1547 return chars_per_line;
1550 /* See ui-file.h. */
1552 void
1553 pager_file::wrap_here (int indent)
1555 /* This should have been allocated, but be paranoid anyway. */
1556 gdb_assert (filter_initialized);
1558 flush_wrap_buffer ();
1559 if (chars_per_line == UINT_MAX) /* No line overflow checking. */
1561 m_wrap_column = 0;
1563 else if (chars_printed >= chars_per_line)
1565 this->puts ("\n");
1566 if (indent != 0)
1567 this->puts (n_spaces (indent));
1568 m_wrap_column = 0;
1570 else
1572 m_wrap_column = chars_printed;
1573 m_wrap_indent = indent;
1574 m_wrap_style = m_applied_style;
1578 /* Print input string to gdb_stdout arranging strings in columns of n
1579 chars. String can be right or left justified in the column. Never
1580 prints trailing spaces. String should never be longer than width.
1581 FIXME: this could be useful for the EXAMINE command, which
1582 currently doesn't tabulate very well. */
1584 void
1585 puts_tabular (char *string, int width, int right)
1587 int spaces = 0;
1588 int stringlen;
1589 char *spacebuf;
1591 gdb_assert (chars_per_line > 0);
1592 if (chars_per_line == UINT_MAX)
1594 gdb_puts (string);
1595 gdb_puts ("\n");
1596 return;
1599 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
1600 gdb_puts ("\n");
1602 if (width >= chars_per_line)
1603 width = chars_per_line - 1;
1605 stringlen = strlen (string);
1607 if (chars_printed > 0)
1608 spaces = width - (chars_printed - 1) % width - 1;
1609 if (right)
1610 spaces += width - stringlen;
1612 spacebuf = (char *) alloca (spaces + 1);
1613 spacebuf[spaces] = '\0';
1614 while (spaces--)
1615 spacebuf[spaces] = ' ';
1617 gdb_puts (spacebuf);
1618 gdb_puts (string);
1622 /* Ensure that whatever gets printed next, using the filtered output
1623 commands, starts at the beginning of the line. I.e. if there is
1624 any pending output for the current line, flush it and start a new
1625 line. Otherwise do nothing. */
1627 void
1628 begin_line (void)
1630 if (chars_printed > 0)
1632 gdb_puts ("\n");
1636 void
1637 pager_file::puts (const char *linebuffer)
1639 const char *lineptr;
1641 if (linebuffer == 0)
1642 return;
1644 /* Don't do any filtering or wrapping if both are disabled. */
1645 if (batch_flag
1646 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
1647 || top_level_interpreter () == NULL
1648 || top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
1650 flush_wrap_buffer ();
1651 m_stream->puts (linebuffer);
1652 return;
1655 auto buffer_clearer
1656 = make_scope_exit ([&] ()
1658 m_wrap_buffer.clear ();
1659 m_wrap_column = 0;
1660 m_wrap_indent = 0;
1663 /* If the user does "set height 1" then the pager will exhibit weird
1664 behavior. This is pathological, though, so don't allow it. */
1665 const unsigned int lines_allowed = (lines_per_page > 1
1666 ? lines_per_page - 1
1667 : 1);
1669 /* Go through and output each character. Show line extension
1670 when this is necessary; prompt user for new page when this is
1671 necessary. */
1673 lineptr = linebuffer;
1674 while (*lineptr)
1676 /* Possible new page. Note that PAGINATION_DISABLED_FOR_COMMAND
1677 might be set during this loop, so we must continue to check
1678 it here. */
1679 if (pagination_enabled
1680 && !pagination_disabled_for_command
1681 && lines_printed >= lines_allowed)
1682 prompt_for_continue ();
1684 while (*lineptr && *lineptr != '\n')
1686 int skip_bytes;
1688 /* Print a single line. */
1689 if (*lineptr == '\t')
1691 m_wrap_buffer.push_back ('\t');
1692 /* Shifting right by 3 produces the number of tab stops
1693 we have already passed, and then adding one and
1694 shifting left 3 advances to the next tab stop. */
1695 chars_printed = ((chars_printed >> 3) + 1) << 3;
1696 lineptr++;
1698 else if (*lineptr == '\033'
1699 && skip_ansi_escape (lineptr, &skip_bytes))
1701 m_wrap_buffer.append (lineptr, skip_bytes);
1702 /* Note that we don't consider this a character, so we
1703 don't increment chars_printed here. */
1704 lineptr += skip_bytes;
1706 else if (*lineptr == '\r')
1708 m_wrap_buffer.push_back (*lineptr);
1709 chars_printed = 0;
1710 lineptr++;
1712 else
1714 m_wrap_buffer.push_back (*lineptr);
1715 chars_printed++;
1716 lineptr++;
1719 if (chars_printed >= chars_per_line)
1721 unsigned int save_chars = chars_printed;
1723 /* If we change the style, below, we'll want to reset it
1724 before continuing to print. If there is no wrap
1725 column, then we'll only reset the style if the pager
1726 prompt is given; and to avoid emitting style
1727 sequences in the middle of a run of text, we track
1728 this as well. */
1729 ui_file_style save_style = m_applied_style;
1730 bool did_paginate = false;
1732 chars_printed = 0;
1733 lines_printed++;
1734 if (m_wrap_column)
1736 /* We are about to insert a newline at an historic
1737 location in the WRAP_BUFFER. Before we do we want to
1738 restore the default style. To know if we actually
1739 need to insert an escape sequence we must restore the
1740 current applied style to how it was at the WRAP_COLUMN
1741 location. */
1742 m_applied_style = m_wrap_style;
1743 m_stream->emit_style_escape (ui_file_style ());
1744 /* If we aren't actually wrapping, don't output
1745 newline -- if chars_per_line is right, we
1746 probably just overflowed anyway; if it's wrong,
1747 let us keep going. */
1748 m_stream->puts ("\n");
1750 else
1751 this->flush_wrap_buffer ();
1753 /* Possible new page. Note that
1754 PAGINATION_DISABLED_FOR_COMMAND might be set during
1755 this loop, so we must continue to check it here. */
1756 if (pagination_enabled
1757 && !pagination_disabled_for_command
1758 && lines_printed >= lines_allowed)
1760 prompt_for_continue ();
1761 did_paginate = true;
1764 /* Now output indentation and wrapped string. */
1765 if (m_wrap_column)
1767 m_stream->puts (n_spaces (m_wrap_indent));
1769 /* Having finished inserting the wrapping we should
1770 restore the style as it was at the WRAP_COLUMN. */
1771 m_stream->emit_style_escape (m_wrap_style);
1773 /* The WRAP_BUFFER will still contain content, and that
1774 content might set some alternative style. Restore
1775 APPLIED_STYLE as it was before we started wrapping,
1776 this reflects the current style for the last character
1777 in WRAP_BUFFER. */
1778 m_applied_style = save_style;
1780 /* Note that this can set chars_printed > chars_per_line
1781 if we are printing a long string. */
1782 chars_printed = m_wrap_indent + (save_chars - m_wrap_column);
1783 m_wrap_column = 0; /* And disable fancy wrap */
1785 else if (did_paginate)
1786 m_stream->emit_style_escape (save_style);
1790 if (*lineptr == '\n')
1792 chars_printed = 0;
1793 wrap_here (0); /* Spit out chars, cancel further wraps. */
1794 lines_printed++;
1795 m_stream->puts ("\n");
1796 lineptr++;
1800 buffer_clearer.release ();
1803 void
1804 pager_file::write (const char *buf, long length_buf)
1806 /* We have to make a string here because the pager uses
1807 skip_ansi_escape, which requires NUL-termination. */
1808 std::string str (buf, length_buf);
1809 this->puts (str.c_str ());
1812 #if GDB_SELF_TEST
1814 /* Test that disabling the pager does not also disable word
1815 wrapping. */
1817 static void
1818 test_pager ()
1820 string_file *strfile = new string_file ();
1821 pager_file pager (strfile);
1823 /* Make sure the pager is disabled. */
1824 scoped_restore save_enabled
1825 = make_scoped_restore (&pagination_enabled, false);
1826 scoped_restore save_disabled
1827 = make_scoped_restore (&pagination_disabled_for_command, false);
1828 scoped_restore save_batch
1829 = make_scoped_restore (&batch_flag, false);
1830 scoped_restore save_lines
1831 = make_scoped_restore (&lines_per_page, 50);
1832 /* Make it easy to word wrap. */
1833 scoped_restore save_chars
1834 = make_scoped_restore (&chars_per_line, 15);
1835 scoped_restore save_printed
1836 = make_scoped_restore (&chars_printed, 0);
1838 pager.puts ("aaaaaaaaaaaa");
1839 pager.wrap_here (2);
1840 pager.puts ("bbbbbbbbbbbb\n");
1842 SELF_CHECK (strfile->string () == "aaaaaaaaaaaa\n bbbbbbbbbbbb\n");
1845 #endif /* GDB_SELF_TEST */
1847 void
1848 gdb_puts (const char *linebuffer, struct ui_file *stream)
1850 stream->puts (linebuffer);
1853 void
1854 gdb_puts (const std::string &s, ui_file *stream)
1856 gdb_puts (s.c_str (), stream);
1859 /* See utils.h. */
1861 void
1862 fputs_styled (const char *linebuffer, const ui_file_style &style,
1863 struct ui_file *stream)
1865 stream->emit_style_escape (style);
1866 gdb_puts (linebuffer, stream);
1867 stream->emit_style_escape (ui_file_style ());
1870 /* See utils.h. */
1872 void
1873 fputs_highlighted (const char *str, const compiled_regex &highlight,
1874 struct ui_file *stream)
1876 regmatch_t pmatch;
1878 while (*str && highlight.exec (str, 1, &pmatch, 0) == 0)
1880 size_t n_highlight = pmatch.rm_eo - pmatch.rm_so;
1882 /* Output the part before pmatch with current style. */
1883 while (pmatch.rm_so > 0)
1885 gdb_putc (*str, stream);
1886 pmatch.rm_so--;
1887 str++;
1890 /* Output pmatch with the highlight style. */
1891 stream->emit_style_escape (highlight_style.style ());
1892 while (n_highlight > 0)
1894 gdb_putc (*str, stream);
1895 n_highlight--;
1896 str++;
1898 stream->emit_style_escape (ui_file_style ());
1901 /* Output the trailing part of STR not matching HIGHLIGHT. */
1902 if (*str)
1903 gdb_puts (str, stream);
1906 void
1907 gdb_putc (int c)
1909 return gdb_stdout->putc (c);
1912 void
1913 gdb_putc (int c, struct ui_file *stream)
1915 return stream->putc (c);
1918 void
1919 gdb_vprintf (struct ui_file *stream, const char *format, va_list args)
1921 stream->vprintf (format, args);
1924 void
1925 gdb_vprintf (const char *format, va_list args)
1927 gdb_stdout->vprintf (format, args);
1930 void
1931 gdb_printf (struct ui_file *stream, const char *format, ...)
1933 va_list args;
1935 va_start (args, format);
1936 gdb_vprintf (stream, format, args);
1937 va_end (args);
1940 /* See utils.h. */
1942 void
1943 fprintf_styled (struct ui_file *stream, const ui_file_style &style,
1944 const char *format, ...)
1946 va_list args;
1948 stream->emit_style_escape (style);
1949 va_start (args, format);
1950 gdb_vprintf (stream, format, args);
1951 va_end (args);
1952 stream->emit_style_escape (ui_file_style ());
1955 void
1956 gdb_printf (const char *format, ...)
1958 va_list args;
1960 va_start (args, format);
1961 gdb_vprintf (gdb_stdout, format, args);
1962 va_end (args);
1966 void
1967 printf_unfiltered (const char *format, ...)
1969 va_list args;
1971 va_start (args, format);
1972 string_file file (gdb_stdout->can_emit_style_escape ());
1973 file.vprintf (format, args);
1974 gdb_stdout->puts_unfiltered (file.string ().c_str ());
1975 va_end (args);
1978 /* Easy -- but watch out!
1980 This routine is *not* a replacement for puts()! puts() appends a newline.
1981 This one doesn't, and had better not! */
1983 void
1984 gdb_puts (const char *string)
1986 gdb_stdout->puts (string);
1989 /* Return a pointer to N spaces and a null. The pointer is good
1990 until the next call to here. */
1991 const char *
1992 n_spaces (int n)
1994 char *t;
1995 static char *spaces = 0;
1996 static int max_spaces = -1;
1998 if (n > max_spaces)
2000 xfree (spaces);
2001 spaces = (char *) xmalloc (n + 1);
2002 for (t = spaces + n; t != spaces;)
2003 *--t = ' ';
2004 spaces[n] = '\0';
2005 max_spaces = n;
2008 return spaces + max_spaces - n;
2011 /* Print N spaces. */
2012 void
2013 print_spaces (int n, struct ui_file *stream)
2015 gdb_puts (n_spaces (n), stream);
2018 /* C++/ObjC demangler stuff. */
2020 /* fprintf_symbol attempts to demangle NAME, a symbol in language
2021 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2022 If the name is not mangled, or the language for the name is unknown, or
2023 demangling is off, the name is printed in its "raw" form. */
2025 void
2026 fprintf_symbol (struct ui_file *stream, const char *name,
2027 enum language lang, int arg_mode)
2029 if (name != NULL)
2031 /* If user wants to see raw output, no problem. */
2032 if (!demangle)
2034 gdb_puts (name, stream);
2036 else
2038 gdb::unique_xmalloc_ptr<char> demangled
2039 = language_def (lang)->demangle_symbol (name, arg_mode);
2040 gdb_puts (demangled ? demangled.get () : name, stream);
2045 /* True if CH is a character that can be part of a symbol name. I.e.,
2046 either a number, a letter, or a '_'. */
2048 static bool
2049 valid_identifier_name_char (int ch)
2051 return (ISALNUM (ch) || ch == '_');
2054 /* Skip to end of token, or to END, whatever comes first. Input is
2055 assumed to be a C++ operator name. */
2057 static const char *
2058 cp_skip_operator_token (const char *token, const char *end)
2060 const char *p = token;
2061 while (p != end && !ISSPACE (*p) && *p != '(')
2063 if (valid_identifier_name_char (*p))
2065 while (p != end && valid_identifier_name_char (*p))
2066 p++;
2067 return p;
2069 else
2071 /* Note, ordered such that among ops that share a prefix,
2072 longer comes first. This is so that the loop below can
2073 bail on first match. */
2074 static const char *ops[] =
2076 "[",
2077 "]",
2078 "~",
2079 ",",
2080 "-=", "--", "->", "-",
2081 "+=", "++", "+",
2082 "*=", "*",
2083 "/=", "/",
2084 "%=", "%",
2085 "|=", "||", "|",
2086 "&=", "&&", "&",
2087 "^=", "^",
2088 "!=", "!",
2089 "<<=", "<=", "<<", "<",
2090 ">>=", ">=", ">>", ">",
2091 "==", "=",
2094 for (const char *op : ops)
2096 size_t oplen = strlen (op);
2097 size_t lencmp = std::min<size_t> (oplen, end - p);
2099 if (strncmp (p, op, lencmp) == 0)
2100 return p + lencmp;
2102 /* Some unidentified character. Return it. */
2103 return p + 1;
2107 return p;
2110 /* Advance STRING1/STRING2 past whitespace. */
2112 static void
2113 skip_ws (const char *&string1, const char *&string2, const char *end_str2)
2115 while (ISSPACE (*string1))
2116 string1++;
2117 while (string2 < end_str2 && ISSPACE (*string2))
2118 string2++;
2121 /* True if STRING points at the start of a C++ operator name. START
2122 is the start of the string that STRING points to, hence when
2123 reading backwards, we must not read any character before START. */
2125 static bool
2126 cp_is_operator (const char *string, const char *start)
2128 return ((string == start
2129 || !valid_identifier_name_char (string[-1]))
2130 && strncmp (string, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
2131 && !valid_identifier_name_char (string[CP_OPERATOR_LEN]));
2134 /* If *NAME points at an ABI tag, skip it and return true. Otherwise
2135 leave *NAME unmodified and return false. (see GCC's abi_tag
2136 attribute), such names are demangled as e.g.,
2137 "function[abi:cxx11]()". */
2139 static bool
2140 skip_abi_tag (const char **name)
2142 const char *p = *name;
2144 if (startswith (p, "[abi:"))
2146 p += 5;
2148 while (valid_identifier_name_char (*p))
2149 p++;
2151 if (*p == ']')
2153 p++;
2154 *name = p;
2155 return true;
2158 return false;
2161 /* If *NAME points at a template parameter list, skip it and return true.
2162 Otherwise do nothing and return false. */
2164 static bool
2165 skip_template_parameter_list (const char **name)
2167 const char *p = *name;
2169 if (*p == '<')
2171 const char *template_param_list_end = find_toplevel_char (p + 1, '>');
2173 if (template_param_list_end == NULL)
2174 return false;
2176 p = template_param_list_end + 1;
2178 /* Skip any whitespace that might occur after the closing of the
2179 parameter list, but only if it is the end of parameter list. */
2180 const char *q = p;
2181 while (ISSPACE (*q))
2182 ++q;
2183 if (*q == '>')
2184 p = q;
2185 *name = p;
2186 return true;
2189 return false;
2192 /* See utils.h. */
2195 strncmp_iw_with_mode (const char *string1, const char *string2,
2196 size_t string2_len, strncmp_iw_mode mode,
2197 enum language language,
2198 completion_match_for_lcd *match_for_lcd,
2199 bool ignore_template_params)
2201 const char *string1_start = string1;
2202 const char *end_str2 = string2 + string2_len;
2203 bool skip_spaces = true;
2204 bool have_colon_op = (language == language_cplus
2205 || language == language_rust
2206 || language == language_fortran);
2208 gdb_assert (match_for_lcd == nullptr || match_for_lcd->empty ());
2210 while (1)
2212 if (skip_spaces
2213 || ((ISSPACE (*string1) && !valid_identifier_name_char (*string2))
2214 || (ISSPACE (*string2) && !valid_identifier_name_char (*string1))))
2216 skip_ws (string1, string2, end_str2);
2217 skip_spaces = false;
2220 /* Skip [abi:cxx11] tags in the symbol name if the lookup name
2221 doesn't include them. E.g.:
2223 string1: function[abi:cxx1](int)
2224 string2: function
2226 string1: function[abi:cxx1](int)
2227 string2: function(int)
2229 string1: Struct[abi:cxx1]::function()
2230 string2: Struct::function()
2232 string1: function(Struct[abi:cxx1], int)
2233 string2: function(Struct, int)
2235 if (string2 == end_str2
2236 || (*string2 != '[' && !valid_identifier_name_char (*string2)))
2238 const char *abi_start = string1;
2240 /* There can be more than one tag. */
2241 while (*string1 == '[' && skip_abi_tag (&string1))
2244 if (match_for_lcd != NULL && abi_start != string1)
2245 match_for_lcd->mark_ignored_range (abi_start, string1);
2247 while (ISSPACE (*string1))
2248 string1++;
2251 /* Skip template parameters in STRING1 if STRING2 does not contain
2252 any. E.g.:
2254 Case 1: User is looking for all functions named "foo".
2255 string1: foo <...> (...)
2256 string2: foo
2258 Case 2: User is looking for all methods named "foo" in all template
2259 class instantiations.
2260 string1: Foo<...>::foo <...> (...)
2261 string2: Foo::foo (...)
2263 Case 3: User is looking for a specific overload of a template
2264 function or method.
2265 string1: foo<...>
2266 string2: foo(...)
2268 Case 4: User is looking for a specific overload of a specific
2269 template instantiation.
2270 string1: foo<A> (...)
2271 string2: foo<B> (...)
2273 Case 5: User is looking wild parameter match.
2274 string1: foo<A<a<b<...> > > > (...)
2275 string2: foo<A
2277 if (language == language_cplus && ignore_template_params
2278 && *string1 == '<' && *string2 != '<')
2280 /* Skip any parameter list in STRING1. */
2281 const char *template_start = string1;
2283 if (skip_template_parameter_list (&string1))
2285 /* Don't mark the parameter list ignored if the user didn't
2286 try to ignore it. [Case #5 above] */
2287 if (*string2 != '\0'
2288 && match_for_lcd != NULL && template_start != string1)
2289 match_for_lcd->mark_ignored_range (template_start, string1);
2293 if (*string1 == '\0' || string2 == end_str2)
2294 break;
2296 /* Handle the :: operator. */
2297 if (have_colon_op && string1[0] == ':' && string1[1] == ':')
2299 if (*string2 != ':')
2300 return 1;
2302 string1++;
2303 string2++;
2305 if (string2 == end_str2)
2306 break;
2308 if (*string2 != ':')
2309 return 1;
2311 string1++;
2312 string2++;
2314 while (ISSPACE (*string1))
2315 string1++;
2316 while (string2 < end_str2 && ISSPACE (*string2))
2317 string2++;
2318 continue;
2321 /* Handle C++ user-defined operators. */
2322 else if (language == language_cplus
2323 && *string1 == 'o')
2325 if (cp_is_operator (string1, string1_start))
2327 /* An operator name in STRING1. Check STRING2. */
2328 size_t cmplen
2329 = std::min<size_t> (CP_OPERATOR_LEN, end_str2 - string2);
2330 if (strncmp (string1, string2, cmplen) != 0)
2331 return 1;
2333 string1 += cmplen;
2334 string2 += cmplen;
2336 if (string2 != end_str2)
2338 /* Check for "operatorX" in STRING2. */
2339 if (valid_identifier_name_char (*string2))
2340 return 1;
2342 skip_ws (string1, string2, end_str2);
2345 /* Handle operator(). */
2346 if (*string1 == '(')
2348 if (string2 == end_str2)
2350 if (mode == strncmp_iw_mode::NORMAL)
2351 return 0;
2352 else
2354 /* Don't break for the regular return at the
2355 bottom, because "operator" should not
2356 match "operator()", since this open
2357 parentheses is not the parameter list
2358 start. */
2359 return *string1 != '\0';
2363 if (*string1 != *string2)
2364 return 1;
2366 string1++;
2367 string2++;
2370 while (1)
2372 skip_ws (string1, string2, end_str2);
2374 /* Skip to end of token, or to END, whatever comes
2375 first. */
2376 const char *end_str1 = string1 + strlen (string1);
2377 const char *p1 = cp_skip_operator_token (string1, end_str1);
2378 const char *p2 = cp_skip_operator_token (string2, end_str2);
2380 cmplen = std::min (p1 - string1, p2 - string2);
2381 if (p2 == end_str2)
2383 if (strncmp (string1, string2, cmplen) != 0)
2384 return 1;
2386 else
2388 if (p1 - string1 != p2 - string2)
2389 return 1;
2390 if (strncmp (string1, string2, cmplen) != 0)
2391 return 1;
2394 string1 += cmplen;
2395 string2 += cmplen;
2397 if (*string1 == '\0' || string2 == end_str2)
2398 break;
2399 if (*string1 == '(' || *string2 == '(')
2400 break;
2402 /* If STRING1 or STRING2 starts with a template
2403 parameter list, break out of operator processing. */
2404 skip_ws (string1, string2, end_str2);
2405 if (*string1 == '<' || *string2 == '<')
2406 break;
2409 continue;
2413 if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2414 break;
2415 if (case_sensitivity == case_sensitive_off
2416 && (TOLOWER ((unsigned char) *string1)
2417 != TOLOWER ((unsigned char) *string2)))
2418 break;
2420 /* If we see any non-whitespace, non-identifier-name character
2421 (any of "()<>*&" etc.), then skip spaces the next time
2422 around. */
2423 if (!ISSPACE (*string1) && !valid_identifier_name_char (*string1))
2424 skip_spaces = true;
2426 string1++;
2427 string2++;
2430 if (string2 == end_str2)
2432 if (mode == strncmp_iw_mode::NORMAL)
2434 /* Strip abi tag markers from the matched symbol name.
2435 Usually the ABI marker will be found on function name
2436 (automatically added because the function returns an
2437 object marked with an ABI tag). However, it's also
2438 possible to see a marker in one of the function
2439 parameters, for example.
2441 string2 (lookup name):
2442 func
2443 symbol name:
2444 function(some_struct[abi:cxx11], int)
2446 and for completion LCD computation we want to say that
2447 the match was for:
2448 function(some_struct, int)
2450 if (match_for_lcd != NULL)
2452 while ((string1 = strstr (string1, "[abi:")) != NULL)
2454 const char *abi_start = string1;
2456 /* There can be more than one tag. */
2457 while (skip_abi_tag (&string1) && *string1 == '[')
2460 if (abi_start != string1)
2461 match_for_lcd->mark_ignored_range (abi_start, string1);
2465 return 0;
2467 else
2469 if (*string1 == '(')
2471 int p_count = 0;
2475 if (*string1 == '(')
2476 ++p_count;
2477 else if (*string1 == ')')
2478 --p_count;
2479 ++string1;
2481 while (*string1 != '\0' && p_count > 0);
2483 /* There maybe things like 'const' after the parameters,
2484 which we do want to ignore. However, if there's an '@'
2485 then this likely indicates something like '@plt' which we
2486 should not ignore. */
2487 return *string1 == '@';
2490 return *string1 == '\0' ? 0 : 1;
2494 else
2495 return 1;
2498 #if GDB_SELF_TEST
2500 /* Unit tests for strncmp_iw_with_mode. */
2502 #define CHECK_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2503 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2504 strncmp_iw_mode::MODE, \
2505 (LANG), (LCD)) == 0)
2507 #define CHECK_MATCH_LANG(S1, S2, MODE, LANG) \
2508 CHECK_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2510 #define CHECK_MATCH(S1, S2, MODE) \
2511 CHECK_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2513 #define CHECK_NO_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2514 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2515 strncmp_iw_mode::MODE, \
2516 (LANG)) != 0)
2518 #define CHECK_NO_MATCH_LANG(S1, S2, MODE, LANG) \
2519 CHECK_NO_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2521 #define CHECK_NO_MATCH(S1, S2, MODE) \
2522 CHECK_NO_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2524 static void
2525 check_scope_operator (enum language lang)
2527 CHECK_MATCH_LANG ("::", "::", NORMAL, lang);
2528 CHECK_MATCH_LANG ("::foo", "::", NORMAL, lang);
2529 CHECK_MATCH_LANG ("::foo", "::foo", NORMAL, lang);
2530 CHECK_MATCH_LANG (" :: foo ", "::foo", NORMAL, lang);
2531 CHECK_MATCH_LANG ("a::b", "a ::b", NORMAL, lang);
2532 CHECK_MATCH_LANG ("a::b", "a\t::b", NORMAL, lang);
2533 CHECK_MATCH_LANG ("a::b", "a \t::b", NORMAL, lang);
2534 CHECK_MATCH_LANG ("a::b", "a\t ::b", NORMAL, lang);
2535 CHECK_MATCH_LANG ("a::b", "a:: b", NORMAL, lang);
2536 CHECK_MATCH_LANG ("a::b", "a::\tb", NORMAL, lang);
2537 CHECK_MATCH_LANG ("a::b", "a:: \tb", NORMAL, lang);
2538 CHECK_MATCH_LANG ("a::b", "a::\t b", NORMAL, lang);
2539 CHECK_MATCH_LANG ("a::b", "a :: b", NORMAL, lang);
2540 CHECK_MATCH_LANG ("a::b", "a ::\tb", NORMAL, lang);
2541 CHECK_MATCH_LANG ("a::b", "a\t:: b", NORMAL, lang);
2542 CHECK_MATCH_LANG ("a::b", "a \t::\t b", NORMAL, lang);
2543 CHECK_MATCH_LANG ("a ::b", "a::b", NORMAL, lang);
2544 CHECK_MATCH_LANG ("a\t::b", "a::b", NORMAL, lang);
2545 CHECK_MATCH_LANG ("a \t::b", "a::b", NORMAL, lang);
2546 CHECK_MATCH_LANG ("a\t ::b", "a::b", NORMAL, lang);
2547 CHECK_MATCH_LANG ("a:: b", "a::b", NORMAL, lang);
2548 CHECK_MATCH_LANG ("a::\tb", "a::b", NORMAL, lang);
2549 CHECK_MATCH_LANG ("a:: \tb", "a::b", NORMAL, lang);
2550 CHECK_MATCH_LANG ("a::\t b", "a::b", NORMAL, lang);
2551 CHECK_MATCH_LANG ("a :: b", "a::b", NORMAL, lang);
2552 CHECK_MATCH_LANG ("a ::\tb", "a::b", NORMAL, lang);
2553 CHECK_MATCH_LANG ("a\t:: b", "a::b", NORMAL, lang);
2554 CHECK_MATCH_LANG ("a \t::\t b", "a::b", 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 ("a ::b ::c", "a::b::c", NORMAL, lang);
2559 CHECK_MATCH_LANG ("a::b::c", "a :: b:: c", NORMAL, lang);
2560 CHECK_MATCH_LANG ("\ta::\tb::\tc", "\ta::\tb::\tc", NORMAL, lang);
2561 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a\t::b\t::c\t", NORMAL, lang);
2562 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", " \ta:: \tb:: \tc", NORMAL, lang);
2563 CHECK_MATCH_LANG ("\t a::\t b::\t c", "\t a::\t b::\t c", NORMAL, lang);
2564 CHECK_MATCH_LANG ("a::b::c", "\ta::\tb::\tc", NORMAL, lang);
2565 CHECK_MATCH_LANG ("a::b::c", "a\t::b\t::c\t", NORMAL, lang);
2566 CHECK_MATCH_LANG ("a::b::c", " \ta:: \tb:: \tc", NORMAL, lang);
2567 CHECK_MATCH_LANG ("a::b::c", "\t a::\t b::\t c", NORMAL, lang);
2568 CHECK_MATCH_LANG ("\ta::\tb::\tc", "a::b::c", NORMAL, lang);
2569 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a::b::c", NORMAL, lang);
2570 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", "a::b::c", NORMAL, lang);
2571 CHECK_MATCH_LANG ("\t a::\t b::\t c", "a::b::c", NORMAL, lang);
2572 CHECK_MATCH_LANG ("a :: b:: c\t", "\ta :: b\t:: c\t\t", NORMAL, lang);
2573 CHECK_MATCH_LANG (" a::\t \t b:: c\t", "\ta ::b:: c\t\t",
2574 NORMAL, lang);
2575 CHECK_MATCH_LANG ("a :: b :: \t\t\tc\t",
2576 "\t\t\t\ta :: \t\t\t b \t\t::c",
2577 NORMAL, lang);
2578 CHECK_MATCH_LANG ("a::b()", "a", NORMAL, lang);
2579 CHECK_MATCH_LANG ("a::b()", "a::", NORMAL, lang);
2580 CHECK_MATCH_LANG ("a::b()", "a::b", NORMAL, lang);
2581 CHECK_MATCH_LANG ("a::b(a)", "a", NORMAL, lang);
2582 CHECK_MATCH_LANG ("a::b(a)", "a::", NORMAL, lang);
2583 CHECK_MATCH_LANG ("a::b(a)", "a::b", NORMAL, lang);
2584 CHECK_MATCH_LANG ("a::b(a,b)", "a", NORMAL, lang);
2585 CHECK_MATCH_LANG ("a::b(a,b)", "a::", NORMAL, lang);
2586 CHECK_MATCH_LANG ("a::b(a,b)", "a::b", NORMAL, lang);
2587 CHECK_MATCH_LANG ("a::b(a,b,c)", "a", NORMAL, lang);
2588 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::", NORMAL, lang);
2589 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::b", NORMAL, lang);
2591 CHECK_NO_MATCH_LANG ("a::", "::a", NORMAL, lang);
2592 CHECK_NO_MATCH_LANG ("::a", "::a()", NORMAL, lang);
2593 CHECK_NO_MATCH_LANG ("::", "::a", NORMAL, lang);
2594 CHECK_NO_MATCH_LANG ("a:::b", "a::b", NORMAL, lang);
2595 CHECK_NO_MATCH_LANG ("a::b()", "a::b(a)", NORMAL, lang);
2596 CHECK_NO_MATCH_LANG ("a::b(a)", "a::b()", NORMAL, lang);
2597 CHECK_NO_MATCH_LANG ("a::b(a,b)", "a::b(a,a)", NORMAL, lang);
2598 CHECK_NO_MATCH_LANG ("a::b", "a()", NORMAL, lang);
2599 CHECK_NO_MATCH_LANG ("a::b", "a::()", NORMAL, lang);
2600 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2601 CHECK_NO_MATCH_LANG ("a::b", "a(a)", NORMAL, lang);
2602 CHECK_NO_MATCH_LANG ("a::b", "a::(a)", NORMAL, lang);
2603 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2604 CHECK_NO_MATCH_LANG ("a::b", "a(a,b)", NORMAL, lang);
2605 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b)", NORMAL, lang);
2606 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b)", NORMAL, lang);
2607 CHECK_NO_MATCH_LANG ("a::b", "a(a,b,c)", NORMAL, lang);
2608 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b,c)", NORMAL, lang);
2609 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b,c)", NORMAL, lang);
2612 /* Callback for strncmp_iw_with_mode unit tests. */
2614 static void
2615 strncmp_iw_with_mode_tests ()
2617 /* Some of the following tests are nonsensical, but could be input by a
2618 deranged script (or user). */
2620 /* strncmp_iw_mode::NORMAL: strcmp()-like but ignore any whitespace... */
2622 CHECK_MATCH ("", "", 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 ("foo ", "foo", NORMAL);
2629 CHECK_MATCH (" foo ", "foo", NORMAL);
2630 CHECK_MATCH ("\tfoo", "foo", NORMAL);
2631 CHECK_MATCH ("foo\t", "foo", NORMAL);
2632 CHECK_MATCH ("\tfoo\t", "foo", NORMAL);
2633 CHECK_MATCH (" \tfoo \t", "foo", NORMAL);
2634 CHECK_MATCH ("\t foo\t ", "foo", NORMAL);
2635 CHECK_MATCH ("\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2636 "foo", NORMAL);
2637 CHECK_MATCH ("foo",
2638 "\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2639 NORMAL);
2640 CHECK_MATCH ("foo bar", "foo", NORMAL);
2641 CHECK_NO_MATCH ("foo", "bar", NORMAL);
2642 CHECK_NO_MATCH ("foo bar", "foobar", NORMAL);
2643 CHECK_NO_MATCH (" foo ", "bar", NORMAL);
2644 CHECK_NO_MATCH ("foo", " bar ", NORMAL);
2645 CHECK_NO_MATCH (" \t\t foo\t\t ", "\t \t \tbar\t", NORMAL);
2646 CHECK_NO_MATCH ("@!%&", "@!%&foo", NORMAL);
2648 /* ... and function parameters in STRING1. */
2649 CHECK_MATCH ("foo()", "foo()", NORMAL);
2650 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2651 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2652 CHECK_MATCH ("foo\t()", "foo()", NORMAL);
2653 CHECK_MATCH ("foo\t ()", "foo()", NORMAL);
2654 CHECK_MATCH ("foo \t()", "foo()", NORMAL);
2655 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2656 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2657 CHECK_MATCH ("foo()", "foo\t()", NORMAL);
2658 CHECK_MATCH ("foo()", "foo\t ()", NORMAL);
2659 CHECK_MATCH ("foo()", "foo \t()", NORMAL);
2660 CHECK_MATCH ("foo()", "foo()", NORMAL);
2661 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2662 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2663 CHECK_MATCH ("foo\t()", "foo\t()", NORMAL);
2664 CHECK_MATCH ("foo\t ()", "foo\t ()", NORMAL);
2665 CHECK_MATCH ("foo \t()", "foo \t()", NORMAL);
2666 CHECK_MATCH ("foo(a)", "foo(a)", NORMAL);
2667 CHECK_MATCH ("foo( a)", "foo(a)", NORMAL);
2668 CHECK_MATCH ("foo(a )", "foo(a)", NORMAL);
2669 CHECK_MATCH ("foo(\ta)", "foo(a)", NORMAL);
2670 CHECK_MATCH ("foo(a\t)", "foo(a)", NORMAL);
2671 CHECK_MATCH ("foo(\t a)", "foo(a)", NORMAL);
2672 CHECK_MATCH ("foo( \ta)", "foo(a)", NORMAL);
2673 CHECK_MATCH ("foo(a\t )", "foo(a)", NORMAL);
2674 CHECK_MATCH ("foo(a \t)", "foo(a)", NORMAL);
2675 CHECK_MATCH ("foo( a )", "foo(a)", NORMAL);
2676 CHECK_MATCH ("foo(\ta\t)", "foo(a)", NORMAL);
2677 CHECK_MATCH ("foo(\t a\t )", "foo(a)", NORMAL);
2678 CHECK_MATCH ("foo( \ta \t)", "foo(a)", NORMAL);
2679 CHECK_MATCH ("foo(a)", "foo( a)", NORMAL);
2680 CHECK_MATCH ("foo(a)", "foo(a )", NORMAL);
2681 CHECK_MATCH ("foo(a)", "foo(\ta)", NORMAL);
2682 CHECK_MATCH ("foo(a)", "foo(a\t)", NORMAL);
2683 CHECK_MATCH ("foo(a)", "foo(\t a)", NORMAL);
2684 CHECK_MATCH ("foo(a)", "foo( \ta)", NORMAL);
2685 CHECK_MATCH ("foo(a)", "foo(a\t )", NORMAL);
2686 CHECK_MATCH ("foo(a)", "foo(a \t)", NORMAL);
2687 CHECK_MATCH ("foo(a)", "foo( a )", NORMAL);
2688 CHECK_MATCH ("foo(a)", "foo(\ta\t)", NORMAL);
2689 CHECK_MATCH ("foo(a)", "foo(\t a\t )", NORMAL);
2690 CHECK_MATCH ("foo(a)", "foo( \ta \t)", NORMAL);
2691 CHECK_MATCH ("foo(a,b)", "foo(a,b)", NORMAL);
2692 CHECK_MATCH ("foo(a ,b)", "foo(a,b)", NORMAL);
2693 CHECK_MATCH ("foo(a\t,b)", "foo(a,b)", NORMAL);
2694 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2695 CHECK_MATCH ("foo(a\t,\tb)", "foo(a,b)", NORMAL);
2696 CHECK_MATCH ("foo(a \t,b)", "foo(a,b)", NORMAL);
2697 CHECK_MATCH ("foo(a\t ,b)", "foo(a,b)", NORMAL);
2698 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2699 CHECK_MATCH ("foo(a, \tb)", "foo(a,b)", NORMAL);
2700 CHECK_MATCH ("foo(a,\t b)", "foo(a,b)", NORMAL);
2701 CHECK_MATCH ("foo(a,b)", "foo(a ,b)", NORMAL);
2702 CHECK_MATCH ("foo(a,b)", "foo(a\t,b)", NORMAL);
2703 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2704 CHECK_MATCH ("foo(a,b)", "foo(a\t,\tb)", NORMAL);
2705 CHECK_MATCH ("foo(a,b)", "foo(a \t,b)", NORMAL);
2706 CHECK_MATCH ("foo(a,b)", "foo(a\t ,b)", NORMAL);
2707 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2708 CHECK_MATCH ("foo(a,b)", "foo(a, \tb)", NORMAL);
2709 CHECK_MATCH ("foo(a,b)", "foo(a,\t b)", NORMAL);
2710 CHECK_MATCH ("foo(a,b,c,d)", "foo(a,b,c,d)", NORMAL);
2711 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo(a,b,c,d)", NORMAL);
2712 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo( a , b , c , d )", NORMAL);
2713 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo", NORMAL);
2714 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo&*(a b * &)", NORMAL);
2715 CHECK_MATCH ("foo(a) b", "foo(a)", NORMAL);
2716 CHECK_MATCH ("*foo(*a&)", "*foo", NORMAL);
2717 CHECK_MATCH ("*foo(*a&)", "*foo(*a&)", NORMAL);
2718 CHECK_MATCH ("*a&b#c/^d$foo(*a&)", "*a&b#c/^d$foo", NORMAL);
2719 CHECK_MATCH ("* foo", "*foo", NORMAL);
2720 CHECK_MATCH ("foo&", "foo", NORMAL);
2721 CHECK_MATCH ("foo*", "foo", NORMAL);
2722 CHECK_MATCH ("foo.", "foo", NORMAL);
2723 CHECK_MATCH ("foo->", "foo", NORMAL);
2725 CHECK_NO_MATCH ("foo", "foo(", NORMAL);
2726 CHECK_NO_MATCH ("foo", "foo()", NORMAL);
2727 CHECK_NO_MATCH ("foo", "foo(a)", NORMAL);
2728 CHECK_NO_MATCH ("foo", "foo(a)", 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 &", "foo (*", NORMAL);
2735 CHECK_NO_MATCH ("foo &*", "foo (&)", NORMAL);
2736 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2737 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2738 CHECK_NO_MATCH ("foo(a*) b", "foo(a) b", NORMAL);
2739 CHECK_NO_MATCH ("foo[aqi:A](a)", "foo(b)", 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", "foo.", NORMAL);
2750 CHECK_NO_MATCH ("foo", "foo->", NORMAL);
2751 CHECK_NO_MATCH ("foo bar", "foo()", NORMAL);
2752 CHECK_NO_MATCH ("foo bar", "foo bar()", NORMAL);
2753 CHECK_NO_MATCH ("foo()", "foo(a)", NORMAL);
2754 CHECK_NO_MATCH ("*(*)&", "*(*)*", NORMAL);
2755 CHECK_NO_MATCH ("foo(a)", "foo()", NORMAL);
2756 CHECK_NO_MATCH ("foo(a)", "foo(b)", NORMAL);
2757 CHECK_NO_MATCH ("foo(a,b)", "foo(a,b,c)", NORMAL);
2758 CHECK_NO_MATCH ("foo(a\\b)", "foo()", NORMAL);
2759 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar", NORMAL);
2760 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar ( a b c \td\t)\t", NORMAL);
2762 /* Test scope operator. */
2763 check_scope_operator (language_minimal);
2764 check_scope_operator (language_cplus);
2765 check_scope_operator (language_fortran);
2766 check_scope_operator (language_rust);
2768 /* Test C++ user-defined operators. */
2769 CHECK_MATCH_LANG ("operator foo(int&)", "operator foo(int &)", NORMAL,
2770 language_cplus);
2771 CHECK_MATCH_LANG ("operator foo(int &)", "operator foo(int &)", NORMAL,
2772 language_cplus);
2773 CHECK_MATCH_LANG ("operator foo(int\t&)", "operator foo(int\t&)", NORMAL,
2774 language_cplus);
2775 CHECK_MATCH_LANG ("operator foo (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 \t(int)", "operator foo(int)", NORMAL,
2780 language_cplus);
2781 CHECK_MATCH_LANG ("operator foo (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);
2785 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo \t(int)", NORMAL,
2786 language_cplus);
2788 CHECK_MATCH_LANG ("a::operator foo(int&)", "a::operator foo(int &)", NORMAL,
2789 language_cplus);
2790 CHECK_MATCH_LANG ("a :: operator foo(int &)", "a::operator foo(int &)", NORMAL,
2791 language_cplus);
2792 CHECK_MATCH_LANG ("a \t:: \toperator foo(int\t&)", "a::operator foo(int\t&)", NORMAL,
2793 language_cplus);
2794 CHECK_MATCH_LANG ("a::operator foo (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 \t(int)", "a::operator foo(int)", NORMAL,
2799 language_cplus);
2800 CHECK_MATCH_LANG ("a::operator foo (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);
2804 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo \t(int)", NORMAL,
2805 language_cplus);
2807 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(char)", 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 &)", NORMAL,
2812 language_cplus);
2813 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int, char *)", NORMAL,
2814 language_cplus);
2815 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator bar(int)", NORMAL,
2816 language_cplus);
2818 CHECK_NO_MATCH_LANG ("a::operator b::foo(int)", "a::operator a::foo(char)", 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 &)", NORMAL,
2823 language_cplus);
2824 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int, char *)", NORMAL,
2825 language_cplus);
2826 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator bar(int)", NORMAL,
2827 language_cplus);
2829 /* Skip "[abi:cxx11]" tags in the symbol name if the lookup name
2830 doesn't include them. These are not language-specific in
2831 strncmp_iw_with_mode. */
2833 CHECK_MATCH ("foo[abi:a]", "foo", NORMAL);
2834 CHECK_MATCH ("foo[abi:a]()", "foo", NORMAL);
2835 CHECK_MATCH ("foo[abi:a](a)", "foo", NORMAL);
2836 CHECK_MATCH ("foo[abi:a](a&,b*)", "foo", NORMAL);
2837 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2838 CHECK_MATCH ("foo[abi:a](a,b) c", "foo(a,b) c", NORMAL);
2839 CHECK_MATCH ("foo[abi:a](a)", "foo(a)", NORMAL);
2840 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2841 CHECK_MATCH ("foo[abi:a]", "foo[abi:a]", NORMAL);
2842 CHECK_MATCH ("foo[ abi:a]", "foo[abi:a]", NORMAL);
2843 CHECK_MATCH ("foo[\tabi:a]", "foo[abi:a]", NORMAL);
2844 CHECK_MATCH ("foo[ \tabi:a]", "foo[abi:a]", NORMAL);
2845 CHECK_MATCH ("foo[\t abi:a]", "foo[abi:a]", NORMAL);
2846 CHECK_MATCH ("foo[abi :a]", "foo[abi:a]", NORMAL);
2847 CHECK_MATCH ("foo[abi\t:a]", "foo[abi:a]", NORMAL);
2848 CHECK_MATCH ("foo[abi \t:a]", "foo[abi:a]", NORMAL);
2849 CHECK_MATCH ("foo[abi\t :a]", "foo[abi:a]", NORMAL);
2850 CHECK_MATCH ("foo[abi:a]", "foo[ abi:a]", NORMAL);
2851 CHECK_MATCH ("foo[abi:a]", "foo[\tabi:a]", NORMAL);
2852 CHECK_MATCH ("foo[abi:a]", "foo[ \tabi:a]", NORMAL);
2853 CHECK_MATCH ("foo[abi:a]", "foo[\t abi:a]", NORMAL);
2854 CHECK_MATCH ("foo[abi:a]", "foo[abi :a]", NORMAL);
2855 CHECK_MATCH ("foo[abi:a]", "foo[abi\t:a]", NORMAL);
2856 CHECK_MATCH ("foo[abi:a]", "foo[abi \t:a]", NORMAL);
2857 CHECK_MATCH ("foo[abi:a]", "foo[abi\t :a]", NORMAL);
2858 CHECK_MATCH ("foo[abi:a]", "foo[abi:a ]", NORMAL);
2859 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t]", NORMAL);
2860 CHECK_MATCH ("foo[abi:a]", "foo[abi:a \t]", NORMAL);
2861 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t ]", NORMAL);
2862 CHECK_MATCH ("foo[abi:a,b]", "foo[abi:a,b]", NORMAL);
2863 CHECK_MATCH ("foo[abi:::]", "foo[abi:::]", NORMAL);
2864 CHECK_MATCH ("foo[abi : : : ]", "foo[abi:::]", NORMAL);
2865 CHECK_MATCH ("foo[abi:::]", "foo[abi : : : ]", NORMAL);
2866 CHECK_MATCH ("foo[ \t abi \t:\t: : \t]",
2867 "foo[ abi : \t ::]",
2868 NORMAL);
2869 CHECK_MATCH ("foo< bar< baz< quxi > > >(int)", "foo<bar<baz<quxi>>>(int)",
2870 NORMAL);
2871 CHECK_MATCH ("\tfoo<\tbar<\tbaz\t<\tquxi\t>\t>\t>(int)",
2872 "foo<bar<baz<quxi>>>(int)", NORMAL);
2873 CHECK_MATCH (" \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)",
2874 "foo<bar<baz<quxi>>>(int)", NORMAL);
2875 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2876 "foo < bar < baz < quxi > > > (int)", NORMAL);
2877 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2878 "\tfoo\t<\tbar\t<\tbaz\t<\tquxi\t>\t>\t>\t(int)", NORMAL);
2879 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2880 " \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)", NORMAL);
2881 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "fo", NORMAL);
2882 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo", NORMAL);
2883 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz>>::", NORMAL);
2884 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz> >::foo", NORMAL);
2885 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
2886 NORMAL);
2887 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", NORMAL);
2888 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar)", NORMAL);
2889 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar)", NORMAL);
2890 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar[abi:c])", NORMAL);
2891 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar[abi:c])", NORMAL);
2892 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar)", NORMAL);
2893 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c])",
2894 NORMAL);
2895 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo", NORMAL);
2896 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo()", NORMAL);
2897 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>", NORMAL);
2898 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz)", NORMAL);
2899 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:b])",
2900 NORMAL);
2901 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:A])",
2902 NORMAL);
2903 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz)",
2904 NORMAL);
2905 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:A]>(char*, baz)",
2906 NORMAL);
2907 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz[abi:b])",
2908 NORMAL);
2909 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])",
2910 "foo<bar[abi:a]>(char*, baz[abi:B])", NORMAL);
2912 CHECK_NO_MATCH ("foo", "foo[", NORMAL);
2913 CHECK_NO_MATCH ("foo", "foo[]", NORMAL);
2914 CHECK_NO_MATCH ("foo", "foo[ a]", NORMAL);
2915 CHECK_NO_MATCH ("foo", "foo[a ]", NORMAL);
2916 CHECK_NO_MATCH ("foo", "foo[ a ]", NORMAL);
2917 CHECK_NO_MATCH ("foo", "foo[\ta]", NORMAL);
2918 CHECK_NO_MATCH ("foo", "foo[a \t]", NORMAL);
2919 CHECK_NO_MATCH ("foo", "foo[a\t ]", NORMAL);
2920 CHECK_NO_MATCH ("foo", "foo[ \ta]", NORMAL);
2921 CHECK_NO_MATCH ("foo", "foo[\t a]", NORMAL);
2922 CHECK_NO_MATCH ("foo", "foo[ \ta \t]", NORMAL);
2923 CHECK_NO_MATCH ("foo", "foo[\t a\t ]", NORMAL);
2924 CHECK_NO_MATCH ("foo", "foo[abi]", NORMAL);
2925 CHECK_NO_MATCH ("foo", "foo[ abi]", NORMAL);
2926 CHECK_NO_MATCH ("foo", "foo[abi ]", NORMAL);
2927 CHECK_NO_MATCH ("foo", "foo[\tabi]", NORMAL);
2928 CHECK_NO_MATCH ("foo", "foo[abi\t]", NORMAL);
2929 CHECK_NO_MATCH ("foo", "foo[ \tabi]", NORMAL);
2930 CHECK_NO_MATCH ("foo", "foo[\t abi]", NORMAL);
2931 CHECK_NO_MATCH ("foo", "foo[abi \t]", NORMAL);
2932 CHECK_NO_MATCH ("foo", "foo[abi\t ]", NORMAL);
2933 CHECK_NO_MATCH ("foo", "foo[abi :]", NORMAL);
2934 CHECK_NO_MATCH ("foo", "foo[abi\t:]", NORMAL);
2935 CHECK_NO_MATCH ("foo", "foo[abi \t:]", NORMAL);
2936 CHECK_NO_MATCH ("foo", "foo[abi\t :]", NORMAL);
2937 CHECK_NO_MATCH ("foo", "foo[abi: ]", NORMAL);
2938 CHECK_NO_MATCH ("foo", "foo[abi:\t]", NORMAL);
2939 CHECK_NO_MATCH ("foo", "foo[abi: \t]", NORMAL);
2940 CHECK_NO_MATCH ("foo", "foo[abi:\t ]", NORMAL);
2941 CHECK_NO_MATCH ("foo", "foo[abi: a]", NORMAL);
2942 CHECK_NO_MATCH ("foo", "foo[abi:\ta]", NORMAL);
2943 CHECK_NO_MATCH ("foo", "foo[abi: \ta]", NORMAL);
2944 CHECK_NO_MATCH ("foo", "foo[abi:\t a]", NORMAL);
2945 CHECK_NO_MATCH ("foo", "foo[abi:a ]", NORMAL);
2946 CHECK_NO_MATCH ("foo", "foo[abi:a\t]", NORMAL);
2947 CHECK_NO_MATCH ("foo", "foo[abi:a \t]", NORMAL);
2948 CHECK_NO_MATCH ("foo", "foo[abi:a\t ]", 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)", NORMAL);
2952 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a)", NORMAL);
2953 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) c", NORMAL);
2954 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) .", NORMAL);
2955 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) *", NORMAL);
2956 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) &", NORMAL);
2957 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) c", 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) *", 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)c", NORMAL);
2962 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b).", NORMAL);
2963 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)*", NORMAL);
2964 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)&", NORMAL);
2965 CHECK_NO_MATCH ("foo[abi:a](a,b) d", "foo(a,b) c", NORMAL);
2966 CHECK_NO_MATCH ("foo[abi:a](a)", "foo()", NORMAL);
2967 CHECK_NO_MATCH ("foo[abi:a](a)", "foo(b)", NORMAL);
2968 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:b](a)", NORMAL);
2969 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:a](b)", 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:]", "foo[abi:a", NORMAL);
2973 CHECK_NO_MATCH ("foo[abi:,]", "foo[abi:a]", NORMAL);
2974 CHECK_NO_MATCH ("foo[abi:a,b]", "foo[abi:a]", NORMAL);
2975 CHECK_NO_MATCH ("foo[abi::a]", "foo[abi:a]", NORMAL);
2976 CHECK_NO_MATCH ("foo[abi:,([a]", "foo[abi:a]", NORMAL);
2978 CHECK_MATCH ("foo <a, b [, c (", "foo", NORMAL);
2979 CHECK_MATCH ("foo >a, b ], c )", "foo", NORMAL);
2980 CHECK_MATCH ("@!%&\\*", "@!%&\\*", NORMAL);
2981 CHECK_MATCH ("()", "()", NORMAL);
2982 CHECK_MATCH ("*(*)*", "*(*)*", NORMAL);
2983 CHECK_MATCH ("[]", "[]", NORMAL);
2984 CHECK_MATCH ("<>", "<>", NORMAL);
2986 /* strncmp_iw_with_mode::MATCH_PARAMS: the "strcmp_iw hack." */
2987 CHECK_MATCH ("foo2", "foo", NORMAL);
2988 CHECK_NO_MATCH ("foo2", "foo", MATCH_PARAMS);
2989 CHECK_NO_MATCH ("foo2", "foo ", 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\t ", MATCH_PARAMS);
2993 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2994 CHECK_NO_MATCH ("foo2", " foo", MATCH_PARAMS);
2995 CHECK_NO_MATCH ("foo2", "\tfoo", MATCH_PARAMS);
2996 CHECK_NO_MATCH ("foo2", " \tfoo", MATCH_PARAMS);
2997 CHECK_NO_MATCH ("foo2", "\t foo", MATCH_PARAMS);
2998 CHECK_NO_MATCH (" foo2", "foo", MATCH_PARAMS);
2999 CHECK_NO_MATCH ("\tfoo2", "foo", MATCH_PARAMS);
3000 CHECK_NO_MATCH (" \tfoo2", "foo", MATCH_PARAMS);
3001 CHECK_NO_MATCH ("\t foo2", "foo", MATCH_PARAMS);
3002 CHECK_NO_MATCH (" foo2 ", " foo ", MATCH_PARAMS);
3003 CHECK_NO_MATCH ("\tfoo2\t", "\tfoo\t", MATCH_PARAMS);
3004 CHECK_NO_MATCH (" \tfoo2 \t", " \tfoo \t", MATCH_PARAMS);
3005 CHECK_NO_MATCH ("\t foo2\t ", "\t foo\t ", MATCH_PARAMS);
3006 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
3007 CHECK_NO_MATCH ("foo2\t", "foo", MATCH_PARAMS);
3008 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
3009 CHECK_NO_MATCH ("foo2 \t", "foo", MATCH_PARAMS);
3010 CHECK_NO_MATCH ("foo2\t ", "foo", MATCH_PARAMS);
3011 CHECK_NO_MATCH ("foo2 (args)", "foo", MATCH_PARAMS);
3012 CHECK_NO_MATCH ("foo2 (args)", "foo", MATCH_PARAMS);
3013 CHECK_NO_MATCH ("foo2\t(args)", "foo", MATCH_PARAMS);
3014 CHECK_NO_MATCH ("foo2 \t(args)", "foo", MATCH_PARAMS);
3015 CHECK_NO_MATCH ("foo2\t (args)", "foo", MATCH_PARAMS);
3016 CHECK_NO_MATCH ("foo2 ( args)", "foo", MATCH_PARAMS);
3017 CHECK_NO_MATCH ("foo2(args )", "foo", MATCH_PARAMS);
3018 CHECK_NO_MATCH ("foo2(args\t)", "foo", MATCH_PARAMS);
3019 CHECK_NO_MATCH ("foo2 (args \t)", "foo", MATCH_PARAMS);
3020 CHECK_NO_MATCH ("foo2 (args\t )", "foo", MATCH_PARAMS);
3021 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
3022 MATCH_PARAMS);
3023 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", MATCH_PARAMS);
3024 CHECK_NO_MATCH ("foo(args)@plt", "foo", MATCH_PARAMS);
3025 CHECK_NO_MATCH ("foo((())args(()))@plt", "foo", MATCH_PARAMS);
3026 CHECK_MATCH ("foo((())args(()))", "foo", MATCH_PARAMS);
3027 CHECK_MATCH ("foo(args) const", "foo", MATCH_PARAMS);
3028 CHECK_MATCH ("foo(args)const", "foo", MATCH_PARAMS);
3030 /* strncmp_iw_with_mode also supports case insensitivity. */
3032 CHECK_NO_MATCH ("FoO", "foo", NORMAL);
3033 CHECK_NO_MATCH ("FoO", "foo", MATCH_PARAMS);
3035 scoped_restore restore_case = make_scoped_restore (&case_sensitivity);
3036 case_sensitivity = case_sensitive_off;
3038 CHECK_MATCH ("FoO", "foo", NORMAL);
3039 CHECK_MATCH ("FoO", "foo", MATCH_PARAMS);
3040 CHECK_MATCH ("foo", "FoO", NORMAL);
3041 CHECK_MATCH ("foo", "FoO", MATCH_PARAMS);
3043 CHECK_MATCH ("FoO[AbI:abC]()", "foo", NORMAL);
3044 CHECK_NO_MATCH ("FoO[AbI:abC]()", "foo", MATCH_PARAMS);
3045 CHECK_MATCH ("FoO2[AbI:abC]()", "foo", NORMAL);
3046 CHECK_NO_MATCH ("FoO2[AbI:abC]()", "foo", MATCH_PARAMS);
3048 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:abC]()", NORMAL);
3049 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:AbC]()", MATCH_PARAMS);
3050 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3051 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", MATCH_PARAMS);
3052 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3053 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)",
3054 MATCH_PARAMS);
3055 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3056 NORMAL);
3057 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3058 MATCH_PARAMS);
3062 #undef MATCH
3063 #undef NO_MATCH
3064 #endif
3066 /* See utils.h. */
3069 strncmp_iw (const char *string1, const char *string2, size_t string2_len)
3071 return strncmp_iw_with_mode (string1, string2, string2_len,
3072 strncmp_iw_mode::NORMAL, language_minimal);
3075 /* See utils.h. */
3078 strcmp_iw (const char *string1, const char *string2)
3080 return strncmp_iw_with_mode (string1, string2, strlen (string2),
3081 strncmp_iw_mode::MATCH_PARAMS, language_minimal);
3084 /* This is like strcmp except that it ignores whitespace and treats
3085 '(' as the first non-NULL character in terms of ordering. Like
3086 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
3087 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
3088 according to that ordering.
3090 If a list is sorted according to this function and if you want to
3091 find names in the list that match some fixed NAME according to
3092 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
3093 where this function would put NAME.
3095 This function must be neutral to the CASE_SENSITIVITY setting as the user
3096 may choose it during later lookup. Therefore this function always sorts
3097 primarily case-insensitively and secondarily case-sensitively.
3099 Here are some examples of why using strcmp to sort is a bad idea:
3101 Whitespace example:
3103 Say your partial symtab contains: "foo<char *>", "goo". Then, if
3104 we try to do a search for "foo<char*>", strcmp will locate this
3105 after "foo<char *>" and before "goo". Then lookup_partial_symbol
3106 will start looking at strings beginning with "goo", and will never
3107 see the correct match of "foo<char *>".
3109 Parenthesis example:
3111 In practice, this is less like to be an issue, but I'll give it a
3112 shot. Let's assume that '$' is a legitimate character to occur in
3113 symbols. (Which may well even be the case on some systems.) Then
3114 say that the partial symbol table contains "foo$" and "foo(int)".
3115 strcmp will put them in this order, since '$' < '('. Now, if the
3116 user searches for "foo", then strcmp will sort "foo" before "foo$".
3117 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
3118 "foo") is false, so it won't proceed to the actual match of
3119 "foo(int)" with "foo". */
3122 strcmp_iw_ordered (const char *string1, const char *string2)
3124 const char *saved_string1 = string1, *saved_string2 = string2;
3125 enum case_sensitivity case_pass = case_sensitive_off;
3127 for (;;)
3129 /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
3130 Provide stub characters if we are already at the end of one of the
3131 strings. */
3132 char c1 = 'X', c2 = 'X';
3134 while (*string1 != '\0' && *string2 != '\0')
3136 while (ISSPACE (*string1))
3137 string1++;
3138 while (ISSPACE (*string2))
3139 string2++;
3141 switch (case_pass)
3143 case case_sensitive_off:
3144 c1 = TOLOWER ((unsigned char) *string1);
3145 c2 = TOLOWER ((unsigned char) *string2);
3146 break;
3147 case case_sensitive_on:
3148 c1 = *string1;
3149 c2 = *string2;
3150 break;
3152 if (c1 != c2)
3153 break;
3155 if (*string1 != '\0')
3157 string1++;
3158 string2++;
3162 switch (*string1)
3164 /* Characters are non-equal unless they're both '\0'; we want to
3165 make sure we get the comparison right according to our
3166 comparison in the cases where one of them is '\0' or '('. */
3167 case '\0':
3168 if (*string2 == '\0')
3169 break;
3170 else
3171 return -1;
3172 case '(':
3173 if (*string2 == '\0')
3174 return 1;
3175 else
3176 return -1;
3177 default:
3178 if (*string2 == '\0' || *string2 == '(')
3179 return 1;
3180 else if (c1 > c2)
3181 return 1;
3182 else if (c1 < c2)
3183 return -1;
3184 /* PASSTHRU */
3187 if (case_pass == case_sensitive_on)
3188 return 0;
3190 /* Otherwise the strings were equal in case insensitive way, make
3191 a more fine grained comparison in a case sensitive way. */
3193 case_pass = case_sensitive_on;
3194 string1 = saved_string1;
3195 string2 = saved_string2;
3201 static void
3202 show_debug_timestamp (struct ui_file *file, int from_tty,
3203 struct cmd_list_element *c, const char *value)
3205 gdb_printf (file, _("Timestamping debugging messages is %s.\n"),
3206 value);
3210 const char *
3211 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
3213 /* Truncate address to the size of a target address, avoiding shifts
3214 larger or equal than the width of a CORE_ADDR. The local
3215 variable ADDR_BIT stops the compiler reporting a shift overflow
3216 when it won't occur. */
3217 /* NOTE: This assumes that the significant address information is
3218 kept in the least significant bits of ADDR - the upper bits were
3219 either zero or sign extended. Should gdbarch_address_to_pointer or
3220 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
3222 int addr_bit = gdbarch_addr_bit (gdbarch);
3224 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3225 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
3226 return hex_string (addr);
3229 /* This function is described in "defs.h". */
3231 const char *
3232 print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
3234 int addr_bit = gdbarch_addr_bit (gdbarch);
3236 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3237 address &= ((CORE_ADDR) 1 << addr_bit) - 1;
3239 /* FIXME: cagney/2002-05-03: Need local_address_string() function
3240 that returns the language localized string formatted to a width
3241 based on gdbarch_addr_bit. */
3242 if (addr_bit <= 32)
3243 return hex_string_custom (address, 8);
3244 else
3245 return hex_string_custom (address, 16);
3248 /* Convert a string back into a CORE_ADDR. */
3249 CORE_ADDR
3250 string_to_core_addr (const char *my_string)
3252 CORE_ADDR addr = 0;
3254 if (my_string[0] == '0' && TOLOWER (my_string[1]) == 'x')
3256 /* Assume that it is in hex. */
3257 int i;
3259 for (i = 2; my_string[i] != '\0'; i++)
3261 if (ISDIGIT (my_string[i]))
3262 addr = (my_string[i] - '0') + (addr * 16);
3263 else if (ISXDIGIT (my_string[i]))
3264 addr = (TOLOWER (my_string[i]) - 'a' + 0xa) + (addr * 16);
3265 else
3266 error (_("invalid hex \"%s\""), my_string);
3269 else
3271 /* Assume that it is in decimal. */
3272 int i;
3274 for (i = 0; my_string[i] != '\0'; i++)
3276 if (ISDIGIT (my_string[i]))
3277 addr = (my_string[i] - '0') + (addr * 10);
3278 else
3279 error (_("invalid decimal \"%s\""), my_string);
3283 return addr;
3286 #if GDB_SELF_TEST
3288 static void
3289 gdb_realpath_check_trailer (const char *input, const char *trailer)
3291 gdb::unique_xmalloc_ptr<char> result = gdb_realpath (input);
3293 size_t len = strlen (result.get ());
3294 size_t trail_len = strlen (trailer);
3296 SELF_CHECK (len >= trail_len
3297 && strcmp (result.get () + len - trail_len, trailer) == 0);
3300 static void
3301 gdb_realpath_tests ()
3303 /* A file which contains a directory prefix. */
3304 gdb_realpath_check_trailer ("./xfullpath.exp", "/xfullpath.exp");
3305 /* A file which contains a directory prefix. */
3306 gdb_realpath_check_trailer ("../../defs.h", "/defs.h");
3307 /* A one-character filename. */
3308 gdb_realpath_check_trailer ("./a", "/a");
3309 /* A file in the root directory. */
3310 gdb_realpath_check_trailer ("/root_file_which_should_exist",
3311 "/root_file_which_should_exist");
3312 /* A file which does not have a directory prefix. */
3313 gdb_realpath_check_trailer ("xfullpath.exp", "xfullpath.exp");
3314 /* A one-char filename without any directory prefix. */
3315 gdb_realpath_check_trailer ("a", "a");
3316 /* An empty filename. */
3317 gdb_realpath_check_trailer ("", "");
3320 /* Test the gdb_argv::as_array_view method. */
3322 static void
3323 gdb_argv_as_array_view_test ()
3326 gdb_argv argv;
3328 gdb::array_view<char *> view = argv.as_array_view ();
3330 SELF_CHECK (view.data () == nullptr);
3331 SELF_CHECK (view.size () == 0);
3334 gdb_argv argv ("une bonne 50");
3336 gdb::array_view<char *> view = argv.as_array_view ();
3338 SELF_CHECK (view.size () == 3);
3339 SELF_CHECK (strcmp (view[0], "une") == 0);
3340 SELF_CHECK (strcmp (view[1], "bonne") == 0);
3341 SELF_CHECK (strcmp (view[2], "50") == 0);
3345 #endif /* GDB_SELF_TEST */
3347 /* Simple, portable version of dirname that does not modify its
3348 argument. */
3350 std::string
3351 ldirname (const char *filename)
3353 std::string dirname;
3354 const char *base = lbasename (filename);
3356 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3357 --base;
3359 if (base == filename)
3360 return dirname;
3362 dirname = std::string (filename, base - filename);
3364 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3365 create "d:./bar" later instead of the (different) "d:/bar". */
3366 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3367 && !IS_DIR_SEPARATOR (filename[0]))
3368 dirname[base++ - filename] = '.';
3370 return dirname;
3373 /* Return ARGS parsed as a valid pid, or throw an error. */
3376 parse_pid_to_attach (const char *args)
3378 unsigned long pid;
3379 char *dummy;
3381 if (!args)
3382 error_no_arg (_("process-id to attach"));
3384 dummy = (char *) args;
3385 pid = strtoul (args, &dummy, 0);
3386 /* Some targets don't set errno on errors, grrr! */
3387 if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3388 error (_("Illegal process-id: %s."), args);
3390 return pid;
3393 /* Substitute all occurrences of string FROM by string TO in *STRINGP. *STRINGP
3394 must come from xrealloc-compatible allocator and it may be updated. FROM
3395 needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
3396 located at the start or end of *STRINGP. */
3398 void
3399 substitute_path_component (char **stringp, const char *from, const char *to)
3401 char *string = *stringp, *s;
3402 const size_t from_len = strlen (from);
3403 const size_t to_len = strlen (to);
3405 for (s = string;;)
3407 s = strstr (s, from);
3408 if (s == NULL)
3409 break;
3411 if ((s == string || IS_DIR_SEPARATOR (s[-1])
3412 || s[-1] == DIRNAME_SEPARATOR)
3413 && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
3414 || s[from_len] == DIRNAME_SEPARATOR))
3416 char *string_new;
3418 string_new
3419 = (char *) xrealloc (string, (strlen (string) + to_len + 1));
3421 /* Relocate the current S pointer. */
3422 s = s - string + string_new;
3423 string = string_new;
3425 /* Replace from by to. */
3426 memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
3427 memcpy (s, to, to_len);
3429 s += to_len;
3431 else
3432 s++;
3435 *stringp = string;
3438 #ifdef HAVE_WAITPID
3440 #ifdef SIGALRM
3442 /* SIGALRM handler for waitpid_with_timeout. */
3444 static void
3445 sigalrm_handler (int signo)
3447 /* Nothing to do. */
3450 #endif
3452 /* Wrapper to wait for child PID to die with TIMEOUT.
3453 TIMEOUT is the time to stop waiting in seconds.
3454 If TIMEOUT is zero, pass WNOHANG to waitpid.
3455 Returns PID if it was successfully waited for, otherwise -1.
3457 Timeouts are currently implemented with alarm and SIGALRM.
3458 If the host does not support them, this waits "forever".
3459 It would be odd though for a host to have waitpid and not SIGALRM. */
3461 pid_t
3462 wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3464 pid_t waitpid_result;
3466 gdb_assert (pid > 0);
3467 gdb_assert (timeout >= 0);
3469 if (timeout > 0)
3471 #ifdef SIGALRM
3472 scoped_signal_handler<SIGALRM> alarm_restore (sigalrm_handler);
3474 alarm (timeout);
3475 #endif
3477 waitpid_result = gdb::waitpid (pid, status, 0);
3479 #ifdef SIGALRM
3480 alarm (0);
3481 #endif
3483 else
3484 waitpid_result = gdb::waitpid (pid, status, WNOHANG);
3486 if (waitpid_result == pid)
3487 return pid;
3488 else
3489 return -1;
3492 #endif /* HAVE_WAITPID */
3494 /* Provide fnmatch compatible function for matching of host files.
3495 FNM_NOESCAPE must be set in FLAGS.
3497 It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3498 HAVE_CASE_INSENSITIVE_FILE_SYSTEM. */
3501 gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3503 /* It is unclear how '\' escaping vs. directory separator should coexist. */
3504 gdb_assert ((flags & FNM_NOESCAPE) != 0);
3506 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3508 char *pattern_slash, *string_slash;
3510 /* Replace '\' by '/' in both strings. */
3512 pattern_slash = (char *) alloca (strlen (pattern) + 1);
3513 strcpy (pattern_slash, pattern);
3514 pattern = pattern_slash;
3515 for (; *pattern_slash != 0; pattern_slash++)
3516 if (IS_DIR_SEPARATOR (*pattern_slash))
3517 *pattern_slash = '/';
3519 string_slash = (char *) alloca (strlen (string) + 1);
3520 strcpy (string_slash, string);
3521 string = string_slash;
3522 for (; *string_slash != 0; string_slash++)
3523 if (IS_DIR_SEPARATOR (*string_slash))
3524 *string_slash = '/';
3526 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3528 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3529 flags |= FNM_CASEFOLD;
3530 #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3532 return fnmatch (pattern, string, flags);
3535 /* Return the number of path elements in PATH.
3536 / = 1
3537 /foo = 2
3538 /foo/ = 2
3539 foo/bar = 2
3540 foo/ = 1 */
3543 count_path_elements (const char *path)
3545 int count = 0;
3546 const char *p = path;
3548 if (HAS_DRIVE_SPEC (p))
3550 p = STRIP_DRIVE_SPEC (p);
3551 ++count;
3554 while (*p != '\0')
3556 if (IS_DIR_SEPARATOR (*p))
3557 ++count;
3558 ++p;
3561 /* Backup one if last character is /, unless it's the only one. */
3562 if (p > path + 1 && IS_DIR_SEPARATOR (p[-1]))
3563 --count;
3565 /* Add one for the file name, if present. */
3566 if (p > path && !IS_DIR_SEPARATOR (p[-1]))
3567 ++count;
3569 return count;
3572 /* Remove N leading path elements from PATH.
3573 N must be non-negative.
3574 If PATH has more than N path elements then return NULL.
3575 If PATH has exactly N path elements then return "".
3576 See count_path_elements for a description of how we do the counting. */
3578 const char *
3579 strip_leading_path_elements (const char *path, int n)
3581 int i = 0;
3582 const char *p = path;
3584 gdb_assert (n >= 0);
3586 if (n == 0)
3587 return p;
3589 if (HAS_DRIVE_SPEC (p))
3591 p = STRIP_DRIVE_SPEC (p);
3592 ++i;
3595 while (i < n)
3597 while (*p != '\0' && !IS_DIR_SEPARATOR (*p))
3598 ++p;
3599 if (*p == '\0')
3601 if (i + 1 == n)
3602 return "";
3603 return NULL;
3605 ++p;
3606 ++i;
3609 return p;
3612 /* See utils.h. */
3614 void
3615 copy_bitwise (gdb_byte *dest, ULONGEST dest_offset,
3616 const gdb_byte *source, ULONGEST source_offset,
3617 ULONGEST nbits, int bits_big_endian)
3619 unsigned int buf, avail;
3621 if (nbits == 0)
3622 return;
3624 if (bits_big_endian)
3626 /* Start from the end, then work backwards. */
3627 dest_offset += nbits - 1;
3628 dest += dest_offset / 8;
3629 dest_offset = 7 - dest_offset % 8;
3630 source_offset += nbits - 1;
3631 source += source_offset / 8;
3632 source_offset = 7 - source_offset % 8;
3634 else
3636 dest += dest_offset / 8;
3637 dest_offset %= 8;
3638 source += source_offset / 8;
3639 source_offset %= 8;
3642 /* Fill BUF with DEST_OFFSET bits from the destination and 8 -
3643 SOURCE_OFFSET bits from the source. */
3644 buf = *(bits_big_endian ? source-- : source++) >> source_offset;
3645 buf <<= dest_offset;
3646 buf |= *dest & ((1 << dest_offset) - 1);
3648 /* NBITS: bits yet to be written; AVAIL: BUF's fill level. */
3649 nbits += dest_offset;
3650 avail = dest_offset + 8 - source_offset;
3652 /* Flush 8 bits from BUF, if appropriate. */
3653 if (nbits >= 8 && avail >= 8)
3655 *(bits_big_endian ? dest-- : dest++) = buf;
3656 buf >>= 8;
3657 avail -= 8;
3658 nbits -= 8;
3661 /* Copy the middle part. */
3662 if (nbits >= 8)
3664 size_t len = nbits / 8;
3666 /* Use a faster method for byte-aligned copies. */
3667 if (avail == 0)
3669 if (bits_big_endian)
3671 dest -= len;
3672 source -= len;
3673 memcpy (dest + 1, source + 1, len);
3675 else
3677 memcpy (dest, source, len);
3678 dest += len;
3679 source += len;
3682 else
3684 while (len--)
3686 buf |= *(bits_big_endian ? source-- : source++) << avail;
3687 *(bits_big_endian ? dest-- : dest++) = buf;
3688 buf >>= 8;
3691 nbits %= 8;
3694 /* Write the last byte. */
3695 if (nbits)
3697 if (avail < nbits)
3698 buf |= *source << avail;
3700 buf &= (1 << nbits) - 1;
3701 *dest = (*dest & (~0U << nbits)) | buf;
3705 /* See utils.h. */
3707 std::string
3708 extract_single_filename_arg (const char *args)
3710 if (args == nullptr)
3711 return {};
3713 std::string filename = extract_string_maybe_quoted (&args);
3714 args = skip_spaces (args);
3715 if (*args != '\0')
3716 error (_("Junk after filename \"%s\": %s"), filename.c_str (), args);
3717 if (!filename.empty ())
3718 filename = gdb_tilde_expand (filename.c_str ());
3719 return filename;
3722 #if GDB_SELF_TEST
3723 static void
3724 test_assign_set_return_if_changed ()
3726 bool changed;
3727 int a;
3729 for (bool initial : { false, true })
3731 changed = initial;
3732 a = 1;
3733 assign_set_if_changed (a, 1, changed);
3734 SELF_CHECK (a == 1);
3735 SELF_CHECK (changed == initial);
3738 for (bool initial : { false, true })
3740 changed = initial;
3741 a = 1;
3742 assign_set_if_changed (a, 2, changed);
3743 SELF_CHECK (a == 2);
3744 SELF_CHECK (changed == true);
3747 a = 1;
3748 changed = assign_return_if_changed (a, 1);
3749 SELF_CHECK (a == 1);
3750 SELF_CHECK (changed == false);
3752 a = 1;
3753 assign_set_if_changed (a, 2, changed);
3754 SELF_CHECK (a == 2);
3755 SELF_CHECK (changed == true);
3757 #endif
3759 void _initialize_utils ();
3760 void
3761 _initialize_utils ()
3763 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
3764 Set number of characters where GDB should wrap lines of its output."), _("\
3765 Show number of characters where GDB should wrap lines of its output."), _("\
3766 This affects where GDB wraps its output to fit the screen width.\n\
3767 Setting this to \"unlimited\" or zero prevents GDB from wrapping its output."),
3768 set_width_command,
3769 show_chars_per_line,
3770 &setlist, &showlist);
3772 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
3773 Set number of lines in a page for GDB output pagination."), _("\
3774 Show number of lines in a page for GDB output pagination."), _("\
3775 This affects the number of lines after which GDB will pause\n\
3776 its output and ask you whether to continue.\n\
3777 Setting this to \"unlimited\" or zero causes GDB never pause during output."),
3778 set_height_command,
3779 show_lines_per_page,
3780 &setlist, &showlist);
3782 add_setshow_boolean_cmd ("pagination", class_support,
3783 &pagination_enabled, _("\
3784 Set state of GDB output pagination."), _("\
3785 Show state of GDB output pagination."), _("\
3786 When pagination is ON, GDB pauses at end of each screenful of\n\
3787 its output and asks you whether to continue.\n\
3788 Turning pagination off is an alternative to \"set height unlimited\"."),
3789 NULL,
3790 show_pagination_enabled,
3791 &setlist, &showlist);
3793 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
3794 &sevenbit_strings, _("\
3795 Set printing of 8-bit characters in strings as \\nnn."), _("\
3796 Show printing of 8-bit characters in strings as \\nnn."), NULL,
3797 NULL,
3798 show_sevenbit_strings,
3799 &setprintlist, &showprintlist);
3801 add_setshow_boolean_cmd ("timestamp", class_maintenance,
3802 &debug_timestamp, _("\
3803 Set timestamping of debugging messages."), _("\
3804 Show timestamping of debugging messages."), _("\
3805 When set, debugging messages will be marked with seconds and microseconds."),
3806 NULL,
3807 show_debug_timestamp,
3808 &setdebuglist, &showdebuglist);
3810 add_internal_problem_command (&internal_error_problem);
3811 add_internal_problem_command (&internal_warning_problem);
3812 add_internal_problem_command (&demangler_warning_problem);
3814 add_cmd ("screen", class_maintenance, &maintenance_info_screen,
3815 _("Show screen characteristics."), &maintenanceinfolist);
3817 #if GDB_SELF_TEST
3818 selftests::register_test ("gdb_realpath", gdb_realpath_tests);
3819 selftests::register_test ("gdb_argv_array_view", gdb_argv_as_array_view_test);
3820 selftests::register_test ("strncmp_iw_with_mode",
3821 strncmp_iw_with_mode_tests);
3822 selftests::register_test ("pager", test_pager);
3823 selftests::register_test ("assign_set_return_if_changed",
3824 test_assign_set_return_if_changed);
3825 #endif