]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/utils.c
[gdb/testsuite] Fix gdb.arch/amd64-disp-step-avx.exp on x86_64-freebsd
[thirdparty/binutils-gdb.git] / gdb / utils.c
CommitLineData
c906108c 1/* General utility routines for GDB, the GNU debugger.
1bac305b 2
d01e8234 3 Copyright (C) 1986-2025 Free Software Foundation, Inc.
c906108c 4
c5aa993b 5 This file is part of GDB.
c906108c 6
c5aa993b
JM
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
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b 10 (at your option) any later version.
c906108c 11
c5aa993b
JM
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.
c906108c 16
c5aa993b 17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c906108c 19
4e8f7a8b 20#include <ctype.h>
268a13a5 21#include "gdbsupport/gdb_wait.h"
3cfa137c 22#include "gdbsupport/scoped_signal_handler.h"
4e8f7a8b 23#include "event-top.h"
95e54da7 24#include "gdbthread.h"
202cbf1c 25#include "fnmatch.h"
cbb099e8 26#include "gdb_bfd.h"
7991dee7
JK
27#ifdef HAVE_SYS_RESOURCE_H
28#include <sys/resource.h>
29#endif /* HAVE_SYS_RESOURCE_H */
4e8f7a8b 30
6a83354a 31#ifdef TUI
a4f8f290
AB
32/* For tui_get_command_dimension and tui_disable. */
33#include "tui/tui.h"
6a83354a
AC
34#endif
35
9d271fd8
AC
36#ifdef __GO32__
37#include <pc.h>
38#endif
39
042be3a9 40#include <signal.h>
5b9707eb 41#include "cli/cli-cmds.h"
c906108c
SS
42#include "serial.h"
43#include "bfd.h"
44#include "target.h"
50f182aa 45#include "gdb-demangle.h"
c906108c
SS
46#include "expression.h"
47#include "language.h"
234b45d4 48#include "charset.h"
c906108c 49#include "annotate.h"
303c8ebd 50#include "filenames.h"
7b90c3f9 51#include "symfile.h"
bf31fd38 52#include "gdbsupport/gdb_obstack.h"
9544c605 53#include "gdbcore.h"
698ba934 54#include "top.h"
13d03262 55#include "ui.h"
7c953934 56#include "main.h"
c906108c 57
ef0f16cc 58#include "inferior.h"
ac2e2ef7 59
3b78cdbb 60#include "gdb_curses.h"
020cc13c 61
dbda9972 62#include "readline/readline.h"
c906108c 63
dcb07cfa 64#include <chrono>
75feb17d 65
390a8aca 66#include "interps.h"
d322d6d6 67#include "gdbsupport/gdb_regex.h"
268a13a5
TT
68#include "gdbsupport/job-control.h"
69#include "gdbsupport/selftest.h"
6b09f134 70#include <optional>
0662b6a7
PA
71#include "cp-support.h"
72#include <algorithm>
268a13a5 73#include "gdbsupport/pathstuff.h"
cbe56571 74#include "cli/cli-style.h"
268a13a5 75#include "gdbsupport/scope-exit.h"
0d12e84c 76#include "gdbarch.h"
2a3c1174 77#include "cli-out.h"
51e2cfa2 78#include "gdbsupport/gdb-safe-ctype.h"
91f2597b 79#include "bt-utils.h"
7904e961 80#include "gdbsupport/buildargv.h"
3cd52293 81#include "pager.h"
47ccd6b8 82#include "run-on-main-thread.h"
1217ae67 83#include "gdbsupport/gdb_tilde_expand.h"
a9791f14 84#include "gdbsupport/eintr.h"
8626589c 85
9a4105ab 86void (*deprecated_error_begin_hook) (void);
c906108c
SS
87
88/* Prototypes for local functions */
89
eb0d3137 90static void set_screen_size (void);
a14ed312 91static void set_width (void);
c906108c 92
260c0b2a
DE
93/* Time spent in prompt_for_continue in the currently executing command
94 waiting for user to respond.
95 Initialized in make_command_stats_cleanup.
96 Modified in prompt_for_continue and defaulted_query.
97 Used in report_command_stats. */
98
dcb07cfa 99static std::chrono::steady_clock::duration prompt_for_continue_wait_time;
260c0b2a 100
75feb17d
DJ
101/* A flag indicating whether to timestamp debugging messages. */
102
3c6c449e 103bool debug_timestamp = false;
75feb17d 104
491144b5
CB
105/* True means that strings with character values >0x7F should be printed
106 as octal escapes. False means just print the value (e.g. it's an
c906108c
SS
107 international character, and the terminal or window can cope.) */
108
491144b5 109bool sevenbit_strings = false;
920d2a44
AC
110static void
111show_sevenbit_strings (struct ui_file *file, int from_tty,
112 struct cmd_list_element *c, const char *value)
113{
6cb06a8c
TT
114 gdb_printf (file, _("Printing of 8-bit characters "
115 "in strings as \\nnn is %s.\n"),
116 value);
920d2a44 117}
c906108c 118
c906108c
SS
119/* String to be printed before warning messages, if any. */
120
a6bc5efb 121const char *warning_pre_print = "\n";
c906108c 122
491144b5 123bool pagination_enabled = true;
920d2a44
AC
124static void
125show_pagination_enabled (struct ui_file *file, int from_tty,
126 struct cmd_list_element *c, const char *value)
127{
6cb06a8c 128 gdb_printf (file, _("State of pagination is %s.\n"), value);
920d2a44
AC
129}
130
c906108c 131\f
49346fa7
AVK
132/* Warning hook pointer. This has to be 'static' to avoid link
133 problems with thread-locals on AIX. */
c5aa993b 134
172dc892 135static thread_local warning_hook_handler warning_hook;
49346fa7
AVK
136
137/* See utils.h. */
138
139warning_hook_handler
140get_warning_hook_handler ()
141{
142 return warning_hook;
143}
144
145/* See utils.h. */
146
147scoped_restore_warning_hook::scoped_restore_warning_hook
148 (warning_hook_handler new_handler)
6fb99666 149 : m_save (warning_hook)
49346fa7 150{
6fb99666
CW
151 warning_hook = new_handler;
152}
153
154scoped_restore_warning_hook::~scoped_restore_warning_hook ()
155{
156 warning_hook = m_save;
49346fa7 157}
8731e58e 158
f5a96129
AC
159/* Print a warning message. The first argument STRING is the warning
160 message, used as an fprintf format string, the second is the
161 va_list of arguments for that string. A warning is unfiltered (not
162 paginated) so that the user does not need to page through each
163 screen full of warnings when there are lots of them. */
c906108c
SS
164
165void
f5a96129 166vwarning (const char *string, va_list args)
c906108c 167{
49346fa7 168 if (warning_hook != nullptr)
75670e00 169 warning_hook->warn (string, args);
f5a96129
AC
170 else
171 {
6b09f134 172 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
0d2f5c07 173 if (target_supports_terminal_ours ())
c5ac1540 174 {
223ffa71
TT
175 term_state.emplace ();
176 target_terminal::ours_for_output ();
c5ac1540 177 }
a6bc5efb 178 gdb_puts (warning_pre_print, gdb_stderr);
a048980c 179 print_warning_prefix (gdb_stderr);
a6bc5efb 180 gdb_puts (_("warning: "), gdb_stderr);
19a7b8ab 181 gdb_vprintf (gdb_stderr, string, args);
6cb06a8c 182 gdb_printf (gdb_stderr, "\n");
f5a96129 183 }
c906108c
SS
184}
185
c906108c
SS
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. */
189
c25c4a8b 190void
4ce44c66
JM
191verror (const char *string, va_list args)
192{
6b1b7650 193 throw_verror (GENERIC_ERROR, string, args);
4ce44c66
JM
194}
195
2437fd32
GB
196/* Emit a message and abort. */
197
d9deb60b 198[[noreturn]] static void
2437fd32
GB
199abort_with_message (const char *msg)
200{
72542b8e 201 if (current_ui == NULL)
2437fd32
GB
202 fputs (msg, stderr);
203 else
0426ad51 204 gdb_puts (msg, gdb_stderr);
2437fd32 205
036003a6 206 abort (); /* ARI: abort */
2437fd32
GB
207}
208
7991dee7
JK
209/* Dump core trying to increase the core soft limit to hard limit first. */
210
eae7090b 211void
7991dee7
JK
212dump_core (void)
213{
214#ifdef HAVE_SETRLIMIT
206c1947 215 struct rlimit rlim = { (rlim_t) RLIM_INFINITY, (rlim_t) RLIM_INFINITY };
7991dee7
JK
216
217 setrlimit (RLIMIT_CORE, &rlim);
218#endif /* HAVE_SETRLIMIT */
219
0e6e4b59
AB
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);
224
036003a6 225 abort (); /* ARI: abort */
7991dee7
JK
226}
227
3e43a32a 228/* Check whether GDB will be able to dump core using the dump_core
eae7090b
GB
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. */
7991dee7 232
eae7090b
GB
233int
234can_dump_core (enum resource_limit_kind limit_kind)
7991dee7
JK
235{
236#ifdef HAVE_GETRLIMIT
237 struct rlimit rlim;
238
239 /* Be quiet and assume we can dump if an error is returned. */
240 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
241 return 1;
242
eae7090b 243 switch (limit_kind)
7991dee7 244 {
eae7090b
GB
245 case LIMIT_CUR:
246 if (rlim.rlim_cur == 0)
247 return 0;
d182e398 248 [[fallthrough]];
eae7090b
GB
249
250 case LIMIT_MAX:
251 if (rlim.rlim_max == 0)
252 return 0;
7991dee7
JK
253 }
254#endif /* HAVE_GETRLIMIT */
255
256 return 1;
257}
258
eae7090b
GB
259/* Print a warning that we cannot dump core. */
260
261void
262warn_cant_dump_core (const char *reason)
263{
6cb06a8c
TT
264 gdb_printf (gdb_stderr,
265 _("%s\nUnable to dump core, use `ulimit -c"
266 " unlimited' before executing GDB next time.\n"),
267 reason);
eae7090b
GB
268}
269
270/* Check whether GDB will be able to dump core using the dump_core
271 function, and print a warning if we cannot. */
272
273static int
274can_dump_core_warn (enum resource_limit_kind limit_kind,
275 const char *reason)
276{
277 int core_dump_allowed = can_dump_core (limit_kind);
278
279 if (!core_dump_allowed)
280 warn_cant_dump_core (reason);
281
282 return core_dump_allowed;
283}
284
3c16cced
PA
285/* Allow the user to configure the debugger behavior with respect to
286 what to do when an internal problem is detected. */
287
288const char internal_problem_ask[] = "ask";
289const char internal_problem_yes[] = "yes";
290const char internal_problem_no[] = "no";
40478521 291static const char *const internal_problem_modes[] =
3c16cced
PA
292{
293 internal_problem_ask,
294 internal_problem_yes,
295 internal_problem_no,
296 NULL
297};
3c16cced 298
90f4cc60
AB
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. */
c906108c 302
dec43320 303struct internal_problem
c906108c 304{
90f4cc60
AB
305 /* The name of this problem type. This must not contain white space as
306 this string is used to build command names. */
dec43320 307 const char *name;
90f4cc60
AB
308
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;
313
314 /* Reference a value from internal_problem_modes to indicate if GDB
315 should quit when it hits a problem of this type. */
3c16cced 316 const char *should_quit;
90f4cc60
AB
317
318 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_DUMP_CORE. */
319 bool user_settable_should_dump_core;
320
321 /* Like SHOULD_QUIT, but whether GDB should dump core. */
3c16cced 322 const char *should_dump_core;
91f2597b
AB
323
324 /* Like USER_SETTABLE_SHOULD_QUIT but for SHOULD_PRINT_BACKTRACE. */
325 bool user_settable_should_print_backtrace;
326
327 /* When this is true GDB will print a backtrace when a problem of this
328 type is encountered. */
329 bool should_print_backtrace;
dec43320
AC
330};
331
86d77f6a
AB
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. */
335
336static bool
337readline_initialized (struct ui *ui)
338{
339 return ui->call_readline != nullptr;
340}
341
dec43320
AC
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. */
345
a0b31db1 346static void ATTRIBUTE_PRINTF (4, 0)
dec43320 347internal_vproblem (struct internal_problem *problem,
8731e58e 348 const char *file, int line, const char *fmt, va_list ap)
dec43320 349{
dec43320 350 static int dejavu;
375fc983 351 int quit_p;
7be570e7 352 int dump_core_p;
e05550d7 353 std::string reason;
c906108c 354
dec43320 355 /* Don't allow infinite error/warning recursion. */
714b1282 356 {
02cf60c7 357 static const char msg[] = "Recursive internal problem.\n";
5d502164 358
714b1282
AC
359 switch (dejavu)
360 {
361 case 0:
362 dejavu = 1;
363 break;
364 case 1:
365 dejavu = 2;
2437fd32 366 abort_with_message (msg);
714b1282
AC
367 default:
368 dejavu = 3;
dda83cd7
SM
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. */
bf1d7d9c 374 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
dda83cd7 375 abort (); /* ARI: abort */
714b1282
AC
376 exit (1);
377 }
378 }
c906108c 379
a4f8f290
AB
380#ifdef TUI
381 tui_disable ();
382#endif
383
714b1282 384 /* Create a string containing the full error/warning message. Need
973c5759 385 to call query with this full string, as otherwise the reason
714b1282
AC
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. */
389 {
f8bfbf22 390 std::string msg = string_vprintf (fmt, ap);
e05550d7
TT
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 ());
714b1282 395 }
7be570e7 396
2437fd32 397 /* Fall back to abort_with_message if gdb_stderr is not set up. */
72542b8e 398 if (current_ui == NULL)
2437fd32 399 {
e05550d7 400 fputs (reason.c_str (), stderr);
2437fd32
GB
401 abort_with_message ("\n");
402 }
403
404 /* Try to get the message out and at the start of a new line. */
6b09f134 405 std::optional<target_terminal::scoped_restore_terminal_state> term_state;
2437fd32 406 if (target_supports_terminal_ours ())
c5ac1540 407 {
223ffa71
TT
408 term_state.emplace ();
409 target_terminal::ours_for_output ();
c5ac1540 410 }
2437fd32
GB
411 if (filtered_printing_initialized ())
412 begin_line ();
413
196a707b 414 /* Emit the message unless query will emit it below. */
2437fd32
GB
415 if (problem->should_quit != internal_problem_ask
416 || !confirm
91f2597b 417 || !filtered_printing_initialized ()
86d77f6a 418 || !readline_initialized (current_ui)
91f2597b 419 || problem->should_print_backtrace)
6cb06a8c 420 gdb_printf (gdb_stderr, "%s\n", reason.c_str ());
196a707b 421
91f2597b
AB
422 if (problem->should_print_backtrace)
423 gdb_internal_backtrace ();
424
3c16cced 425 if (problem->should_quit == internal_problem_ask)
dec43320 426 {
dec43320 427 /* Default (yes/batch case) is to quit GDB. When in batch mode
3c16cced
PA
428 this lessens the likelihood of GDB going into an infinite
429 loop. */
86d77f6a
AB
430 if (!confirm || !filtered_printing_initialized ()
431 || !readline_initialized (current_ui))
196a707b 432 quit_p = 1;
26bb68be 433 else
dda83cd7 434 quit_p = query (_("%s\nQuit this debugging session? "),
e05550d7 435 reason.c_str ());
dec43320 436 }
3c16cced
PA
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
f34652de 442 internal_error (_("bad switch"));
dec43320 443
0426ad51 444 gdb_puts (_("\nThis is a bug, please report it."), gdb_stderr);
add6c04d 445 if (REPORT_BUGS_TO[0])
8839e3f3
TT
446 gdb_printf (gdb_stderr, _(" For instructions, see:\n%ps."),
447 styled_string (file_name_style.style (),
448 REPORT_BUGS_TO));
0426ad51 449 gdb_puts ("\n\n", gdb_stderr);
add6c04d 450
3c16cced 451 if (problem->should_dump_core == internal_problem_ask)
dec43320 452 {
e05550d7 453 if (!can_dump_core_warn (LIMIT_MAX, reason.c_str ()))
7991dee7 454 dump_core_p = 0;
86d77f6a
AB
455 else if (!filtered_printing_initialized ()
456 || !readline_initialized (current_ui))
2437fd32 457 dump_core_p = 1;
7991dee7
JK
458 else
459 {
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. */
e05550d7
TT
463 dump_core_p = query (_("%s\nCreate a core file of GDB? "),
464 reason.c_str ());
7991dee7 465 }
dec43320 466 }
3c16cced 467 else if (problem->should_dump_core == internal_problem_yes)
e05550d7 468 dump_core_p = can_dump_core_warn (LIMIT_MAX, reason.c_str ());
3c16cced
PA
469 else if (problem->should_dump_core == internal_problem_no)
470 dump_core_p = 0;
471 else
f34652de 472 internal_error (_("bad switch"));
7be570e7 473
375fc983 474 if (quit_p)
7be570e7
JM
475 {
476 if (dump_core_p)
7991dee7 477 dump_core ();
375fc983
AC
478 else
479 exit (1);
7be570e7
JM
480 }
481 else
482 {
483 if (dump_core_p)
375fc983 484 {
9b265ec2 485#ifdef HAVE_WORKING_FORK
375fc983 486 if (fork () == 0)
7991dee7 487 dump_core ();
9b265ec2 488#endif
375fc983 489 }
7be570e7 490 }
96baa820
JM
491
492 dejavu = 0;
dec43320
AC
493}
494
495static struct internal_problem internal_error_problem = {
90f4cc60 496 "internal-error", true, internal_problem_ask, true, internal_problem_ask,
91f2597b 497 true, GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON
dec43320
AC
498};
499
c25c4a8b 500void
8731e58e 501internal_verror (const char *file, int line, const char *fmt, va_list ap)
dec43320
AC
502{
503 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
2c51604d 504 throw_quit (_("Command aborted."));
c906108c
SS
505}
506
dec43320 507static struct internal_problem internal_warning_problem = {
90f4cc60 508 "internal-warning", true, internal_problem_ask, true, internal_problem_ask,
91f2597b 509 true, false
dec43320
AC
510};
511
512void
8731e58e 513internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
dec43320
AC
514{
515 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
516}
517
57fcfb1b 518static struct internal_problem demangler_warning_problem = {
90f4cc60 519 "demangler-warning", true, internal_problem_ask, false, internal_problem_no,
91f2597b 520 false, false
57fcfb1b
GB
521};
522
523void
524demangler_vwarning (const char *file, int line, const char *fmt, va_list ap)
525{
526 internal_vproblem (&demangler_warning_problem, file, line, fmt, ap);
527}
528
529void
530demangler_warning (const char *file, int line, const char *string, ...)
531{
532 va_list ap;
533
534 va_start (ap, string);
535 demangler_vwarning (file, line, string, ap);
536 va_end (ap);
537}
538
3c16cced
PA
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:
545
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
550
551 Where PROBLEM-NAME is currently "internal-error" or
552 "internal-warning". */
553
554static void
555add_internal_problem_command (struct internal_problem *problem)
556{
557 struct cmd_list_element **set_cmd_list;
558 struct cmd_list_element **show_cmd_list;
3c16cced 559
8d749320
SM
560 set_cmd_list = XNEW (struct cmd_list_element *);
561 show_cmd_list = XNEW (struct cmd_list_element *);
3c16cced
PA
562 *set_cmd_list = NULL;
563 *show_cmd_list = NULL;
564
74765668
AB
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."),
8579fd13 570 problem->name).release ();
74765668
AB
571 const char *show_doc
572 = xstrprintf (_("Show what GDB does when %s is detected."),
8579fd13 573 problem->name).release ();
3c16cced 574
f54bdb6d
SM
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);
3c16cced 578
57fcfb1b
GB
579 if (problem->user_settable_should_quit)
580 {
74765668
AB
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);
57fcfb1b
GB
587 add_setshow_enum_cmd ("quit", class_maintenance,
588 internal_problem_modes,
589 &problem->should_quit,
74765668
AB
590 set_quit_doc.c_str (),
591 show_quit_doc.c_str (),
57fcfb1b
GB
592 NULL, /* help_doc */
593 NULL, /* setfunc */
594 NULL, /* showfunc */
595 set_cmd_list,
596 show_cmd_list);
57fcfb1b 597 }
1eefb858 598
57fcfb1b
GB
599 if (problem->user_settable_should_dump_core)
600 {
74765668 601 std::string set_core_doc
ada6f470
TT
602 = string_printf (_("Set whether GDB should dump core "
603 "when %s is detected."), problem->name);
74765668 604 std::string show_core_doc
ada6f470
TT
605 = string_printf (_("Show whether GDB should dump core "
606 "when %s is detected."), problem->name);
57fcfb1b
GB
607 add_setshow_enum_cmd ("corefile", class_maintenance,
608 internal_problem_modes,
609 &problem->should_dump_core,
74765668
AB
610 set_core_doc.c_str (),
611 show_core_doc.c_str (),
57fcfb1b
GB
612 NULL, /* help_doc */
613 NULL, /* setfunc */
614 NULL, /* showfunc */
615 set_cmd_list,
616 show_cmd_list);
57fcfb1b 617 }
91f2597b
AB
618
619 if (problem->user_settable_should_print_backtrace)
620 {
621 std::string set_bt_doc
ada6f470
TT
622 = string_printf (_("Set whether GDB should show backtrace "
623 "when %s is detected."), problem->name);
91f2597b 624 std::string show_bt_doc
ada6f470
TT
625 = string_printf (_("Show whether GDB should show backtrace "
626 "when %s is detected."), problem->name);
91f2597b
AB
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);
636 }
3c16cced
PA
637}
638
7c647d61
JB
639/* Same as perror_with_name except that it prints a warning instead
640 of throwing an error. */
641
642void
643perror_warning_with_name (const char *string)
644{
18e9961f
TT
645 std::string combined = perror_string (string);
646 warning (_("%s"), combined.c_str ());
7c647d61
JB
647}
648
3d38b301 649/* See utils.h. */
c906108c
SS
650
651void
3d38b301 652warning_filename_and_errno (const char *filename, int saved_errno)
c906108c 653{
3d38b301
AB
654 warning (_("%ps: %s"), styled_string (file_name_style.style (), filename),
655 safe_strerror (saved_errno));
c906108c
SS
656}
657
c906108c 658/* Called when a memory allocation fails, with the number of bytes of
581e13c1 659 memory requested in SIZE. */
c906108c 660
c25c4a8b 661void
d26e3629 662malloc_failure (long size)
c906108c
SS
663{
664 if (size > 0)
665 {
f34652de 666 internal_error (_("virtual memory exhausted: can't allocate %ld bytes."),
8731e58e 667 size);
c906108c
SS
668 }
669 else
670 {
f34652de 671 internal_error (_("virtual memory exhausted."));
c906108c
SS
672 }
673}
674
c1cd3163
TT
675/* See common/errors.h. */
676
677void
678flush_streams ()
679{
680 gdb_stdout->flush ();
681 gdb_stderr->flush ();
682}
683
c906108c
SS
684/* My replacement for the read system call.
685 Used like `read' but keeps going if `read' returns too soon. */
686
687int
fba45db2 688myread (int desc, char *addr, int len)
c906108c 689{
52f0bd74 690 int val;
c906108c
SS
691 int orglen = len;
692
693 while (len > 0)
694 {
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;
702 }
703 return orglen;
704}
d26e3629 705
c906108c 706\f
c5aa993b 707
223ffa71
TT
708/* An RAII class that sets up to handle input and then tears down
709 during destruction. */
3eb7562a 710
223ffa71 711class scoped_input_handler
3eb7562a 712{
223ffa71 713public:
3eb7562a 714
223ffa71 715 scoped_input_handler ()
c2f97536 716 : m_quit_handler (&quit_handler, default_quit_handler),
223ffa71
TT
717 m_ui (NULL)
718 {
719 target_terminal::ours ();
8f7f9b3a 720 current_ui->register_file_handler ();
223ffa71
TT
721 if (current_ui->prompt_state == PROMPT_BLOCKED)
722 m_ui = current_ui;
723 }
3eb7562a 724
223ffa71
TT
725 ~scoped_input_handler ()
726 {
727 if (m_ui != NULL)
8f7f9b3a 728 m_ui->unregister_file_handler ();
223ffa71 729 }
3eb7562a 730
223ffa71 731 DISABLE_COPY_AND_ASSIGN (scoped_input_handler);
3eb7562a 732
223ffa71 733private:
3eb7562a 734
223ffa71
TT
735 /* Save and restore the terminal state. */
736 target_terminal::scoped_restore_terminal_state m_term_state;
3eb7562a 737
223ffa71 738 /* Save and restore the quit handler. */
c2f97536 739 scoped_restore_tmpl<quit_handler_ftype *> m_quit_handler;
223ffa71
TT
740
741 /* The saved UI, if non-NULL. */
742 struct ui *m_ui;
743};
3eb7562a 744
db1ff28b
JK
745\f
746
981c7f5a 747/* This function supports the query, nquery, and yquery functions.
cbdeadca 748 Ask user a y-or-n question and return 0 if answer is no, 1 if
981c7f5a
DJ
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.
cbdeadca
JJ
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. */
756
a0b31db1 757static int ATTRIBUTE_PRINTF (1, 0)
cbdeadca
JJ
758defaulted_query (const char *ctlstr, const char defchar, va_list args)
759{
cbdeadca
JJ
760 int retval;
761 int def_value;
762 char def_answer, not_def_answer;
a121b7c1 763 const char *y_string, *n_string;
cbdeadca
JJ
764
765 /* Set up according to which answer is the default. */
981c7f5a
DJ
766 if (defchar == '\0')
767 {
768 def_value = 1;
769 def_answer = 'Y';
770 not_def_answer = 'N';
771 y_string = "y";
772 n_string = "n";
773 }
774 else if (defchar == 'y')
cbdeadca
JJ
775 {
776 def_value = 1;
777 def_answer = 'Y';
778 not_def_answer = 'N';
779 y_string = "[y]";
780 n_string = "n";
781 }
782 else
783 {
784 def_value = 0;
785 def_answer = 'N';
786 not_def_answer = 'Y';
787 y_string = "y";
788 n_string = "[n]";
789 }
790
981c7f5a 791 /* Automatically answer the default value if the user did not want
a502cf95 792 prompts or the command was issued with the server prefix. */
e360902b 793 if (!confirm || server_command)
981c7f5a
DJ
794 return def_value;
795
796 /* If input isn't coming from the user directly, just say what
7a01c6e0 797 question we're asking, and then answer the default automatically. This
981c7f5a
DJ
798 way, important error messages don't get lost when talking to GDB
799 over a pipe. */
268a799a 800 if (current_ui->instream != current_ui->stdin_stream
efd3baf0 801 || !current_ui->input_interactive_p ()
26a06916
SM
802 /* Restrict queries to the main UI. */
803 || current_ui != main_ui)
981c7f5a 804 {
223ffa71
TT
805 target_terminal::scoped_restore_terminal_state term_state;
806 target_terminal::ours_for_output ();
1285ce86 807 gdb_stdout->wrap_here (0);
19a7b8ab 808 gdb_vprintf (gdb_stdout, ctlstr, args);
981c7f5a 809
6cb06a8c
TT
810 gdb_printf (_("(%s or %s) [answered %c; "
811 "input not from terminal]\n"),
812 y_string, n_string, def_answer);
981c7f5a
DJ
813
814 return def_value;
815 }
816
9a4105ab 817 if (deprecated_query_hook)
cbdeadca 818 {
223ffa71
TT
819 target_terminal::scoped_restore_terminal_state term_state;
820 return deprecated_query_hook (ctlstr, args);
651ce16a 821 }
80dbc9fd 822
981c7f5a 823 /* Format the question outside of the loop, to avoid reusing args. */
887ae0cf
TT
824 string_file tem (gdb_stdout->can_emit_style_escape ());
825 gdb_vprintf (&tem, ctlstr, args);
826 std::string question = tem.release ();
e05550d7
TT
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" : "");
981c7f5a 832
dcb07cfa
PA
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 ();
260c0b2a 837
223ffa71 838 scoped_input_handler prepare_input;
651ce16a 839
cbdeadca
JJ
840 while (1)
841 {
588dcc3e 842 char *response, answer;
cbdeadca 843
cbdeadca 844 gdb_flush (gdb_stdout);
e05550d7 845 response = gdb_readline_wrapper (prompt.c_str ());
cbdeadca 846
588dcc3e 847 if (response == NULL) /* C-d */
cbdeadca 848 {
6cb06a8c 849 gdb_printf ("EOF [assumed %c]\n", def_answer);
cbdeadca
JJ
850 retval = def_value;
851 break;
852 }
588dcc3e
PP
853
854 answer = response[0];
855 xfree (response);
cbdeadca
JJ
856
857 if (answer >= 'a')
858 answer -= 040;
859 /* Check answer. For the non-default, the user must specify
dda83cd7 860 the non-default explicitly. */
cbdeadca
JJ
861 if (answer == not_def_answer)
862 {
863 retval = !def_value;
864 break;
865 }
981c7f5a 866 /* Otherwise, if a default was specified, the user may either
dda83cd7
SM
867 specify the required input or have it default by entering
868 nothing. */
981c7f5a 869 if (answer == def_answer
588dcc3e 870 || (defchar != '\0' && answer == '\0'))
cbdeadca
JJ
871 {
872 retval = def_value;
873 break;
874 }
875 /* Invalid entries are not defaulted and require another selection. */
6cb06a8c
TT
876 gdb_printf (_("Please answer %s or %s.\n"),
877 y_string, n_string);
cbdeadca
JJ
878 }
879
260c0b2a 880 /* Add time spend in this routine to prompt_for_continue_wait_time. */
dcb07cfa 881 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
260c0b2a 882
cbdeadca 883 if (annotation_level > 1)
6cb06a8c 884 gdb_printf (("\n\032\032post-query\n"));
cbdeadca
JJ
885 return retval;
886}
887\f
888
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. */
894
895int
896nquery (const char *ctlstr, ...)
897{
898 va_list args;
899500d6 899 int ret;
cbdeadca
JJ
900
901 va_start (args, ctlstr);
899500d6 902 ret = defaulted_query (ctlstr, 'n', args);
cbdeadca 903 va_end (args);
899500d6 904 return ret;
cbdeadca
JJ
905}
906
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. */
912
913int
914yquery (const char *ctlstr, ...)
915{
916 va_list args;
899500d6 917 int ret;
cbdeadca
JJ
918
919 va_start (args, ctlstr);
899500d6 920 ret = defaulted_query (ctlstr, 'y', args);
cbdeadca 921 va_end (args);
899500d6 922 return ret;
cbdeadca
JJ
923}
924
981c7f5a
DJ
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. */
929
930int
931query (const char *ctlstr, ...)
932{
933 va_list args;
899500d6 934 int ret;
981c7f5a
DJ
935
936 va_start (args, ctlstr);
899500d6 937 ret = defaulted_query (ctlstr, '\0', args);
981c7f5a 938 va_end (args);
899500d6 939 return ret;
981c7f5a
DJ
940}
941
6c7a06a3
TT
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. */
946
947static int
f870a310 948host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
234b45d4 949{
6c7a06a3 950 char the_char = c;
6c7a06a3 951 int result = 0;
234b45d4 952
8268c778 953 auto_obstack host_data;
234b45d4 954
f870a310 955 convert_between_encodings (target_charset (gdbarch), host_charset (),
ac91cd70
PA
956 (gdb_byte *) &the_char, 1, 1,
957 &host_data, translit_none);
6c7a06a3
TT
958
959 if (obstack_object_size (&host_data) == 1)
960 {
961 result = 1;
962 *target_c = *(char *) obstack_base (&host_data);
963 }
964
6c7a06a3 965 return result;
234b45d4
KB
966}
967
c906108c
SS
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.
973
974 A negative value means the sequence \ newline was seen,
975 which is supposed to be equivalent to nothing at all.
976
977 If \ is followed by a null character, we return a negative
978 value and leave the string pointer pointing at the null character.
979
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. */
982
983int
d7561cbb 984parse_escape (struct gdbarch *gdbarch, const char **string_ptr)
c906108c 985{
581e13c1 986 int target_char = -2; /* Initialize to avoid GCC warnings. */
52f0bd74 987 int c = *(*string_ptr)++;
e0627e85 988
6c7a06a3
TT
989 switch (c)
990 {
8731e58e
AC
991 case '\n':
992 return -2;
993 case 0:
994 (*string_ptr)--;
995 return 0;
8731e58e
AC
996
997 case '0':
998 case '1':
999 case '2':
1000 case '3':
1001 case '4':
1002 case '5':
1003 case '6':
1004 case '7':
1005 {
2b531492 1006 int i = fromhex (c);
aa1ee363 1007 int count = 0;
8731e58e
AC
1008 while (++count < 3)
1009 {
5cb316ef 1010 c = (**string_ptr);
51e2cfa2 1011 if (ISDIGIT (c) && c != '8' && c != '9')
8731e58e 1012 {
5cb316ef 1013 (*string_ptr)++;
8731e58e 1014 i *= 8;
2b531492 1015 i += fromhex (c);
8731e58e
AC
1016 }
1017 else
1018 {
8731e58e
AC
1019 break;
1020 }
1021 }
1022 return i;
1023 }
6c7a06a3
TT
1024
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;
1046
1047 default:
1048 break;
1049 }
1050
f870a310 1051 if (!host_char_to_target (gdbarch, c, &target_char))
3351ea09
JB
1052 error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1053 " which has no equivalent\nin the `%s' character set."),
905b671b 1054 c, c, target_charset (gdbarch));
6c7a06a3 1055 return target_char;
c906108c
SS
1056}
1057\f
c5aa993b 1058
c906108c
SS
1059/* Number of lines per page or UINT_MAX if paging is disabled. */
1060static unsigned int lines_per_page;
920d2a44
AC
1061static void
1062show_lines_per_page (struct ui_file *file, int from_tty,
1063 struct cmd_list_element *c, const char *value)
1064{
6cb06a8c
TT
1065 gdb_printf (file,
1066 _("Number of lines gdb thinks are in a page is %s.\n"),
1067 value);
920d2a44 1068}
eb0d3137 1069
cbfbd72a 1070/* Number of chars per line or UINT_MAX if line folding is disabled. */
c906108c 1071static unsigned int chars_per_line;
920d2a44
AC
1072static void
1073show_chars_per_line (struct ui_file *file, int from_tty,
1074 struct cmd_list_element *c, const char *value)
1075{
6cb06a8c
TT
1076 gdb_printf (file,
1077 _("Number of characters gdb thinks "
1078 "are in a line is %s.\n"),
1079 value);
920d2a44 1080}
eb0d3137 1081
c906108c
SS
1082/* Current count of lines printed on this page, chars on this line. */
1083static unsigned int lines_printed, chars_printed;
1084
eb6af809
TT
1085/* True if pagination is disabled for just one command. */
1086
1087static bool pagination_disabled_for_command;
1088
c906108c
SS
1089/* Buffer and start column of buffered text, for doing smarter word-
1090 wrapping. When someone calls wrap_here(), we start buffering output
0426ad51 1091 that comes through gdb_puts(). If we see a newline, we just
c906108c
SS
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. */
1096
c5603d50 1097static bool filter_initialized = false;
c906108c 1098
c906108c 1099\f
c5aa993b 1100
deb1ba4e
TV
1101/* See utils.h. */
1102
1103int readline_hidden_cols = 0;
1104
26c4b26f 1105/* Initialize the number of lines per page and chars per line. */
eb0d3137 1106
c906108c 1107void
fba45db2 1108init_page_info (void)
c906108c 1109{
5da1313b
JK
1110 if (batch_flag)
1111 {
1112 lines_per_page = UINT_MAX;
1113 chars_per_line = UINT_MAX;
1114 }
1115 else
c906108c 1116#if defined(TUI)
5ecb1806 1117 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
c906108c
SS
1118#endif
1119 {
eb0d3137 1120 int rows, cols;
c906108c 1121
ec145965
EZ
1122#if defined(__GO32__)
1123 rows = ScreenRows ();
1124 cols = ScreenCols ();
1125 lines_per_page = rows;
1126 chars_per_line = cols;
1127#else
eb0d3137
MK
1128 /* Make sure Readline has initialized its terminal settings. */
1129 rl_reset_terminal (NULL);
c906108c 1130
eb0d3137
MK
1131 /* Get the screen size from Readline. */
1132 rl_get_screen_size (&rows, &cols);
deb1ba4e
TV
1133
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).
14e61dbb
TV
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);
deb1ba4e 1152
eb0d3137 1153 lines_per_page = rows;
f0f6df0a 1154 chars_per_line = cols + readline_hidden_cols;
c906108c 1155
1a66331e 1156 /* Readline should have fetched the termcap entry for us.
dda83cd7
SM
1157 Only try to use tgetnum function if rl_get_screen_size
1158 did not return a useful value. */
a121b7c1 1159 if (((rows <= 0) && (tgetnum ((char *) "li") < 0))
e681cf3f
EZ
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"))
eb0d3137 1163 {
1a66331e 1164 /* The number of lines per page is not mentioned in the terminal
30baf67b 1165 description or EMACS environment variable is set. This probably
1a66331e 1166 means that paging is not useful, so disable paging. */
eb0d3137
MK
1167 lines_per_page = UINT_MAX;
1168 }
c906108c 1169
c906108c 1170 /* If the output is not a terminal, don't paginate it. */
da5bd37e 1171 if (!gdb_stdout->isatty ())
c5aa993b 1172 lines_per_page = UINT_MAX;
eb0d3137 1173#endif
ec145965 1174 }
eb0d3137 1175
24b73f8e
PP
1176 /* We handle SIGWINCH ourselves. */
1177 rl_catch_sigwinch = 0;
1178
eb0d3137 1179 set_screen_size ();
c5aa993b 1180 set_width ();
c906108c
SS
1181}
1182
2437fd32
GB
1183/* Return nonzero if filtered printing is initialized. */
1184int
1185filtered_printing_initialized (void)
1186{
c5603d50 1187 return filter_initialized;
2437fd32
GB
1188}
1189
b95de2b7
TT
1190set_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)
5da1313b 1194{
b95de2b7
TT
1195 batch_flag = 1;
1196 init_page_info ();
5da1313b
JK
1197}
1198
b95de2b7 1199set_batch_flag_and_restore_page_info::~set_batch_flag_and_restore_page_info ()
5da1313b 1200{
b95de2b7
TT
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;
5da1313b 1204
b95de2b7
TT
1205 set_screen_size ();
1206 set_width ();
5da1313b
JK
1207}
1208
f1531d04
TV
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. */
1215
1216static const int sqrt_int_max = INT_MAX >> (sizeof (int) * 8 / 2);
1217
eb0d3137
MK
1218/* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1219
1220static void
1221set_screen_size (void)
1222{
1223 int rows = lines_per_page;
1224 int cols = chars_per_line;
1225
23031e31
SJ
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:
eb0d3137 1229
23031e31 1230 - the user specified "unlimited", which maps to UINT_MAX, or
85102364 1231 - the user specified some number between INT_MAX and UINT_MAX.
23031e31
SJ
1232
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. */
1236
23031e31 1237 if (rows <= 0 || rows > sqrt_int_max)
8ed25214
PA
1238 {
1239 rows = sqrt_int_max;
1240 lines_per_page = UINT_MAX;
1241 }
23031e31
SJ
1242
1243 if (cols <= 0 || cols > sqrt_int_max)
8ed25214
PA
1244 {
1245 cols = sqrt_int_max;
1246 chars_per_line = UINT_MAX;
1247 }
eb0d3137
MK
1248
1249 /* Update Readline's idea of the terminal size. */
1250 rl_set_screen_size (rows, cols);
1251}
1252
c5603d50 1253/* Reinitialize WRAP_BUFFER. */
eb0d3137 1254
c906108c 1255static void
fba45db2 1256set_width (void)
c906108c
SS
1257{
1258 if (chars_per_line == 0)
c5aa993b 1259 init_page_info ();
c906108c 1260
c5603d50 1261 filter_initialized = true;
c906108c
SS
1262}
1263
c5aa993b 1264static void
eb4c3f4a 1265set_width_command (const char *args, int from_tty, struct cmd_list_element *c)
c906108c 1266{
eb0d3137 1267 set_screen_size ();
c906108c
SS
1268 set_width ();
1269}
1270
eb0d3137 1271static void
eb4c3f4a 1272set_height_command (const char *args, int from_tty, struct cmd_list_element *c)
eb0d3137
MK
1273{
1274 set_screen_size ();
1275}
1276
d6e5e7f7
PP
1277/* See utils.h. */
1278
1279void
1280set_screen_width_and_height (int width, int height)
1281{
1282 lines_per_page = height;
1283 chars_per_line = width;
1284
1285 set_screen_size ();
1286 set_width ();
1287}
1288
7ba8082f
TV
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. */
1295extern "C" char *UP;
1296
f1531d04
TV
1297/* Implement "maint info screen". */
1298
1299static void
1300maintenance_info_screen (const char *args, int from_tty)
1301{
1302 int rows, cols;
1303 rl_get_screen_size (&rows, &cols);
1304
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)" : "");
1310
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 : "")));
1320
e5cbbbf7 1321#ifdef HAVE_LIBCURSES
f1531d04
TV
1322 gdb_printf (gdb_stdout,
1323 _("Number of characters curses thinks "
1324 "are in a line is %d.\n"),
1325 COLS);
e5cbbbf7 1326#endif
f1531d04
TV
1327
1328 gdb_printf (gdb_stdout,
1329 _("Number of characters environment thinks "
1330 "are in a line is %s (COLUMNS).\n"),
1331 getenv ("COLUMNS"));
1332
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)" : "");
1337
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)" : "");
1343
e5cbbbf7 1344#ifdef HAVE_LIBCURSES
f1531d04
TV
1345 gdb_printf (gdb_stdout,
1346 _("Number of lines curses thinks "
1347 "are in a page is %d.\n"),
1348 LINES);
e5cbbbf7 1349#endif
f1531d04
TV
1350
1351 gdb_printf (gdb_stdout,
1352 _("Number of lines environment thinks "
1353 "are in a page is %s (LINES).\n"),
1354 getenv ("LINES"));
7ba8082f
TV
1355
1356 bool have_up = UP != nullptr && *UP != '\0';
1357
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);
1364
1365 const char *mode = nullptr;
1366 const char *reason = nullptr;
1367 if (batch_flag)
1368 {
1369 mode = "unsupported";
1370 reason = "gdb batch mode";
1371 }
1372 else if (!have_up)
1373 {
1374 mode = "unsupported";
1375 reason = "terminal is not Cursor Up capable";
1376 }
1377 else if (force_horizontal_scroll_mode)
1378 {
1379 mode = "disabled";
1380 reason = "horizontal-scroll-mode";
1381 }
1382 else if (readline_hidden_cols)
1383 {
1384 mode = "readline";
1385 reason = "terminal is not auto wrap capable, last column reserved";
1386 }
1387 else
1388 {
1389 mode = "terminal";
1390 reason = "terminal is auto wrap capable";
1391 }
1392
1393 gdb_printf (gdb_stdout, _("Readline wrapping mode: %s (%s).\n"), mode,
1394 reason);
f1531d04
TV
1395}
1396
3cd52293
TT
1397void
1398pager_file::emit_style_escape (const ui_file_style &style)
cbe56571 1399{
3cd52293 1400 if (can_emit_style_escape () && style != m_applied_style)
e7b43072 1401 {
3cd52293
TT
1402 m_applied_style = style;
1403 if (m_paging)
e7b7270a
AB
1404 {
1405 /* Previous style changes will have been sent to m_stream via
1406 escape sequences encoded in the m_wrap_buffer. As a result,
1407 the m_stream->m_applied_style will not have been updated.
1408
1409 If we now use m_stream->emit_style_escape, then the required
1410 style might not actually be emitted as the requested style
1411 might happen to match the out of date value in
1412 m_stream->m_applied_style.
1413
1414 Instead, send the style change directly using m_stream->puts.
1415
1416 However, we track what style is currently applied to the
1417 underlying stream in m_stream_style, this is updated whenever
1418 m_wrap_buffer is flushed to the underlying stream. And so, if
1419 the style we are applying matches what we know is currently
1420 applied to the underlying stream, then we can skip sending
1421 this style to the stream. */
12588184 1422 this->set_stream_style (m_applied_style);
e7b7270a 1423 }
e7b43072 1424 else
3cd52293 1425 m_wrap_buffer.append (style.to_ansi ());
e7b43072 1426 }
cbe56571
TT
1427}
1428
c906108c 1429/* Wait, so the user can read what's on the screen. Prompt the user
720d2e96
PA
1430 to continue by pressing RETURN. 'q' is also provided because
1431 telling users what to do in the prompt is more user-friendly than
1432 expecting them to think of Ctrl-C/SIGINT. */
c906108c 1433
3cd52293
TT
1434void
1435pager_file::prompt_for_continue ()
c906108c 1436{
c906108c 1437 char cont_prompt[120];
260c0b2a
DE
1438 /* Used to add duration we waited for user to respond to
1439 prompt_for_continue_wait_time. */
dcb07cfa
PA
1440 using namespace std::chrono;
1441 steady_clock::time_point prompt_started = steady_clock::now ();
eb6af809 1442 bool disable_pagination = pagination_disabled_for_command;
c906108c 1443
3cd52293
TT
1444 scoped_restore save_paging = make_scoped_restore (&m_paging, true);
1445
e7b7270a
AB
1446 /* Clear the current styling on ourselves and the managed stream. */
1447 this->emit_style_escape (ui_file_style ());
cbe56571 1448
c906108c 1449 if (annotation_level > 1)
3cd52293 1450 m_stream->puts (("\n\032\032pre-prompt-for-continue\n"));
c906108c
SS
1451
1452 strcpy (cont_prompt,
eb6af809
TT
1453 "--Type <RET> for more, q to quit, "
1454 "c to continue without paging--");
c906108c
SS
1455 if (annotation_level > 1)
1456 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1457
720d2e96
PA
1458 /* We must do this *before* we call gdb_readline_wrapper, else it
1459 will eventually call us -- thinking that we're trying to print
1460 beyond the end of the screen. */
c906108c
SS
1461 reinitialize_more_filter ();
1462
223ffa71 1463 scoped_input_handler prepare_input;
82584158 1464
720d2e96
PA
1465 /* Call gdb_readline_wrapper, not readline, in order to keep an
1466 event loop running. */
5aa89276 1467 gdb::unique_xmalloc_ptr<char> ignore (gdb_readline_wrapper (cont_prompt));
c906108c 1468
260c0b2a 1469 /* Add time spend in this routine to prompt_for_continue_wait_time. */
dcb07cfa 1470 prompt_for_continue_wait_time += steady_clock::now () - prompt_started;
260c0b2a 1471
c906108c 1472 if (annotation_level > 1)
3cd52293 1473 m_stream->puts (("\n\032\032post-prompt-for-continue\n"));
c906108c 1474
80dbc9fd 1475 if (ignore != NULL)
c906108c 1476 {
5aa89276 1477 char *p = ignore.get ();
5d502164 1478
c906108c
SS
1479 while (*p == ' ' || *p == '\t')
1480 ++p;
1481 if (p[0] == 'q')
1690b616
SL
1482 /* Do not call quit here; there is no possibility of SIGINT. */
1483 throw_quit ("Quit");
eb6af809
TT
1484 if (p[0] == 'c')
1485 disable_pagination = true;
c906108c 1486 }
c906108c
SS
1487
1488 /* Now we have to do this again, so that GDB will know that it doesn't
1489 need to save the ---Type <return>--- line at the top of the screen. */
1490 reinitialize_more_filter ();
eb6af809 1491 pagination_disabled_for_command = disable_pagination;
c906108c 1492
581e13c1 1493 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
c906108c
SS
1494}
1495
26c4b26f 1496/* Initialize timer to keep track of how long we waited for the user. */
bd712aed
DE
1497
1498void
1499reset_prompt_for_continue_wait_time (void)
1500{
dcb07cfa 1501 using namespace std::chrono;
bd712aed 1502
dcb07cfa 1503 prompt_for_continue_wait_time = steady_clock::duration::zero ();
bd712aed
DE
1504}
1505
1506/* Fetch the cumulative time spent in prompt_for_continue. */
1507
dcb07cfa
PA
1508std::chrono::steady_clock::duration
1509get_prompt_for_continue_wait_time ()
bd712aed
DE
1510{
1511 return prompt_for_continue_wait_time;
1512}
1513
c906108c
SS
1514/* Reinitialize filter; ie. tell it to reset to original values. */
1515
1516void
fba45db2 1517reinitialize_more_filter (void)
c906108c
SS
1518{
1519 lines_printed = 0;
1520 chars_printed = 0;
eb6af809 1521 pagination_disabled_for_command = false;
c906108c
SS
1522}
1523
3cd52293
TT
1524void
1525pager_file::flush_wrap_buffer ()
c5603d50 1526{
3cd52293 1527 if (!m_paging && !m_wrap_buffer.empty ())
c5603d50 1528 {
3cd52293 1529 m_stream->puts (m_wrap_buffer.c_str ());
e7b7270a 1530 m_stream_style = m_applied_style;
3cd52293 1531 m_wrap_buffer.clear ();
c5603d50
TT
1532 }
1533}
1534
3cd52293
TT
1535void
1536pager_file::flush ()
1537{
1538 flush_wrap_buffer ();
1539 m_stream->flush ();
1540}
1541
faa17681
IB
1542/* See utils.h. */
1543
1544void
1545gdb_flush (struct ui_file *stream)
1546{
da5bd37e 1547 stream->flush ();
faa17681
IB
1548}
1549
2f228731
TT
1550/* See utils.h. */
1551
1552int
1553get_chars_per_line ()
1554{
1555 return chars_per_line;
1556}
1557
27d326da 1558/* See ui-file.h. */
c906108c
SS
1559
1560void
3cd52293 1561pager_file::wrap_here (int indent)
c906108c 1562{
581e13c1 1563 /* This should have been allocated, but be paranoid anyway. */
e2ff18a0 1564 gdb_assert (filter_initialized);
c906108c 1565
3cd52293 1566 flush_wrap_buffer ();
3e43a32a 1567 if (chars_per_line == UINT_MAX) /* No line overflow checking. */
c906108c 1568 {
3cd52293 1569 m_wrap_column = 0;
c906108c
SS
1570 }
1571 else if (chars_printed >= chars_per_line)
1572 {
3cd52293 1573 this->puts ("\n");
6c92c339 1574 if (indent != 0)
3cd52293
TT
1575 this->puts (n_spaces (indent));
1576 m_wrap_column = 0;
c906108c
SS
1577 }
1578 else
1579 {
3cd52293
TT
1580 m_wrap_column = chars_printed;
1581 m_wrap_indent = indent;
1582 m_wrap_style = m_applied_style;
c906108c
SS
1583 }
1584}
1585
9fbf7f08
TT
1586/* Print input string to gdb_stdout arranging strings in columns of n
1587 chars. String can be right or left justified in the column. Never
1588 prints trailing spaces. String should never be longer than width.
1589 FIXME: this could be useful for the EXAMINE command, which
1590 currently doesn't tabulate very well. */
4a351cef
AF
1591
1592void
9fbf7f08 1593puts_tabular (char *string, int width, int right)
4a351cef
AF
1594{
1595 int spaces = 0;
1596 int stringlen;
1597 char *spacebuf;
1598
1599 gdb_assert (chars_per_line > 0);
1600 if (chars_per_line == UINT_MAX)
1601 {
0426ad51
TT
1602 gdb_puts (string);
1603 gdb_puts ("\n");
4a351cef
AF
1604 return;
1605 }
1606
1607 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
0426ad51 1608 gdb_puts ("\n");
4a351cef
AF
1609
1610 if (width >= chars_per_line)
1611 width = chars_per_line - 1;
1612
1613 stringlen = strlen (string);
1614
1615 if (chars_printed > 0)
1616 spaces = width - (chars_printed - 1) % width - 1;
1617 if (right)
1618 spaces += width - stringlen;
1619
224c3ddb 1620 spacebuf = (char *) alloca (spaces + 1);
4a351cef
AF
1621 spacebuf[spaces] = '\0';
1622 while (spaces--)
1623 spacebuf[spaces] = ' ';
1624
0426ad51
TT
1625 gdb_puts (spacebuf);
1626 gdb_puts (string);
4a351cef
AF
1627}
1628
1629
c906108c 1630/* Ensure that whatever gets printed next, using the filtered output
581e13c1 1631 commands, starts at the beginning of the line. I.e. if there is
c906108c 1632 any pending output for the current line, flush it and start a new
581e13c1 1633 line. Otherwise do nothing. */
c906108c
SS
1634
1635void
fba45db2 1636begin_line (void)
c906108c
SS
1637{
1638 if (chars_printed > 0)
1639 {
0426ad51 1640 gdb_puts ("\n");
c906108c
SS
1641 }
1642}
1643
3cd52293
TT
1644void
1645pager_file::puts (const char *linebuffer)
c906108c 1646{
6594ca4a 1647 gdb_assert (linebuffer != nullptr);
c906108c 1648
1f0f8b5d
TT
1649 /* Don't do any filtering or wrapping if both are disabled. */
1650 if (batch_flag
390a8aca 1651 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
58dadb1b 1652 || top_level_interpreter () == NULL
29f94340 1653 || top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
c906108c 1654 {
3cd52293
TT
1655 flush_wrap_buffer ();
1656 m_stream->puts (linebuffer);
c906108c
SS
1657 return;
1658 }
1659
a0087920
TT
1660 auto buffer_clearer
1661 = make_scope_exit ([&] ()
1662 {
3cd52293
TT
1663 m_wrap_buffer.clear ();
1664 m_wrap_column = 0;
1665 m_wrap_indent = 0;
a0087920
TT
1666 });
1667
111d1981
TT
1668 /* If the user does "set height 1" then the pager will exhibit weird
1669 behavior. This is pathological, though, so don't allow it. */
1670 const unsigned int lines_allowed = (lines_per_page > 1
1671 ? lines_per_page - 1
1672 : 1);
1673
c906108c
SS
1674 /* Go through and output each character. Show line extension
1675 when this is necessary; prompt user for new page when this is
1676 necessary. */
c5aa993b 1677
9f5f1eb9 1678 while (*linebuffer != '\0')
c906108c 1679 {
eb6af809
TT
1680 /* Possible new page. Note that PAGINATION_DISABLED_FOR_COMMAND
1681 might be set during this loop, so we must continue to check
1682 it here. */
1f0f8b5d
TT
1683 if (pagination_enabled
1684 && !pagination_disabled_for_command
111d1981 1685 && lines_printed >= lines_allowed)
c906108c
SS
1686 prompt_for_continue ();
1687
9f5f1eb9 1688 while (*linebuffer != '\0' && *linebuffer != '\n')
c906108c 1689 {
a0087920
TT
1690 int skip_bytes;
1691
c906108c 1692 /* Print a single line. */
9f5f1eb9 1693 if (*linebuffer == '\t')
c906108c 1694 {
3cd52293 1695 m_wrap_buffer.push_back ('\t');
c906108c 1696 /* Shifting right by 3 produces the number of tab stops
dda83cd7
SM
1697 we have already passed, and then adding one and
1698 shifting left 3 advances to the next tab stop. */
c906108c 1699 chars_printed = ((chars_printed >> 3) + 1) << 3;
9f5f1eb9 1700 linebuffer++;
c906108c 1701 }
9f5f1eb9
SM
1702 else if (*linebuffer == '\033'
1703 && skip_ansi_escape (linebuffer, &skip_bytes))
a0087920 1704 {
9f5f1eb9 1705 m_wrap_buffer.append (linebuffer, skip_bytes);
a0087920
TT
1706 /* Note that we don't consider this a character, so we
1707 don't increment chars_printed here. */
9f5f1eb9 1708 linebuffer += skip_bytes;
a0087920 1709 }
9f5f1eb9 1710 else if (*linebuffer == '\r')
2f228731 1711 {
9f5f1eb9 1712 m_wrap_buffer.push_back (*linebuffer);
2f228731 1713 chars_printed = 0;
9f5f1eb9 1714 linebuffer++;
2f228731 1715 }
c906108c
SS
1716 else
1717 {
9f5f1eb9 1718 m_wrap_buffer.push_back (*linebuffer);
c906108c 1719 chars_printed++;
9f5f1eb9 1720 linebuffer++;
c906108c 1721 }
c5aa993b 1722
c906108c
SS
1723 if (chars_printed >= chars_per_line)
1724 {
1725 unsigned int save_chars = chars_printed;
1726
99f20f08
TT
1727 /* If we change the style, below, we'll want to reset it
1728 before continuing to print. If there is no wrap
1729 column, then we'll only reset the style if the pager
1730 prompt is given; and to avoid emitting style
1731 sequences in the middle of a run of text, we track
1732 this as well. */
3cd52293 1733 ui_file_style save_style = m_applied_style;
99f20f08
TT
1734 bool did_paginate = false;
1735
c906108c
SS
1736 chars_printed = 0;
1737 lines_printed++;
3cd52293 1738 if (m_wrap_column)
cbe56571 1739 {
e7b43072
AB
1740 /* We are about to insert a newline at an historic
1741 location in the WRAP_BUFFER. Before we do we want to
1742 restore the default style. To know if we actually
1743 need to insert an escape sequence we must restore the
1744 current applied style to how it was at the WRAP_COLUMN
1745 location. */
3cd52293 1746 m_applied_style = m_wrap_style;
12588184
AB
1747 this->set_stream_style (ui_file_style ());
1748
a0087920
TT
1749 /* If we aren't actually wrapping, don't output
1750 newline -- if chars_per_line is right, we
1751 probably just overflowed anyway; if it's wrong,
1752 let us keep going. */
3cd52293 1753 m_stream->puts ("\n");
cbe56571 1754 }
a0087920 1755 else
3cd52293 1756 this->flush_wrap_buffer ();
c906108c 1757
eb6af809
TT
1758 /* Possible new page. Note that
1759 PAGINATION_DISABLED_FOR_COMMAND might be set during
1760 this loop, so we must continue to check it here. */
1f0f8b5d
TT
1761 if (pagination_enabled
1762 && !pagination_disabled_for_command
111d1981 1763 && lines_printed >= lines_allowed)
99f20f08
TT
1764 {
1765 prompt_for_continue ();
1766 did_paginate = true;
1767 }
c906108c 1768
581e13c1 1769 /* Now output indentation and wrapped string. */
3cd52293 1770 if (m_wrap_column)
c906108c 1771 {
3cd52293 1772 m_stream->puts (n_spaces (m_wrap_indent));
e7b43072
AB
1773
1774 /* Having finished inserting the wrapping we should
1775 restore the style as it was at the WRAP_COLUMN. */
12588184 1776 this->set_stream_style (m_wrap_style);
e7b43072
AB
1777
1778 /* The WRAP_BUFFER will still contain content, and that
1779 content might set some alternative style. Restore
1780 APPLIED_STYLE as it was before we started wrapping,
1781 this reflects the current style for the last character
1782 in WRAP_BUFFER. */
3cd52293 1783 m_applied_style = save_style;
e7b43072 1784
6c92c339 1785 /* Note that this can set chars_printed > chars_per_line
c906108c 1786 if we are printing a long string. */
3cd52293
TT
1787 chars_printed = m_wrap_indent + (save_chars - m_wrap_column);
1788 m_wrap_column = 0; /* And disable fancy wrap */
c5aa993b 1789 }
3cd52293 1790 else if (did_paginate)
e7b7270a 1791 this->emit_style_escape (save_style);
c906108c
SS
1792 }
1793 }
1794
9f5f1eb9 1795 if (*linebuffer == '\n')
c906108c
SS
1796 {
1797 chars_printed = 0;
3cd52293 1798 wrap_here (0); /* Spit out chars, cancel further wraps. */
c906108c 1799 lines_printed++;
3cd52293 1800 m_stream->puts ("\n");
9f5f1eb9 1801 linebuffer++;
c906108c
SS
1802 }
1803 }
a0087920
TT
1804
1805 buffer_clearer.release ();
c906108c
SS
1806}
1807
1808void
3cd52293 1809pager_file::write (const char *buf, long length_buf)
c906108c 1810{
3cd52293 1811 /* We have to make a string here because the pager uses
7b18593a 1812 examine_ansi_escape, which requires NUL-termination. */
3cd52293
TT
1813 std::string str (buf, length_buf);
1814 this->puts (str.c_str ());
c906108c
SS
1815}
1816
1f0f8b5d
TT
1817#if GDB_SELF_TEST
1818
1819/* Test that disabling the pager does not also disable word
1820 wrapping. */
1821
1822static void
1823test_pager ()
1824{
1825 string_file *strfile = new string_file ();
1826 pager_file pager (strfile);
1827
1828 /* Make sure the pager is disabled. */
1829 scoped_restore save_enabled
1830 = make_scoped_restore (&pagination_enabled, false);
1831 scoped_restore save_disabled
1832 = make_scoped_restore (&pagination_disabled_for_command, false);
1833 scoped_restore save_batch
1834 = make_scoped_restore (&batch_flag, false);
1835 scoped_restore save_lines
1836 = make_scoped_restore (&lines_per_page, 50);
1837 /* Make it easy to word wrap. */
1838 scoped_restore save_chars
1839 = make_scoped_restore (&chars_per_line, 15);
1840 scoped_restore save_printed
1841 = make_scoped_restore (&chars_printed, 0);
1842
1843 pager.puts ("aaaaaaaaaaaa");
1844 pager.wrap_here (2);
1845 pager.puts ("bbbbbbbbbbbb\n");
1846
1847 SELF_CHECK (strfile->string () == "aaaaaaaaaaaa\n bbbbbbbbbbbb\n");
1848}
1849
1850#endif /* GDB_SELF_TEST */
1851
dfcb27e4 1852void
0426ad51 1853gdb_puts (const char *linebuffer, struct ui_file *stream)
3cd52293
TT
1854{
1855 stream->puts (linebuffer);
dfcb27e4
IB
1856}
1857
a887499c
SM
1858void
1859gdb_puts (const std::string &s, ui_file *stream)
1860{
1861 gdb_puts (s.c_str (), stream);
1862}
1863
cbe56571
TT
1864/* See utils.h. */
1865
1866void
1867fputs_styled (const char *linebuffer, const ui_file_style &style,
1868 struct ui_file *stream)
1869{
3cd52293 1870 stream->emit_style_escape (style);
0426ad51 1871 gdb_puts (linebuffer, stream);
3cd52293 1872 stream->emit_style_escape (ui_file_style ());
cbe56571
TT
1873}
1874
9303eb2f
PW
1875/* See utils.h. */
1876
1877void
1878fputs_highlighted (const char *str, const compiled_regex &highlight,
1879 struct ui_file *stream)
1880{
1881 regmatch_t pmatch;
1882
1883 while (*str && highlight.exec (str, 1, &pmatch, 0) == 0)
1884 {
1885 size_t n_highlight = pmatch.rm_eo - pmatch.rm_so;
1886
1887 /* Output the part before pmatch with current style. */
1888 while (pmatch.rm_so > 0)
1889 {
a11ac3b3 1890 gdb_putc (*str, stream);
9303eb2f
PW
1891 pmatch.rm_so--;
1892 str++;
1893 }
1894
1895 /* Output pmatch with the highlight style. */
3cd52293 1896 stream->emit_style_escape (highlight_style.style ());
9303eb2f
PW
1897 while (n_highlight > 0)
1898 {
a11ac3b3 1899 gdb_putc (*str, stream);
9303eb2f
PW
1900 n_highlight--;
1901 str++;
1902 }
3cd52293 1903 stream->emit_style_escape (ui_file_style ());
9303eb2f
PW
1904 }
1905
1906 /* Output the trailing part of STR not matching HIGHLIGHT. */
1907 if (*str)
0426ad51 1908 gdb_puts (str, stream);
9303eb2f
PW
1909}
1910
4311246b 1911void
a11ac3b3 1912gdb_putc (int c)
d1f4cff8 1913{
a11ac3b3 1914 return gdb_stdout->putc (c);
d1f4cff8
AC
1915}
1916
4311246b 1917void
a11ac3b3 1918gdb_putc (int c, struct ui_file *stream)
c906108c 1919{
a11ac3b3 1920 return stream->putc (c);
c906108c
SS
1921}
1922
c906108c 1923void
19a7b8ab 1924gdb_vprintf (struct ui_file *stream, const char *format, va_list args)
c906108c 1925{
19a7b8ab 1926 stream->vprintf (format, args);
c906108c
SS
1927}
1928
1929void
19a7b8ab 1930gdb_vprintf (const char *format, va_list args)
c906108c 1931{
19a7b8ab 1932 gdb_stdout->vprintf (format, args);
c906108c
SS
1933}
1934
c906108c 1935void
6cb06a8c 1936gdb_printf (struct ui_file *stream, const char *format, ...)
c906108c
SS
1937{
1938 va_list args;
e0627e85 1939
c906108c 1940 va_start (args, format);
19a7b8ab 1941 gdb_vprintf (stream, format, args);
c906108c
SS
1942 va_end (args);
1943}
1944
cbe56571
TT
1945/* See utils.h. */
1946
1947void
1948fprintf_styled (struct ui_file *stream, const ui_file_style &style,
1949 const char *format, ...)
1950{
1951 va_list args;
1952
3cd52293 1953 stream->emit_style_escape (style);
cbe56571 1954 va_start (args, format);
19a7b8ab 1955 gdb_vprintf (stream, format, args);
cbe56571 1956 va_end (args);
3cd52293 1957 stream->emit_style_escape (ui_file_style ());
cbe56571
TT
1958}
1959
c906108c 1960void
6cb06a8c 1961gdb_printf (const char *format, ...)
c906108c
SS
1962{
1963 va_list args;
e0627e85 1964
c906108c 1965 va_start (args, format);
19a7b8ab 1966 gdb_vprintf (gdb_stdout, format, args);
c906108c
SS
1967 va_end (args);
1968}
1969
1970
c906108c 1971void
8731e58e 1972printf_unfiltered (const char *format, ...)
c906108c
SS
1973{
1974 va_list args;
e0627e85 1975
c906108c 1976 va_start (args, format);
9b716718
TT
1977 string_file file (gdb_stdout->can_emit_style_escape ());
1978 file.vprintf (format, args);
1979 gdb_stdout->puts_unfiltered (file.string ().c_str ());
c906108c
SS
1980 va_end (args);
1981}
1982
c906108c
SS
1983/* Easy -- but watch out!
1984
1985 This routine is *not* a replacement for puts()! puts() appends a newline.
1986 This one doesn't, and had better not! */
1987
1988void
0426ad51 1989gdb_puts (const char *string)
c906108c 1990{
0426ad51 1991 gdb_stdout->puts (string);
c906108c
SS
1992}
1993
c906108c
SS
1994/* Return a pointer to N spaces and a null. The pointer is good
1995 until the next call to here. */
dde238e0 1996const char *
fba45db2 1997n_spaces (int n)
c906108c 1998{
392a587b
JM
1999 char *t;
2000 static char *spaces = 0;
2001 static int max_spaces = -1;
c906108c
SS
2002
2003 if (n > max_spaces)
2004 {
84d53fa9 2005 xfree (spaces);
c5aa993b
JM
2006 spaces = (char *) xmalloc (n + 1);
2007 for (t = spaces + n; t != spaces;)
c906108c
SS
2008 *--t = ' ';
2009 spaces[n] = '\0';
2010 max_spaces = n;
2011 }
2012
2013 return spaces + max_spaces - n;
2014}
2015
2016/* Print N spaces. */
2017void
d0b1020b 2018print_spaces (int n, struct ui_file *stream)
c906108c 2019{
0426ad51 2020 gdb_puts (n_spaces (n), stream);
c906108c
SS
2021}
2022\f
4a351cef 2023/* C++/ObjC demangler stuff. */
c906108c 2024
bed009b9 2025/* fprintf_symbol attempts to demangle NAME, a symbol in language
389e51db
AC
2026 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2027 If the name is not mangled, or the language for the name is unknown, or
581e13c1 2028 demangling is off, the name is printed in its "raw" form. */
c906108c
SS
2029
2030void
bed009b9
TT
2031fprintf_symbol (struct ui_file *stream, const char *name,
2032 enum language lang, int arg_mode)
c906108c 2033{
c906108c
SS
2034 if (name != NULL)
2035 {
2036 /* If user wants to see raw output, no problem. */
2037 if (!demangle)
2038 {
0426ad51 2039 gdb_puts (name, stream);
c906108c
SS
2040 }
2041 else
2042 {
3456e70c 2043 gdb::unique_xmalloc_ptr<char> demangled
9497d69f 2044 = language_def (lang)->demangle_symbol (name, arg_mode);
0426ad51 2045 gdb_puts (demangled ? demangled.get () : name, stream);
c906108c
SS
2046 }
2047 }
2048}
2049
0662b6a7
PA
2050/* True if CH is a character that can be part of a symbol name. I.e.,
2051 either a number, a letter, or a '_'. */
2052
2053static bool
2054valid_identifier_name_char (int ch)
2055{
51e2cfa2 2056 return (ISALNUM (ch) || ch == '_');
0662b6a7
PA
2057}
2058
2059/* Skip to end of token, or to END, whatever comes first. Input is
2060 assumed to be a C++ operator name. */
2061
2062static const char *
2063cp_skip_operator_token (const char *token, const char *end)
2064{
2065 const char *p = token;
51e2cfa2 2066 while (p != end && !ISSPACE (*p) && *p != '(')
0662b6a7
PA
2067 {
2068 if (valid_identifier_name_char (*p))
2069 {
2070 while (p != end && valid_identifier_name_char (*p))
2071 p++;
2072 return p;
2073 }
2074 else
2075 {
2076 /* Note, ordered such that among ops that share a prefix,
2077 longer comes first. This is so that the loop below can
2078 bail on first match. */
2079 static const char *ops[] =
2080 {
2081 "[",
2082 "]",
2083 "~",
2084 ",",
2085 "-=", "--", "->", "-",
2086 "+=", "++", "+",
2087 "*=", "*",
2088 "/=", "/",
2089 "%=", "%",
2090 "|=", "||", "|",
2091 "&=", "&&", "&",
2092 "^=", "^",
2093 "!=", "!",
2094 "<<=", "<=", "<<", "<",
2095 ">>=", ">=", ">>", ">",
2096 "==", "=",
2097 };
2098
2099 for (const char *op : ops)
2100 {
2101 size_t oplen = strlen (op);
2102 size_t lencmp = std::min<size_t> (oplen, end - p);
2103
2104 if (strncmp (p, op, lencmp) == 0)
2105 return p + lencmp;
2106 }
2107 /* Some unidentified character. Return it. */
2108 return p + 1;
2109 }
2110 }
2111
2112 return p;
2113}
2114
2115/* Advance STRING1/STRING2 past whitespace. */
2116
2117static void
2118skip_ws (const char *&string1, const char *&string2, const char *end_str2)
2119{
51e2cfa2 2120 while (ISSPACE (*string1))
0662b6a7 2121 string1++;
51e2cfa2 2122 while (string2 < end_str2 && ISSPACE (*string2))
0662b6a7
PA
2123 string2++;
2124}
2125
2126/* True if STRING points at the start of a C++ operator name. START
2127 is the start of the string that STRING points to, hence when
2128 reading backwards, we must not read any character before START. */
2129
2130static bool
2131cp_is_operator (const char *string, const char *start)
2132{
2133 return ((string == start
2134 || !valid_identifier_name_char (string[-1]))
2135 && strncmp (string, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
2136 && !valid_identifier_name_char (string[CP_OPERATOR_LEN]));
2137}
2138
bd69330d
PA
2139/* If *NAME points at an ABI tag, skip it and return true. Otherwise
2140 leave *NAME unmodified and return false. (see GCC's abi_tag
2141 attribute), such names are demangled as e.g.,
2142 "function[abi:cxx11]()". */
2143
2144static bool
2145skip_abi_tag (const char **name)
2146{
2147 const char *p = *name;
2148
2149 if (startswith (p, "[abi:"))
2150 {
2151 p += 5;
2152
2153 while (valid_identifier_name_char (*p))
2154 p++;
2155
2156 if (*p == ']')
2157 {
2158 p++;
2159 *name = p;
2160 return true;
2161 }
2162 }
2163 return false;
2164}
2165
64a97606
KS
2166/* If *NAME points at a template parameter list, skip it and return true.
2167 Otherwise do nothing and return false. */
2168
2169static bool
2170skip_template_parameter_list (const char **name)
2171{
2172 const char *p = *name;
2173
2174 if (*p == '<')
2175 {
2176 const char *template_param_list_end = find_toplevel_char (p + 1, '>');
2177
2178 if (template_param_list_end == NULL)
2179 return false;
2180
2181 p = template_param_list_end + 1;
2182
2183 /* Skip any whitespace that might occur after the closing of the
2184 parameter list, but only if it is the end of parameter list. */
2185 const char *q = p;
2186 while (ISSPACE (*q))
2187 ++q;
2188 if (*q == '>')
2189 p = q;
2190 *name = p;
2191 return true;
2192 }
2193
2194 return false;
2195}
2196
b5ec771e 2197/* See utils.h. */
1d550c82 2198
b5ec771e 2199int
1d550c82 2200strncmp_iw_with_mode (const char *string1, const char *string2,
0662b6a7 2201 size_t string2_len, strncmp_iw_mode mode,
bd69330d 2202 enum language language,
64a97606
KS
2203 completion_match_for_lcd *match_for_lcd,
2204 bool ignore_template_params)
c906108c 2205{
0662b6a7 2206 const char *string1_start = string1;
1d550c82 2207 const char *end_str2 = string2 + string2_len;
0662b6a7
PA
2208 bool skip_spaces = true;
2209 bool have_colon_op = (language == language_cplus
2210 || language == language_rust
2211 || language == language_fortran);
1d550c82 2212
454f8b67
AB
2213 gdb_assert (match_for_lcd == nullptr || match_for_lcd->empty ());
2214
1d550c82 2215 while (1)
c906108c 2216 {
0662b6a7 2217 if (skip_spaces
51e2cfa2
PA
2218 || ((ISSPACE (*string1) && !valid_identifier_name_char (*string2))
2219 || (ISSPACE (*string2) && !valid_identifier_name_char (*string1))))
0662b6a7
PA
2220 {
2221 skip_ws (string1, string2, end_str2);
2222 skip_spaces = false;
2223 }
2224
bd69330d
PA
2225 /* Skip [abi:cxx11] tags in the symbol name if the lookup name
2226 doesn't include them. E.g.:
2227
2228 string1: function[abi:cxx1](int)
2229 string2: function
2230
2231 string1: function[abi:cxx1](int)
2232 string2: function(int)
2233
2234 string1: Struct[abi:cxx1]::function()
2235 string2: Struct::function()
2236
2237 string1: function(Struct[abi:cxx1], int)
2238 string2: function(Struct, int)
2239 */
2240 if (string2 == end_str2
2241 || (*string2 != '[' && !valid_identifier_name_char (*string2)))
2242 {
2243 const char *abi_start = string1;
2244
2245 /* There can be more than one tag. */
2246 while (*string1 == '[' && skip_abi_tag (&string1))
2247 ;
2248
2249 if (match_for_lcd != NULL && abi_start != string1)
2250 match_for_lcd->mark_ignored_range (abi_start, string1);
2251
51e2cfa2 2252 while (ISSPACE (*string1))
bd69330d
PA
2253 string1++;
2254 }
2255
64a97606
KS
2256 /* Skip template parameters in STRING1 if STRING2 does not contain
2257 any. E.g.:
2258
2259 Case 1: User is looking for all functions named "foo".
2260 string1: foo <...> (...)
2261 string2: foo
2262
2263 Case 2: User is looking for all methods named "foo" in all template
2264 class instantiations.
2265 string1: Foo<...>::foo <...> (...)
2266 string2: Foo::foo (...)
2267
2268 Case 3: User is looking for a specific overload of a template
2269 function or method.
2270 string1: foo<...>
2271 string2: foo(...)
2272
2273 Case 4: User is looking for a specific overload of a specific
2274 template instantiation.
2275 string1: foo<A> (...)
2276 string2: foo<B> (...)
2277
2278 Case 5: User is looking wild parameter match.
2279 string1: foo<A<a<b<...> > > > (...)
2280 string2: foo<A
2281 */
2282 if (language == language_cplus && ignore_template_params
2283 && *string1 == '<' && *string2 != '<')
2284 {
2285 /* Skip any parameter list in STRING1. */
2286 const char *template_start = string1;
2287
2288 if (skip_template_parameter_list (&string1))
2289 {
2290 /* Don't mark the parameter list ignored if the user didn't
2291 try to ignore it. [Case #5 above] */
2292 if (*string2 != '\0'
2293 && match_for_lcd != NULL && template_start != string1)
2294 match_for_lcd->mark_ignored_range (template_start, string1);
2295 }
2296 }
2297
1d550c82
PA
2298 if (*string1 == '\0' || string2 == end_str2)
2299 break;
0662b6a7
PA
2300
2301 /* Handle the :: operator. */
2302 if (have_colon_op && string1[0] == ':' && string1[1] == ':')
2303 {
2304 if (*string2 != ':')
2305 return 1;
2306
2307 string1++;
2308 string2++;
2309
2310 if (string2 == end_str2)
2311 break;
2312
2313 if (*string2 != ':')
2314 return 1;
2315
2316 string1++;
2317 string2++;
2318
51e2cfa2 2319 while (ISSPACE (*string1))
0662b6a7 2320 string1++;
51e2cfa2 2321 while (string2 < end_str2 && ISSPACE (*string2))
0662b6a7
PA
2322 string2++;
2323 continue;
2324 }
2325
2326 /* Handle C++ user-defined operators. */
2327 else if (language == language_cplus
2328 && *string1 == 'o')
2329 {
2330 if (cp_is_operator (string1, string1_start))
2331 {
2332 /* An operator name in STRING1. Check STRING2. */
2333 size_t cmplen
2334 = std::min<size_t> (CP_OPERATOR_LEN, end_str2 - string2);
2335 if (strncmp (string1, string2, cmplen) != 0)
2336 return 1;
2337
2338 string1 += cmplen;
2339 string2 += cmplen;
2340
2341 if (string2 != end_str2)
2342 {
2343 /* Check for "operatorX" in STRING2. */
2344 if (valid_identifier_name_char (*string2))
2345 return 1;
2346
2347 skip_ws (string1, string2, end_str2);
2348 }
2349
2350 /* Handle operator(). */
2351 if (*string1 == '(')
2352 {
2353 if (string2 == end_str2)
2354 {
2355 if (mode == strncmp_iw_mode::NORMAL)
2356 return 0;
2357 else
2358 {
2359 /* Don't break for the regular return at the
2360 bottom, because "operator" should not
2361 match "operator()", since this open
2362 parentheses is not the parameter list
2363 start. */
2364 return *string1 != '\0';
2365 }
2366 }
2367
2368 if (*string1 != *string2)
2369 return 1;
2370
2371 string1++;
2372 string2++;
2373 }
2374
2375 while (1)
2376 {
2377 skip_ws (string1, string2, end_str2);
2378
2379 /* Skip to end of token, or to END, whatever comes
2380 first. */
2381 const char *end_str1 = string1 + strlen (string1);
2382 const char *p1 = cp_skip_operator_token (string1, end_str1);
2383 const char *p2 = cp_skip_operator_token (string2, end_str2);
2384
2385 cmplen = std::min (p1 - string1, p2 - string2);
2386 if (p2 == end_str2)
2387 {
2388 if (strncmp (string1, string2, cmplen) != 0)
2389 return 1;
2390 }
2391 else
2392 {
2393 if (p1 - string1 != p2 - string2)
2394 return 1;
2395 if (strncmp (string1, string2, cmplen) != 0)
2396 return 1;
2397 }
2398
2399 string1 += cmplen;
2400 string2 += cmplen;
2401
2402 if (*string1 == '\0' || string2 == end_str2)
2403 break;
2404 if (*string1 == '(' || *string2 == '(')
2405 break;
64a97606
KS
2406
2407 /* If STRING1 or STRING2 starts with a template
2408 parameter list, break out of operator processing. */
2409 skip_ws (string1, string2, end_str2);
2410 if (*string1 == '<' || *string2 == '<')
2411 break;
0662b6a7
PA
2412 }
2413
2414 continue;
2415 }
2416 }
2417
559a7a62
JK
2418 if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2419 break;
2420 if (case_sensitivity == case_sensitive_off
51e2cfa2
PA
2421 && (TOLOWER ((unsigned char) *string1)
2422 != TOLOWER ((unsigned char) *string2)))
559a7a62 2423 break;
1d550c82 2424
0662b6a7
PA
2425 /* If we see any non-whitespace, non-identifier-name character
2426 (any of "()<>*&" etc.), then skip spaces the next time
2427 around. */
51e2cfa2 2428 if (!ISSPACE (*string1) && !valid_identifier_name_char (*string1))
0662b6a7
PA
2429 skip_spaces = true;
2430
1d550c82
PA
2431 string1++;
2432 string2++;
c906108c 2433 }
1d550c82
PA
2434
2435 if (string2 == end_str2)
2436 {
2437 if (mode == strncmp_iw_mode::NORMAL)
bd69330d
PA
2438 {
2439 /* Strip abi tag markers from the matched symbol name.
2440 Usually the ABI marker will be found on function name
2441 (automatically added because the function returns an
2442 object marked with an ABI tag). However, it's also
2443 possible to see a marker in one of the function
2444 parameters, for example.
2445
2446 string2 (lookup name):
2447 func
2448 symbol name:
2449 function(some_struct[abi:cxx11], int)
2450
2451 and for completion LCD computation we want to say that
2452 the match was for:
2453 function(some_struct, int)
2454 */
2455 if (match_for_lcd != NULL)
2456 {
2457 while ((string1 = strstr (string1, "[abi:")) != NULL)
2458 {
2459 const char *abi_start = string1;
2460
2461 /* There can be more than one tag. */
2462 while (skip_abi_tag (&string1) && *string1 == '[')
2463 ;
2464
2465 if (abi_start != string1)
2466 match_for_lcd->mark_ignored_range (abi_start, string1);
2467 }
2468 }
2469
2470 return 0;
2471 }
1d550c82 2472 else
f0bdf68d
AB
2473 {
2474 if (*string1 == '(')
2475 {
2476 int p_count = 0;
2477
2478 do
2479 {
2480 if (*string1 == '(')
2481 ++p_count;
2482 else if (*string1 == ')')
2483 --p_count;
2484 ++string1;
2485 }
2486 while (*string1 != '\0' && p_count > 0);
2487
2488 /* There maybe things like 'const' after the parameters,
2489 which we do want to ignore. However, if there's an '@'
2490 then this likely indicates something like '@plt' which we
2491 should not ignore. */
2492 return *string1 == '@';
2493 }
2494
2495 return *string1 == '\0' ? 0 : 1;
2496 }
2497
1d550c82
PA
2498 }
2499 else
2500 return 1;
2501}
2502
b05752c2
KS
2503#if GDB_SELF_TEST
2504
2505/* Unit tests for strncmp_iw_with_mode. */
2506
2507#define CHECK_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2508 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2509 strncmp_iw_mode::MODE, \
2510 (LANG), (LCD)) == 0)
2511
2512#define CHECK_MATCH_LANG(S1, S2, MODE, LANG) \
2513 CHECK_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2514
2515#define CHECK_MATCH(S1, S2, MODE) \
2516 CHECK_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2517
2518#define CHECK_NO_MATCH_LM(S1, S2, MODE, LANG, LCD) \
2519 SELF_CHECK (strncmp_iw_with_mode ((S1), (S2), strlen ((S2)), \
2520 strncmp_iw_mode::MODE, \
2521 (LANG)) != 0)
2522
2523#define CHECK_NO_MATCH_LANG(S1, S2, MODE, LANG) \
2524 CHECK_NO_MATCH_LM ((S1), (S2), MODE, (LANG), nullptr)
2525
2526#define CHECK_NO_MATCH(S1, S2, MODE) \
2527 CHECK_NO_MATCH_LANG ((S1), (S2), MODE, language_minimal)
2528
2529static void
2530check_scope_operator (enum language lang)
2531{
2532 CHECK_MATCH_LANG ("::", "::", NORMAL, lang);
2533 CHECK_MATCH_LANG ("::foo", "::", NORMAL, lang);
2534 CHECK_MATCH_LANG ("::foo", "::foo", NORMAL, lang);
2535 CHECK_MATCH_LANG (" :: foo ", "::foo", NORMAL, lang);
2536 CHECK_MATCH_LANG ("a::b", "a ::b", NORMAL, lang);
2537 CHECK_MATCH_LANG ("a::b", "a\t::b", NORMAL, lang);
2538 CHECK_MATCH_LANG ("a::b", "a \t::b", NORMAL, lang);
2539 CHECK_MATCH_LANG ("a::b", "a\t ::b", NORMAL, lang);
2540 CHECK_MATCH_LANG ("a::b", "a:: b", NORMAL, lang);
2541 CHECK_MATCH_LANG ("a::b", "a::\tb", NORMAL, lang);
2542 CHECK_MATCH_LANG ("a::b", "a:: \tb", NORMAL, lang);
2543 CHECK_MATCH_LANG ("a::b", "a::\t b", NORMAL, lang);
2544 CHECK_MATCH_LANG ("a::b", "a :: b", NORMAL, lang);
2545 CHECK_MATCH_LANG ("a::b", "a ::\tb", NORMAL, lang);
2546 CHECK_MATCH_LANG ("a::b", "a\t:: b", NORMAL, lang);
2547 CHECK_MATCH_LANG ("a::b", "a \t::\t b", NORMAL, lang);
2548 CHECK_MATCH_LANG ("a ::b", "a::b", NORMAL, lang);
2549 CHECK_MATCH_LANG ("a\t::b", "a::b", NORMAL, lang);
2550 CHECK_MATCH_LANG ("a \t::b", "a::b", NORMAL, lang);
2551 CHECK_MATCH_LANG ("a\t ::b", "a::b", NORMAL, lang);
2552 CHECK_MATCH_LANG ("a:: b", "a::b", NORMAL, lang);
2553 CHECK_MATCH_LANG ("a::\tb", "a::b", NORMAL, lang);
2554 CHECK_MATCH_LANG ("a:: \tb", "a::b", NORMAL, lang);
2555 CHECK_MATCH_LANG ("a::\t b", "a::b", NORMAL, lang);
2556 CHECK_MATCH_LANG ("a :: b", "a::b", NORMAL, lang);
2557 CHECK_MATCH_LANG ("a ::\tb", "a::b", NORMAL, lang);
2558 CHECK_MATCH_LANG ("a\t:: b", "a::b", NORMAL, lang);
2559 CHECK_MATCH_LANG ("a \t::\t b", "a::b", NORMAL, lang);
2560 CHECK_MATCH_LANG ("a::b::c", "a::b::c", NORMAL, lang);
2561 CHECK_MATCH_LANG (" a:: b:: c", "a::b::c", NORMAL, lang);
2562 CHECK_MATCH_LANG ("a::b::c", " a:: b:: c", NORMAL, lang);
2563 CHECK_MATCH_LANG ("a ::b ::c", "a::b::c", NORMAL, lang);
2564 CHECK_MATCH_LANG ("a::b::c", "a :: b:: c", NORMAL, lang);
2565 CHECK_MATCH_LANG ("\ta::\tb::\tc", "\ta::\tb::\tc", NORMAL, lang);
2566 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a\t::b\t::c\t", NORMAL, lang);
2567 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", " \ta:: \tb:: \tc", NORMAL, lang);
2568 CHECK_MATCH_LANG ("\t a::\t b::\t c", "\t a::\t b::\t c", NORMAL, lang);
2569 CHECK_MATCH_LANG ("a::b::c", "\ta::\tb::\tc", NORMAL, lang);
2570 CHECK_MATCH_LANG ("a::b::c", "a\t::b\t::c\t", NORMAL, lang);
2571 CHECK_MATCH_LANG ("a::b::c", " \ta:: \tb:: \tc", NORMAL, lang);
2572 CHECK_MATCH_LANG ("a::b::c", "\t a::\t b::\t c", NORMAL, lang);
2573 CHECK_MATCH_LANG ("\ta::\tb::\tc", "a::b::c", NORMAL, lang);
2574 CHECK_MATCH_LANG ("a\t::b\t::c\t", "a::b::c", NORMAL, lang);
2575 CHECK_MATCH_LANG (" \ta:: \tb:: \tc", "a::b::c", NORMAL, lang);
2576 CHECK_MATCH_LANG ("\t a::\t b::\t c", "a::b::c", NORMAL, lang);
2577 CHECK_MATCH_LANG ("a :: b:: c\t", "\ta :: b\t:: c\t\t", NORMAL, lang);
2578 CHECK_MATCH_LANG (" a::\t \t b:: c\t", "\ta ::b:: c\t\t",
2579 NORMAL, lang);
2580 CHECK_MATCH_LANG ("a :: b :: \t\t\tc\t",
2581 "\t\t\t\ta :: \t\t\t b \t\t::c",
2582 NORMAL, lang);
2583 CHECK_MATCH_LANG ("a::b()", "a", NORMAL, lang);
2584 CHECK_MATCH_LANG ("a::b()", "a::", NORMAL, lang);
2585 CHECK_MATCH_LANG ("a::b()", "a::b", NORMAL, lang);
2586 CHECK_MATCH_LANG ("a::b(a)", "a", NORMAL, lang);
2587 CHECK_MATCH_LANG ("a::b(a)", "a::", NORMAL, lang);
2588 CHECK_MATCH_LANG ("a::b(a)", "a::b", NORMAL, lang);
2589 CHECK_MATCH_LANG ("a::b(a,b)", "a", NORMAL, lang);
2590 CHECK_MATCH_LANG ("a::b(a,b)", "a::", NORMAL, lang);
2591 CHECK_MATCH_LANG ("a::b(a,b)", "a::b", NORMAL, lang);
2592 CHECK_MATCH_LANG ("a::b(a,b,c)", "a", NORMAL, lang);
2593 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::", NORMAL, lang);
2594 CHECK_MATCH_LANG ("a::b(a,b,c)", "a::b", NORMAL, lang);
2595
2596 CHECK_NO_MATCH_LANG ("a::", "::a", NORMAL, lang);
2597 CHECK_NO_MATCH_LANG ("::a", "::a()", NORMAL, lang);
2598 CHECK_NO_MATCH_LANG ("::", "::a", NORMAL, lang);
2599 CHECK_NO_MATCH_LANG ("a:::b", "a::b", NORMAL, lang);
2600 CHECK_NO_MATCH_LANG ("a::b()", "a::b(a)", NORMAL, lang);
2601 CHECK_NO_MATCH_LANG ("a::b(a)", "a::b()", NORMAL, lang);
2602 CHECK_NO_MATCH_LANG ("a::b(a,b)", "a::b(a,a)", NORMAL, lang);
2603 CHECK_NO_MATCH_LANG ("a::b", "a()", NORMAL, lang);
2604 CHECK_NO_MATCH_LANG ("a::b", "a::()", NORMAL, lang);
2605 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2606 CHECK_NO_MATCH_LANG ("a::b", "a(a)", NORMAL, lang);
2607 CHECK_NO_MATCH_LANG ("a::b", "a::(a)", NORMAL, lang);
2608 CHECK_NO_MATCH_LANG ("a::b", "a::b()", NORMAL, lang);
2609 CHECK_NO_MATCH_LANG ("a::b", "a(a,b)", NORMAL, lang);
2610 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b)", NORMAL, lang);
2611 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b)", NORMAL, lang);
2612 CHECK_NO_MATCH_LANG ("a::b", "a(a,b,c)", NORMAL, lang);
2613 CHECK_NO_MATCH_LANG ("a::b", "a::(a,b,c)", NORMAL, lang);
2614 CHECK_NO_MATCH_LANG ("a::b", "a::b(a,b,c)", NORMAL, lang);
2615}
2616
2617/* Callback for strncmp_iw_with_mode unit tests. */
2618
2619static void
2620strncmp_iw_with_mode_tests ()
2621{
2622 /* Some of the following tests are nonsensical, but could be input by a
2623 deranged script (or user). */
2624
2625 /* strncmp_iw_mode::NORMAL: strcmp()-like but ignore any whitespace... */
2626
2627 CHECK_MATCH ("", "", NORMAL);
2628 CHECK_MATCH ("foo", "foo", NORMAL);
2629 CHECK_MATCH (" foo", "foo", NORMAL);
2630 CHECK_MATCH ("foo ", "foo", NORMAL);
2631 CHECK_MATCH (" foo ", "foo", NORMAL);
2632 CHECK_MATCH (" foo", "foo", NORMAL);
2633 CHECK_MATCH ("foo ", "foo", NORMAL);
2634 CHECK_MATCH (" foo ", "foo", NORMAL);
2635 CHECK_MATCH ("\tfoo", "foo", NORMAL);
2636 CHECK_MATCH ("foo\t", "foo", NORMAL);
2637 CHECK_MATCH ("\tfoo\t", "foo", NORMAL);
2638 CHECK_MATCH (" \tfoo \t", "foo", NORMAL);
2639 CHECK_MATCH ("\t foo\t ", "foo", NORMAL);
2640 CHECK_MATCH ("\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2641 "foo", NORMAL);
2642 CHECK_MATCH ("foo",
2643 "\t \t \t\t\t\t foo\t\t\t \t\t \t \t \t \t ",
2644 NORMAL);
2645 CHECK_MATCH ("foo bar", "foo", NORMAL);
2646 CHECK_NO_MATCH ("foo", "bar", NORMAL);
2647 CHECK_NO_MATCH ("foo bar", "foobar", NORMAL);
2648 CHECK_NO_MATCH (" foo ", "bar", NORMAL);
2649 CHECK_NO_MATCH ("foo", " bar ", NORMAL);
2650 CHECK_NO_MATCH (" \t\t foo\t\t ", "\t \t \tbar\t", NORMAL);
2651 CHECK_NO_MATCH ("@!%&", "@!%&foo", NORMAL);
2652
2653 /* ... and function parameters in STRING1. */
2654 CHECK_MATCH ("foo()", "foo()", NORMAL);
2655 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2656 CHECK_MATCH ("foo ()", "foo()", NORMAL);
2657 CHECK_MATCH ("foo\t()", "foo()", NORMAL);
2658 CHECK_MATCH ("foo\t ()", "foo()", NORMAL);
2659 CHECK_MATCH ("foo \t()", "foo()", NORMAL);
2660 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2661 CHECK_MATCH ("foo()", "foo ()", NORMAL);
2662 CHECK_MATCH ("foo()", "foo\t()", NORMAL);
2663 CHECK_MATCH ("foo()", "foo\t ()", NORMAL);
2664 CHECK_MATCH ("foo()", "foo \t()", NORMAL);
2665 CHECK_MATCH ("foo()", "foo()", NORMAL);
2666 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2667 CHECK_MATCH ("foo ()", "foo ()", NORMAL);
2668 CHECK_MATCH ("foo\t()", "foo\t()", NORMAL);
2669 CHECK_MATCH ("foo\t ()", "foo\t ()", NORMAL);
2670 CHECK_MATCH ("foo \t()", "foo \t()", NORMAL);
2671 CHECK_MATCH ("foo(a)", "foo(a)", NORMAL);
2672 CHECK_MATCH ("foo( a)", "foo(a)", NORMAL);
2673 CHECK_MATCH ("foo(a )", "foo(a)", NORMAL);
2674 CHECK_MATCH ("foo(\ta)", "foo(a)", NORMAL);
2675 CHECK_MATCH ("foo(a\t)", "foo(a)", NORMAL);
2676 CHECK_MATCH ("foo(\t a)", "foo(a)", NORMAL);
2677 CHECK_MATCH ("foo( \ta)", "foo(a)", NORMAL);
2678 CHECK_MATCH ("foo(a\t )", "foo(a)", NORMAL);
2679 CHECK_MATCH ("foo(a \t)", "foo(a)", NORMAL);
2680 CHECK_MATCH ("foo( a )", "foo(a)", NORMAL);
2681 CHECK_MATCH ("foo(\ta\t)", "foo(a)", NORMAL);
2682 CHECK_MATCH ("foo(\t a\t )", "foo(a)", NORMAL);
2683 CHECK_MATCH ("foo( \ta \t)", "foo(a)", NORMAL);
2684 CHECK_MATCH ("foo(a)", "foo( a)", NORMAL);
2685 CHECK_MATCH ("foo(a)", "foo(a )", NORMAL);
2686 CHECK_MATCH ("foo(a)", "foo(\ta)", NORMAL);
2687 CHECK_MATCH ("foo(a)", "foo(a\t)", NORMAL);
2688 CHECK_MATCH ("foo(a)", "foo(\t a)", NORMAL);
2689 CHECK_MATCH ("foo(a)", "foo( \ta)", NORMAL);
2690 CHECK_MATCH ("foo(a)", "foo(a\t )", NORMAL);
2691 CHECK_MATCH ("foo(a)", "foo(a \t)", NORMAL);
2692 CHECK_MATCH ("foo(a)", "foo( a )", NORMAL);
2693 CHECK_MATCH ("foo(a)", "foo(\ta\t)", NORMAL);
2694 CHECK_MATCH ("foo(a)", "foo(\t a\t )", NORMAL);
2695 CHECK_MATCH ("foo(a)", "foo( \ta \t)", NORMAL);
2696 CHECK_MATCH ("foo(a,b)", "foo(a,b)", NORMAL);
2697 CHECK_MATCH ("foo(a ,b)", "foo(a,b)", NORMAL);
2698 CHECK_MATCH ("foo(a\t,b)", "foo(a,b)", NORMAL);
2699 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2700 CHECK_MATCH ("foo(a\t,\tb)", "foo(a,b)", NORMAL);
2701 CHECK_MATCH ("foo(a \t,b)", "foo(a,b)", NORMAL);
2702 CHECK_MATCH ("foo(a\t ,b)", "foo(a,b)", NORMAL);
2703 CHECK_MATCH ("foo(a,\tb)", "foo(a,b)", NORMAL);
2704 CHECK_MATCH ("foo(a, \tb)", "foo(a,b)", NORMAL);
2705 CHECK_MATCH ("foo(a,\t b)", "foo(a,b)", NORMAL);
2706 CHECK_MATCH ("foo(a,b)", "foo(a ,b)", NORMAL);
2707 CHECK_MATCH ("foo(a,b)", "foo(a\t,b)", NORMAL);
2708 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2709 CHECK_MATCH ("foo(a,b)", "foo(a\t,\tb)", NORMAL);
2710 CHECK_MATCH ("foo(a,b)", "foo(a \t,b)", NORMAL);
2711 CHECK_MATCH ("foo(a,b)", "foo(a\t ,b)", NORMAL);
2712 CHECK_MATCH ("foo(a,b)", "foo(a,\tb)", NORMAL);
2713 CHECK_MATCH ("foo(a,b)", "foo(a, \tb)", NORMAL);
2714 CHECK_MATCH ("foo(a,b)", "foo(a,\t b)", NORMAL);
2715 CHECK_MATCH ("foo(a,b,c,d)", "foo(a,b,c,d)", NORMAL);
2716 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo(a,b,c,d)", NORMAL);
2717 CHECK_MATCH (" foo ( a , b , c , d ) ", "foo( a , b , c , d )", NORMAL);
2718 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo", NORMAL);
2719 CHECK_MATCH ("foo &\t*(\ta b *\t\t&)", "foo&*(a b * &)", NORMAL);
2720 CHECK_MATCH ("foo(a) b", "foo(a)", NORMAL);
2721 CHECK_MATCH ("*foo(*a&)", "*foo", NORMAL);
2722 CHECK_MATCH ("*foo(*a&)", "*foo(*a&)", NORMAL);
2723 CHECK_MATCH ("*a&b#c/^d$foo(*a&)", "*a&b#c/^d$foo", NORMAL);
2724 CHECK_MATCH ("* foo", "*foo", NORMAL);
2725 CHECK_MATCH ("foo&", "foo", NORMAL);
2726 CHECK_MATCH ("foo*", "foo", NORMAL);
2727 CHECK_MATCH ("foo.", "foo", NORMAL);
2728 CHECK_MATCH ("foo->", "foo", NORMAL);
2729
2730 CHECK_NO_MATCH ("foo", "foo(", NORMAL);
2731 CHECK_NO_MATCH ("foo", "foo()", NORMAL);
2732 CHECK_NO_MATCH ("foo", "foo(a)", NORMAL);
2733 CHECK_NO_MATCH ("foo", "foo(a)", NORMAL);
2734 CHECK_NO_MATCH ("foo", "foo*", NORMAL);
2735 CHECK_NO_MATCH ("foo", "foo (*", NORMAL);
2736 CHECK_NO_MATCH ("foo*", "foo (*", NORMAL);
2737 CHECK_NO_MATCH ("foo *", "foo (*", NORMAL);
2738 CHECK_NO_MATCH ("foo&", "foo (*", NORMAL);
2739 CHECK_NO_MATCH ("foo &", "foo (*", NORMAL);
2740 CHECK_NO_MATCH ("foo &*", "foo (&)", NORMAL);
2741 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2742 CHECK_NO_MATCH ("foo & \t *\t", "foo (*", NORMAL);
2743 CHECK_NO_MATCH ("foo(a*) b", "foo(a) b", NORMAL);
2744 CHECK_NO_MATCH ("foo[aqi:A](a)", "foo(b)", 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&", "&foo", NORMAL);
2752 CHECK_NO_MATCH ("foo", "foo&", NORMAL);
2753 CHECK_NO_MATCH ("foo", "foo*", NORMAL);
2754 CHECK_NO_MATCH ("foo", "foo.", NORMAL);
2755 CHECK_NO_MATCH ("foo", "foo->", NORMAL);
2756 CHECK_NO_MATCH ("foo bar", "foo()", NORMAL);
2757 CHECK_NO_MATCH ("foo bar", "foo bar()", NORMAL);
2758 CHECK_NO_MATCH ("foo()", "foo(a)", NORMAL);
2759 CHECK_NO_MATCH ("*(*)&", "*(*)*", NORMAL);
2760 CHECK_NO_MATCH ("foo(a)", "foo()", NORMAL);
2761 CHECK_NO_MATCH ("foo(a)", "foo(b)", NORMAL);
2762 CHECK_NO_MATCH ("foo(a,b)", "foo(a,b,c)", NORMAL);
2763 CHECK_NO_MATCH ("foo(a\\b)", "foo()", NORMAL);
2764 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar", NORMAL);
2765 CHECK_NO_MATCH ("foo bar(a b c d)", "foobar ( a b c \td\t)\t", NORMAL);
2766
2767 /* Test scope operator. */
2768 check_scope_operator (language_minimal);
2769 check_scope_operator (language_cplus);
2770 check_scope_operator (language_fortran);
2771 check_scope_operator (language_rust);
2772
2773 /* Test C++ user-defined operators. */
2774 CHECK_MATCH_LANG ("operator foo(int&)", "operator foo(int &)", NORMAL,
2775 language_cplus);
2776 CHECK_MATCH_LANG ("operator foo(int &)", "operator foo(int &)", NORMAL,
2777 language_cplus);
2778 CHECK_MATCH_LANG ("operator foo(int\t&)", "operator foo(int\t&)", NORMAL,
2779 language_cplus);
2780 CHECK_MATCH_LANG ("operator foo (int)", "operator foo(int)", NORMAL,
2781 language_cplus);
2782 CHECK_MATCH_LANG ("operator foo\t(int)", "operator foo(int)", NORMAL,
2783 language_cplus);
2784 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo(int)", NORMAL,
2785 language_cplus);
2786 CHECK_MATCH_LANG ("operator foo (int)", "operator foo \t(int)", NORMAL,
2787 language_cplus);
2788 CHECK_MATCH_LANG ("operator foo\t(int)", "operator foo \t(int)", NORMAL,
2789 language_cplus);
2790 CHECK_MATCH_LANG ("operator foo \t(int)", "operator foo \t(int)", NORMAL,
2791 language_cplus);
2792
2793 CHECK_MATCH_LANG ("a::operator foo(int&)", "a::operator foo(int &)", NORMAL,
2794 language_cplus);
2795 CHECK_MATCH_LANG ("a :: operator foo(int &)", "a::operator foo(int &)", NORMAL,
2796 language_cplus);
2797 CHECK_MATCH_LANG ("a \t:: \toperator foo(int\t&)", "a::operator foo(int\t&)", NORMAL,
2798 language_cplus);
2799 CHECK_MATCH_LANG ("a::operator foo (int)", "a::operator foo(int)", NORMAL,
2800 language_cplus);
2801 CHECK_MATCH_LANG ("a::operator foo\t(int)", "a::operator foo(int)", NORMAL,
2802 language_cplus);
2803 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo(int)", NORMAL,
2804 language_cplus);
2805 CHECK_MATCH_LANG ("a::operator foo (int)", "a::operator foo \t(int)", NORMAL,
2806 language_cplus);
2807 CHECK_MATCH_LANG ("a::operator foo\t(int)", "a::operator foo \t(int)", NORMAL,
2808 language_cplus);
2809 CHECK_MATCH_LANG ("a::operator foo \t(int)", "a::operator foo \t(int)", NORMAL,
2810 language_cplus);
2811
2812 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(char)", NORMAL,
2813 language_cplus);
2814 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int *)", NORMAL,
2815 language_cplus);
2816 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int &)", NORMAL,
2817 language_cplus);
2818 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator foo(int, char *)", NORMAL,
2819 language_cplus);
2820 CHECK_NO_MATCH_LANG ("operator foo(int)", "operator bar(int)", NORMAL,
2821 language_cplus);
2822
2823 CHECK_NO_MATCH_LANG ("a::operator b::foo(int)", "a::operator a::foo(char)", NORMAL,
2824 language_cplus);
2825 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int *)", NORMAL,
2826 language_cplus);
2827 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int &)", NORMAL,
2828 language_cplus);
2829 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator foo(int, char *)", NORMAL,
2830 language_cplus);
2831 CHECK_NO_MATCH_LANG ("a::operator foo(int)", "a::operator bar(int)", NORMAL,
2832 language_cplus);
2833
2834 /* Skip "[abi:cxx11]" tags in the symbol name if the lookup name
2835 doesn't include them. These are not language-specific in
2836 strncmp_iw_with_mode. */
2837
2838 CHECK_MATCH ("foo[abi:a]", "foo", NORMAL);
2839 CHECK_MATCH ("foo[abi:a]()", "foo", NORMAL);
2840 CHECK_MATCH ("foo[abi:a](a)", "foo", NORMAL);
2841 CHECK_MATCH ("foo[abi:a](a&,b*)", "foo", NORMAL);
2842 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2843 CHECK_MATCH ("foo[abi:a](a,b) c", "foo(a,b) c", NORMAL);
2844 CHECK_MATCH ("foo[abi:a](a)", "foo(a)", NORMAL);
2845 CHECK_MATCH ("foo[abi:a](a,b)", "foo(a,b)", NORMAL);
2846 CHECK_MATCH ("foo[abi:a]", "foo[abi:a]", NORMAL);
2847 CHECK_MATCH ("foo[ abi:a]", "foo[abi:a]", NORMAL);
2848 CHECK_MATCH ("foo[\tabi:a]", "foo[abi:a]", NORMAL);
2849 CHECK_MATCH ("foo[ \tabi:a]", "foo[abi:a]", NORMAL);
2850 CHECK_MATCH ("foo[\t abi:a]", "foo[abi:a]", NORMAL);
2851 CHECK_MATCH ("foo[abi :a]", "foo[abi:a]", NORMAL);
2852 CHECK_MATCH ("foo[abi\t:a]", "foo[abi:a]", NORMAL);
2853 CHECK_MATCH ("foo[abi \t:a]", "foo[abi:a]", NORMAL);
2854 CHECK_MATCH ("foo[abi\t :a]", "foo[abi:a]", NORMAL);
2855 CHECK_MATCH ("foo[abi:a]", "foo[ abi:a]", NORMAL);
2856 CHECK_MATCH ("foo[abi:a]", "foo[\tabi:a]", NORMAL);
2857 CHECK_MATCH ("foo[abi:a]", "foo[ \tabi:a]", NORMAL);
2858 CHECK_MATCH ("foo[abi:a]", "foo[\t abi:a]", NORMAL);
2859 CHECK_MATCH ("foo[abi:a]", "foo[abi :a]", NORMAL);
2860 CHECK_MATCH ("foo[abi:a]", "foo[abi\t:a]", NORMAL);
2861 CHECK_MATCH ("foo[abi:a]", "foo[abi \t:a]", NORMAL);
2862 CHECK_MATCH ("foo[abi:a]", "foo[abi\t :a]", NORMAL);
2863 CHECK_MATCH ("foo[abi:a]", "foo[abi:a ]", NORMAL);
2864 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t]", NORMAL);
2865 CHECK_MATCH ("foo[abi:a]", "foo[abi:a \t]", NORMAL);
2866 CHECK_MATCH ("foo[abi:a]", "foo[abi:a\t ]", NORMAL);
2867 CHECK_MATCH ("foo[abi:a,b]", "foo[abi:a,b]", NORMAL);
2868 CHECK_MATCH ("foo[abi:::]", "foo[abi:::]", NORMAL);
2869 CHECK_MATCH ("foo[abi : : : ]", "foo[abi:::]", NORMAL);
2870 CHECK_MATCH ("foo[abi:::]", "foo[abi : : : ]", NORMAL);
2871 CHECK_MATCH ("foo[ \t abi \t:\t: : \t]",
2872 "foo[ abi : \t ::]",
2873 NORMAL);
2874 CHECK_MATCH ("foo< bar< baz< quxi > > >(int)", "foo<bar<baz<quxi>>>(int)",
2875 NORMAL);
2876 CHECK_MATCH ("\tfoo<\tbar<\tbaz\t<\tquxi\t>\t>\t>(int)",
2877 "foo<bar<baz<quxi>>>(int)", NORMAL);
2878 CHECK_MATCH (" \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)",
2879 "foo<bar<baz<quxi>>>(int)", NORMAL);
2880 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2881 "foo < bar < baz < quxi > > > (int)", NORMAL);
2882 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2883 "\tfoo\t<\tbar\t<\tbaz\t<\tquxi\t>\t>\t>\t(int)", NORMAL);
2884 CHECK_MATCH ("foo<bar<baz<quxi>>>(int)",
2885 " \tfoo \t< \tbar \t< \tbaz \t< \tquxi \t> \t> \t> \t( \tint \t)", NORMAL);
2886 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "fo", NORMAL);
2887 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo", NORMAL);
2888 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz>>::", NORMAL);
2889 CHECK_MATCH ("foo<bar<baz>>::foo(quxi &)", "foo<bar<baz> >::foo", NORMAL);
2890 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
2891 NORMAL);
2892 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", NORMAL);
2893 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar)", NORMAL);
2894 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar)", NORMAL);
2895 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo(bar[abi:c])", NORMAL);
2896 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a](bar[abi:c])", NORMAL);
2897 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar)", NORMAL);
2898 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c])",
2899 NORMAL);
2900 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo", NORMAL);
2901 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo()", NORMAL);
2902 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>", NORMAL);
2903 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz)", NORMAL);
2904 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:b])",
2905 NORMAL);
2906 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar>(char*, baz[abi:A])",
2907 NORMAL);
2908 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz)",
2909 NORMAL);
2910 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:A]>(char*, baz)",
2911 NORMAL);
2912 CHECK_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])", "foo<bar[abi:a]>(char*, baz[abi:b])",
2913 NORMAL);
2914 CHECK_NO_MATCH("foo<bar[abi:a]>(char *, baz[abi:b])",
2915 "foo<bar[abi:a]>(char*, baz[abi:B])", NORMAL);
2916
2917 CHECK_NO_MATCH ("foo", "foo[", NORMAL);
2918 CHECK_NO_MATCH ("foo", "foo[]", NORMAL);
2919 CHECK_NO_MATCH ("foo", "foo[ a]", NORMAL);
2920 CHECK_NO_MATCH ("foo", "foo[a ]", NORMAL);
2921 CHECK_NO_MATCH ("foo", "foo[ a ]", NORMAL);
2922 CHECK_NO_MATCH ("foo", "foo[\ta]", NORMAL);
2923 CHECK_NO_MATCH ("foo", "foo[a \t]", NORMAL);
2924 CHECK_NO_MATCH ("foo", "foo[a\t ]", NORMAL);
2925 CHECK_NO_MATCH ("foo", "foo[ \ta]", NORMAL);
2926 CHECK_NO_MATCH ("foo", "foo[\t a]", NORMAL);
2927 CHECK_NO_MATCH ("foo", "foo[ \ta \t]", NORMAL);
2928 CHECK_NO_MATCH ("foo", "foo[\t a\t ]", NORMAL);
2929 CHECK_NO_MATCH ("foo", "foo[abi]", NORMAL);
2930 CHECK_NO_MATCH ("foo", "foo[ abi]", NORMAL);
2931 CHECK_NO_MATCH ("foo", "foo[abi ]", NORMAL);
2932 CHECK_NO_MATCH ("foo", "foo[\tabi]", NORMAL);
2933 CHECK_NO_MATCH ("foo", "foo[abi\t]", NORMAL);
2934 CHECK_NO_MATCH ("foo", "foo[ \tabi]", NORMAL);
2935 CHECK_NO_MATCH ("foo", "foo[\t abi]", NORMAL);
2936 CHECK_NO_MATCH ("foo", "foo[abi \t]", NORMAL);
2937 CHECK_NO_MATCH ("foo", "foo[abi\t ]", NORMAL);
2938 CHECK_NO_MATCH ("foo", "foo[abi :]", 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\t :]", NORMAL);
2942 CHECK_NO_MATCH ("foo", "foo[abi: ]", NORMAL);
2943 CHECK_NO_MATCH ("foo", "foo[abi:\t]", NORMAL);
2944 CHECK_NO_MATCH ("foo", "foo[abi: \t]", NORMAL);
2945 CHECK_NO_MATCH ("foo", "foo[abi:\t ]", NORMAL);
2946 CHECK_NO_MATCH ("foo", "foo[abi: a]", NORMAL);
2947 CHECK_NO_MATCH ("foo", "foo[abi:\ta]", NORMAL);
2948 CHECK_NO_MATCH ("foo", "foo[abi: \ta]", NORMAL);
2949 CHECK_NO_MATCH ("foo", "foo[abi:\t a]", NORMAL);
2950 CHECK_NO_MATCH ("foo", "foo[abi:a ]", NORMAL);
2951 CHECK_NO_MATCH ("foo", "foo[abi:a\t]", NORMAL);
2952 CHECK_NO_MATCH ("foo", "foo[abi:a \t]", NORMAL);
2953 CHECK_NO_MATCH ("foo", "foo[abi:a\t ]", 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]()", "foo(a)", NORMAL);
2958 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) c", NORMAL);
2959 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) .", NORMAL);
2960 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) *", NORMAL);
2961 CHECK_NO_MATCH ("foo[abi:a]()", "foo(a) &", NORMAL);
2962 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b) c", 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)", "foo(a,b) &", NORMAL);
2966 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)c", NORMAL);
2967 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b).", NORMAL);
2968 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)*", NORMAL);
2969 CHECK_NO_MATCH ("foo[abi:a](a,b)", "foo(a,b)&", NORMAL);
2970 CHECK_NO_MATCH ("foo[abi:a](a,b) d", "foo(a,b) c", NORMAL);
2971 CHECK_NO_MATCH ("foo[abi:a](a)", "foo()", NORMAL);
2972 CHECK_NO_MATCH ("foo[abi:a](a)", "foo(b)", NORMAL);
2973 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:b](a)", NORMAL);
2974 CHECK_NO_MATCH ("foo[abi:a](a)", "foo[abi:a](b)", NORMAL);
2975 CHECK_NO_MATCH ("foo[abi:]", "foo[abi:a]", NORMAL);
2976 CHECK_NO_MATCH ("foo[abi:", "foo[abi:a]", NORMAL);
2977 CHECK_NO_MATCH ("foo[abi:]", "foo[abi:a", NORMAL);
2978 CHECK_NO_MATCH ("foo[abi:,]", "foo[abi:a]", NORMAL);
2979 CHECK_NO_MATCH ("foo[abi:a,b]", "foo[abi:a]", NORMAL);
2980 CHECK_NO_MATCH ("foo[abi::a]", "foo[abi:a]", NORMAL);
2981 CHECK_NO_MATCH ("foo[abi:,([a]", "foo[abi:a]", NORMAL);
2982
2983 CHECK_MATCH ("foo <a, b [, c (", "foo", NORMAL);
2984 CHECK_MATCH ("foo >a, b ], c )", "foo", NORMAL);
2985 CHECK_MATCH ("@!%&\\*", "@!%&\\*", NORMAL);
2986 CHECK_MATCH ("()", "()", NORMAL);
2987 CHECK_MATCH ("*(*)*", "*(*)*", NORMAL);
2988 CHECK_MATCH ("[]", "[]", NORMAL);
2989 CHECK_MATCH ("<>", "<>", NORMAL);
2990
2991 /* strncmp_iw_with_mode::MATCH_PARAMS: the "strcmp_iw hack." */
2992 CHECK_MATCH ("foo2", "foo", NORMAL);
2993 CHECK_NO_MATCH ("foo2", "foo", MATCH_PARAMS);
2994 CHECK_NO_MATCH ("foo2", "foo ", MATCH_PARAMS);
2995 CHECK_NO_MATCH ("foo2", "foo\t", MATCH_PARAMS);
2996 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2997 CHECK_NO_MATCH ("foo2", "foo\t ", MATCH_PARAMS);
2998 CHECK_NO_MATCH ("foo2", "foo \t", MATCH_PARAMS);
2999 CHECK_NO_MATCH ("foo2", " foo", MATCH_PARAMS);
3000 CHECK_NO_MATCH ("foo2", "\tfoo", MATCH_PARAMS);
3001 CHECK_NO_MATCH ("foo2", " \tfoo", MATCH_PARAMS);
3002 CHECK_NO_MATCH ("foo2", "\t foo", MATCH_PARAMS);
3003 CHECK_NO_MATCH (" foo2", "foo", MATCH_PARAMS);
3004 CHECK_NO_MATCH ("\tfoo2", "foo", MATCH_PARAMS);
3005 CHECK_NO_MATCH (" \tfoo2", "foo", MATCH_PARAMS);
3006 CHECK_NO_MATCH ("\t foo2", "foo", MATCH_PARAMS);
3007 CHECK_NO_MATCH (" foo2 ", " foo ", MATCH_PARAMS);
3008 CHECK_NO_MATCH ("\tfoo2\t", "\tfoo\t", MATCH_PARAMS);
3009 CHECK_NO_MATCH (" \tfoo2 \t", " \tfoo \t", MATCH_PARAMS);
3010 CHECK_NO_MATCH ("\t foo2\t ", "\t foo\t ", MATCH_PARAMS);
3011 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
3012 CHECK_NO_MATCH ("foo2\t", "foo", MATCH_PARAMS);
3013 CHECK_NO_MATCH ("foo2 ", "foo", MATCH_PARAMS);
3014 CHECK_NO_MATCH ("foo2 \t", "foo", MATCH_PARAMS);
3015 CHECK_NO_MATCH ("foo2\t ", "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\t(args)", "foo", MATCH_PARAMS);
3019 CHECK_NO_MATCH ("foo2 \t(args)", "foo", MATCH_PARAMS);
3020 CHECK_NO_MATCH ("foo2\t (args)", "foo", MATCH_PARAMS);
3021 CHECK_NO_MATCH ("foo2 ( args)", "foo", MATCH_PARAMS);
3022 CHECK_NO_MATCH ("foo2(args )", "foo", MATCH_PARAMS);
3023 CHECK_NO_MATCH ("foo2(args\t)", "foo", MATCH_PARAMS);
3024 CHECK_NO_MATCH ("foo2 (args \t)", "foo", MATCH_PARAMS);
3025 CHECK_NO_MATCH ("foo2 (args\t )", "foo", MATCH_PARAMS);
3026 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo[abi:a][abi:b](bar[abi:c][abi:d])",
3027 MATCH_PARAMS);
3028 CHECK_MATCH ("foo[abi:a][abi:b](bar[abi:c][abi:d])", "foo", MATCH_PARAMS);
f0bdf68d
AB
3029 CHECK_NO_MATCH ("foo(args)@plt", "foo", MATCH_PARAMS);
3030 CHECK_NO_MATCH ("foo((())args(()))@plt", "foo", MATCH_PARAMS);
3031 CHECK_MATCH ("foo((())args(()))", "foo", MATCH_PARAMS);
3032 CHECK_MATCH ("foo(args) const", "foo", MATCH_PARAMS);
3033 CHECK_MATCH ("foo(args)const", "foo", MATCH_PARAMS);
b05752c2
KS
3034
3035 /* strncmp_iw_with_mode also supports case insensitivity. */
3036 {
3037 CHECK_NO_MATCH ("FoO", "foo", NORMAL);
3038 CHECK_NO_MATCH ("FoO", "foo", MATCH_PARAMS);
3039
3040 scoped_restore restore_case = make_scoped_restore (&case_sensitivity);
3041 case_sensitivity = case_sensitive_off;
3042
3043 CHECK_MATCH ("FoO", "foo", NORMAL);
3044 CHECK_MATCH ("FoO", "foo", MATCH_PARAMS);
3045 CHECK_MATCH ("foo", "FoO", NORMAL);
3046 CHECK_MATCH ("foo", "FoO", MATCH_PARAMS);
3047
3048 CHECK_MATCH ("FoO[AbI:abC]()", "foo", NORMAL);
3049 CHECK_NO_MATCH ("FoO[AbI:abC]()", "foo", MATCH_PARAMS);
3050 CHECK_MATCH ("FoO2[AbI:abC]()", "foo", NORMAL);
3051 CHECK_NO_MATCH ("FoO2[AbI:abC]()", "foo", MATCH_PARAMS);
3052
3053 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:abC]()", NORMAL);
3054 CHECK_MATCH ("foo[abi:abc]()", "FoO[AbI:AbC]()", MATCH_PARAMS);
3055 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3056 CHECK_MATCH ("foo[abi:abc](xyz)", "FoO[AbI:abC](XyZ)", MATCH_PARAMS);
3057 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)", NORMAL);
3058 CHECK_MATCH ("foo[abi:abc][abi:def](xyz)", "FoO[AbI:abC](XyZ)",
3059 MATCH_PARAMS);
3060 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3061 NORMAL);
3062 CHECK_MATCH ("foo<bar<baz>>(bar<baz>)", "FoO<bAr<BaZ>>(bAr<BaZ>)",
3063 MATCH_PARAMS);
3064 }
3065}
3066
3067#undef MATCH
3068#undef NO_MATCH
3069#endif
3070
1d550c82
PA
3071/* See utils.h. */
3072
3073int
3074strncmp_iw (const char *string1, const char *string2, size_t string2_len)
3075{
3076 return strncmp_iw_with_mode (string1, string2, string2_len,
0662b6a7 3077 strncmp_iw_mode::NORMAL, language_minimal);
1d550c82
PA
3078}
3079
3080/* See utils.h. */
3081
3082int
3083strcmp_iw (const char *string1, const char *string2)
3084{
3085 return strncmp_iw_with_mode (string1, string2, strlen (string2),
0662b6a7 3086 strncmp_iw_mode::MATCH_PARAMS, language_minimal);
c906108c 3087}
2de7ced7 3088
0fe19209
DC
3089/* This is like strcmp except that it ignores whitespace and treats
3090 '(' as the first non-NULL character in terms of ordering. Like
3091 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
3092 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
3093 according to that ordering.
3094
3095 If a list is sorted according to this function and if you want to
3096 find names in the list that match some fixed NAME according to
3097 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
3098 where this function would put NAME.
3099
559a7a62
JK
3100 This function must be neutral to the CASE_SENSITIVITY setting as the user
3101 may choose it during later lookup. Therefore this function always sorts
3102 primarily case-insensitively and secondarily case-sensitively.
3103
0fe19209
DC
3104 Here are some examples of why using strcmp to sort is a bad idea:
3105
3106 Whitespace example:
3107
3108 Say your partial symtab contains: "foo<char *>", "goo". Then, if
3109 we try to do a search for "foo<char*>", strcmp will locate this
3110 after "foo<char *>" and before "goo". Then lookup_partial_symbol
3111 will start looking at strings beginning with "goo", and will never
3112 see the correct match of "foo<char *>".
3113
3114 Parenthesis example:
3115
3116 In practice, this is less like to be an issue, but I'll give it a
3117 shot. Let's assume that '$' is a legitimate character to occur in
3118 symbols. (Which may well even be the case on some systems.) Then
3119 say that the partial symbol table contains "foo$" and "foo(int)".
3120 strcmp will put them in this order, since '$' < '('. Now, if the
3121 user searches for "foo", then strcmp will sort "foo" before "foo$".
3122 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
3123 "foo") is false, so it won't proceed to the actual match of
3124 "foo(int)" with "foo". */
3125
3126int
3127strcmp_iw_ordered (const char *string1, const char *string2)
3128{
559a7a62
JK
3129 const char *saved_string1 = string1, *saved_string2 = string2;
3130 enum case_sensitivity case_pass = case_sensitive_off;
3131
3132 for (;;)
0fe19209 3133 {
b11b1f88
JK
3134 /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
3135 Provide stub characters if we are already at the end of one of the
3136 strings. */
3137 char c1 = 'X', c2 = 'X';
3138
3139 while (*string1 != '\0' && *string2 != '\0')
0fe19209 3140 {
51e2cfa2 3141 while (ISSPACE (*string1))
b11b1f88 3142 string1++;
51e2cfa2 3143 while (ISSPACE (*string2))
b11b1f88
JK
3144 string2++;
3145
559a7a62
JK
3146 switch (case_pass)
3147 {
3148 case case_sensitive_off:
51e2cfa2
PA
3149 c1 = TOLOWER ((unsigned char) *string1);
3150 c2 = TOLOWER ((unsigned char) *string2);
559a7a62
JK
3151 break;
3152 case case_sensitive_on:
b11b1f88
JK
3153 c1 = *string1;
3154 c2 = *string2;
559a7a62
JK
3155 break;
3156 }
b11b1f88
JK
3157 if (c1 != c2)
3158 break;
3159
3160 if (*string1 != '\0')
3161 {
3162 string1++;
3163 string2++;
3164 }
0fe19209 3165 }
b11b1f88
JK
3166
3167 switch (*string1)
0fe19209 3168 {
b11b1f88
JK
3169 /* Characters are non-equal unless they're both '\0'; we want to
3170 make sure we get the comparison right according to our
3171 comparison in the cases where one of them is '\0' or '('. */
3172 case '\0':
3173 if (*string2 == '\0')
559a7a62 3174 break;
b11b1f88
JK
3175 else
3176 return -1;
3177 case '(':
3178 if (*string2 == '\0')
3179 return 1;
3180 else
3181 return -1;
3182 default:
3183 if (*string2 == '\0' || *string2 == '(')
3184 return 1;
559a7a62
JK
3185 else if (c1 > c2)
3186 return 1;
3187 else if (c1 < c2)
3188 return -1;
3189 /* PASSTHRU */
0fe19209 3190 }
559a7a62
JK
3191
3192 if (case_pass == case_sensitive_on)
3193 return 0;
3194
3195 /* Otherwise the strings were equal in case insensitive way, make
3196 a more fine grained comparison in a case sensitive way. */
3197
3198 case_pass = case_sensitive_on;
3199 string1 = saved_string1;
3200 string2 = saved_string2;
0fe19209 3201 }
0fe19209
DC
3202}
3203
c906108c 3204\f
c5aa993b 3205
75feb17d
DJ
3206static void
3207show_debug_timestamp (struct ui_file *file, int from_tty,
3208 struct cmd_list_element *c, const char *value)
3209{
6cb06a8c
TT
3210 gdb_printf (file, _("Timestamping debugging messages is %s.\n"),
3211 value);
75feb17d 3212}
c906108c 3213\f
c5aa993b 3214
66bf4b3a 3215const char *
5af949e3 3216paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
66bf4b3a
AC
3217{
3218 /* Truncate address to the size of a target address, avoiding shifts
3219 larger or equal than the width of a CORE_ADDR. The local
3220 variable ADDR_BIT stops the compiler reporting a shift overflow
581e13c1 3221 when it won't occur. */
66bf4b3a
AC
3222 /* NOTE: This assumes that the significant address information is
3223 kept in the least significant bits of ADDR - the upper bits were
76e71323 3224 either zero or sign extended. Should gdbarch_address_to_pointer or
66bf4b3a
AC
3225 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
3226
5af949e3 3227 int addr_bit = gdbarch_addr_bit (gdbarch);
66bf4b3a
AC
3228
3229 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3230 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
3231 return hex_string (addr);
3232}
3233
f1310107
TJB
3234/* This function is described in "defs.h". */
3235
3236const char *
3237print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
3238{
3239 int addr_bit = gdbarch_addr_bit (gdbarch);
3240
3241 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3242 address &= ((CORE_ADDR) 1 << addr_bit) - 1;
3243
3244 /* FIXME: cagney/2002-05-03: Need local_address_string() function
3245 that returns the language localized string formatted to a width
3246 based on gdbarch_addr_bit. */
3247 if (addr_bit <= 32)
3248 return hex_string_custom (address, 8);
3249 else
3250 return hex_string_custom (address, 16);
3251}
3252
03dd37c3
AC
3253/* Convert a string back into a CORE_ADDR. */
3254CORE_ADDR
3255string_to_core_addr (const char *my_string)
3256{
3257 CORE_ADDR addr = 0;
9544c605 3258
51e2cfa2 3259 if (my_string[0] == '0' && TOLOWER (my_string[1]) == 'x')
03dd37c3 3260 {
ced572fe 3261 /* Assume that it is in hex. */
03dd37c3 3262 int i;
5d502164 3263
03dd37c3
AC
3264 for (i = 2; my_string[i] != '\0'; i++)
3265 {
51e2cfa2 3266 if (ISDIGIT (my_string[i]))
03dd37c3 3267 addr = (my_string[i] - '0') + (addr * 16);
51e2cfa2
PA
3268 else if (ISXDIGIT (my_string[i]))
3269 addr = (TOLOWER (my_string[i]) - 'a' + 0xa) + (addr * 16);
03dd37c3 3270 else
63f06803 3271 error (_("invalid hex \"%s\""), my_string);
03dd37c3
AC
3272 }
3273 }
3274 else
3275 {
3276 /* Assume that it is in decimal. */
3277 int i;
5d502164 3278
03dd37c3
AC
3279 for (i = 0; my_string[i] != '\0'; i++)
3280 {
51e2cfa2 3281 if (ISDIGIT (my_string[i]))
03dd37c3
AC
3282 addr = (my_string[i] - '0') + (addr * 10);
3283 else
63f06803 3284 error (_("invalid decimal \"%s\""), my_string);
03dd37c3
AC
3285 }
3286 }
9544c605 3287
03dd37c3
AC
3288 return addr;
3289}
58d370e0 3290
14278e1f
TT
3291#if GDB_SELF_TEST
3292
3293static void
3294gdb_realpath_check_trailer (const char *input, const char *trailer)
3295{
3296 gdb::unique_xmalloc_ptr<char> result = gdb_realpath (input);
3297
3298 size_t len = strlen (result.get ());
3299 size_t trail_len = strlen (trailer);
3300
3301 SELF_CHECK (len >= trail_len
3302 && strcmp (result.get () + len - trail_len, trailer) == 0);
3303}
3304
3305static void
3306gdb_realpath_tests ()
3307{
3308 /* A file which contains a directory prefix. */
3309 gdb_realpath_check_trailer ("./xfullpath.exp", "/xfullpath.exp");
3310 /* A file which contains a directory prefix. */
3311 gdb_realpath_check_trailer ("../../defs.h", "/defs.h");
3312 /* A one-character filename. */
3313 gdb_realpath_check_trailer ("./a", "/a");
3314 /* A file in the root directory. */
3315 gdb_realpath_check_trailer ("/root_file_which_should_exist",
3316 "/root_file_which_should_exist");
3317 /* A file which does not have a directory prefix. */
3318 gdb_realpath_check_trailer ("xfullpath.exp", "xfullpath.exp");
3319 /* A one-char filename without any directory prefix. */
3320 gdb_realpath_check_trailer ("a", "a");
3321 /* An empty filename. */
3322 gdb_realpath_check_trailer ("", "");
3323}
3324
d369b608
SM
3325/* Test the gdb_argv::as_array_view method. */
3326
3327static void
3328gdb_argv_as_array_view_test ()
3329{
3330 {
3331 gdb_argv argv;
3332
3333 gdb::array_view<char *> view = argv.as_array_view ();
3334
3335 SELF_CHECK (view.data () == nullptr);
3336 SELF_CHECK (view.size () == 0);
3337 }
3338 {
3339 gdb_argv argv ("une bonne 50");
3340
3341 gdb::array_view<char *> view = argv.as_array_view ();
3342
3343 SELF_CHECK (view.size () == 3);
3344 SELF_CHECK (strcmp (view[0], "une") == 0);
3345 SELF_CHECK (strcmp (view[1], "bonne") == 0);
3346 SELF_CHECK (strcmp (view[2], "50") == 0);
3347 }
3348}
3349
14278e1f
TT
3350#endif /* GDB_SELF_TEST */
3351
e1024ff1
DJ
3352/* Simple, portable version of dirname that does not modify its
3353 argument. */
3354
d721ba37 3355std::string
a22a215f 3356gdb_ldirname (const char *filename)
e1024ff1 3357{
d721ba37 3358 std::string dirname;
e1024ff1 3359 const char *base = lbasename (filename);
e1024ff1
DJ
3360
3361 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3362 --base;
3363
3364 if (base == filename)
d721ba37 3365 return dirname;
e1024ff1 3366
d721ba37 3367 dirname = std::string (filename, base - filename);
e1024ff1
DJ
3368
3369 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3370 create "d:./bar" later instead of the (different) "d:/bar". */
3371 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3372 && !IS_DIR_SEPARATOR (filename[0]))
3373 dirname[base++ - filename] = '.';
3374
e1024ff1
DJ
3375 return dirname;
3376}
d1a41061 3377
74164c56
JK
3378/* Return ARGS parsed as a valid pid, or throw an error. */
3379
3380int
c0939df1 3381parse_pid_to_attach (const char *args)
74164c56
JK
3382{
3383 unsigned long pid;
3384 char *dummy;
3385
3386 if (!args)
3387 error_no_arg (_("process-id to attach"));
3388
c0939df1 3389 dummy = (char *) args;
74164c56
JK
3390 pid = strtoul (args, &dummy, 0);
3391 /* Some targets don't set errno on errors, grrr! */
3392 if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3393 error (_("Illegal process-id: %s."), args);
3394
3395 return pid;
3396}
3397
0b6cb71e
DE
3398#ifdef HAVE_WAITPID
3399
3400#ifdef SIGALRM
3401
3402/* SIGALRM handler for waitpid_with_timeout. */
3403
3404static void
3405sigalrm_handler (int signo)
3406{
3407 /* Nothing to do. */
3408}
3409
3410#endif
3411
3412/* Wrapper to wait for child PID to die with TIMEOUT.
3413 TIMEOUT is the time to stop waiting in seconds.
3414 If TIMEOUT is zero, pass WNOHANG to waitpid.
3415 Returns PID if it was successfully waited for, otherwise -1.
3416
3417 Timeouts are currently implemented with alarm and SIGALRM.
3418 If the host does not support them, this waits "forever".
3419 It would be odd though for a host to have waitpid and not SIGALRM. */
3420
3421pid_t
3422wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3423{
3424 pid_t waitpid_result;
3425
3426 gdb_assert (pid > 0);
3427 gdb_assert (timeout >= 0);
3428
3429 if (timeout > 0)
3430 {
3431#ifdef SIGALRM
3cfa137c 3432 scoped_signal_handler<SIGALRM> alarm_restore (sigalrm_handler);
0b6cb71e
DE
3433
3434 alarm (timeout);
3435#endif
3436
a9791f14 3437 waitpid_result = gdb::waitpid (pid, status, 0);
0b6cb71e
DE
3438
3439#ifdef SIGALRM
3440 alarm (0);
0b6cb71e
DE
3441#endif
3442 }
3443 else
a9791f14 3444 waitpid_result = gdb::waitpid (pid, status, WNOHANG);
0b6cb71e
DE
3445
3446 if (waitpid_result == pid)
3447 return pid;
3448 else
3449 return -1;
3450}
3451
3452#endif /* HAVE_WAITPID */
3453
02646a4c
FS
3454/* Provide fnmatch compatible function for matching of host files.
3455 FNM_NOESCAPE must be set in FLAGS.
202cbf1c
JK
3456
3457 It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3458 HAVE_CASE_INSENSITIVE_FILE_SYSTEM. */
3459
3460int
3461gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3462{
202cbf1c
JK
3463 /* It is unclear how '\' escaping vs. directory separator should coexist. */
3464 gdb_assert ((flags & FNM_NOESCAPE) != 0);
3465
3466#ifdef HAVE_DOS_BASED_FILE_SYSTEM
3467 {
3468 char *pattern_slash, *string_slash;
3469
3470 /* Replace '\' by '/' in both strings. */
3471
0ae1c716 3472 pattern_slash = (char *) alloca (strlen (pattern) + 1);
202cbf1c
JK
3473 strcpy (pattern_slash, pattern);
3474 pattern = pattern_slash;
3475 for (; *pattern_slash != 0; pattern_slash++)
3476 if (IS_DIR_SEPARATOR (*pattern_slash))
3477 *pattern_slash = '/';
3478
0ae1c716 3479 string_slash = (char *) alloca (strlen (string) + 1);
202cbf1c
JK
3480 strcpy (string_slash, string);
3481 string = string_slash;
3482 for (; *string_slash != 0; string_slash++)
3483 if (IS_DIR_SEPARATOR (*string_slash))
3484 *string_slash = '/';
3485 }
3486#endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3487
3488#ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3489 flags |= FNM_CASEFOLD;
3490#endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3491
3492 return fnmatch (pattern, string, flags);
3493}
3494
cce0e923
DE
3495/* Return the number of path elements in PATH.
3496 / = 1
3497 /foo = 2
3498 /foo/ = 2
3499 foo/bar = 2
3500 foo/ = 1 */
3501
3502int
3503count_path_elements (const char *path)
3504{
3505 int count = 0;
3506 const char *p = path;
3507
3508 if (HAS_DRIVE_SPEC (p))
3509 {
3510 p = STRIP_DRIVE_SPEC (p);
3511 ++count;
3512 }
3513
3514 while (*p != '\0')
3515 {
3516 if (IS_DIR_SEPARATOR (*p))
3517 ++count;
3518 ++p;
3519 }
3520
3521 /* Backup one if last character is /, unless it's the only one. */
3522 if (p > path + 1 && IS_DIR_SEPARATOR (p[-1]))
3523 --count;
3524
3525 /* Add one for the file name, if present. */
3526 if (p > path && !IS_DIR_SEPARATOR (p[-1]))
3527 ++count;
3528
3529 return count;
3530}
3531
3532/* Remove N leading path elements from PATH.
3533 N must be non-negative.
3534 If PATH has more than N path elements then return NULL.
3535 If PATH has exactly N path elements then return "".
3536 See count_path_elements for a description of how we do the counting. */
3537
3538const char *
3539strip_leading_path_elements (const char *path, int n)
3540{
3541 int i = 0;
3542 const char *p = path;
3543
3544 gdb_assert (n >= 0);
3545
3546 if (n == 0)
3547 return p;
3548
3549 if (HAS_DRIVE_SPEC (p))
3550 {
3551 p = STRIP_DRIVE_SPEC (p);
3552 ++i;
3553 }
3554
3555 while (i < n)
3556 {
3557 while (*p != '\0' && !IS_DIR_SEPARATOR (*p))
3558 ++p;
3559 if (*p == '\0')
3560 {
3561 if (i + 1 == n)
3562 return "";
3563 return NULL;
3564 }
3565 ++p;
3566 ++i;
3567 }
3568
3569 return p;
3570}
3571
a99bc3d2
JB
3572/* See utils.h. */
3573
3574void
3575copy_bitwise (gdb_byte *dest, ULONGEST dest_offset,
3576 const gdb_byte *source, ULONGEST source_offset,
3577 ULONGEST nbits, int bits_big_endian)
3578{
3579 unsigned int buf, avail;
3580
3581 if (nbits == 0)
3582 return;
3583
3584 if (bits_big_endian)
3585 {
3586 /* Start from the end, then work backwards. */
3587 dest_offset += nbits - 1;
3588 dest += dest_offset / 8;
3589 dest_offset = 7 - dest_offset % 8;
3590 source_offset += nbits - 1;
3591 source += source_offset / 8;
3592 source_offset = 7 - source_offset % 8;
3593 }
3594 else
3595 {
3596 dest += dest_offset / 8;
3597 dest_offset %= 8;
3598 source += source_offset / 8;
3599 source_offset %= 8;
3600 }
3601
3602 /* Fill BUF with DEST_OFFSET bits from the destination and 8 -
3603 SOURCE_OFFSET bits from the source. */
3604 buf = *(bits_big_endian ? source-- : source++) >> source_offset;
3605 buf <<= dest_offset;
3606 buf |= *dest & ((1 << dest_offset) - 1);
3607
3608 /* NBITS: bits yet to be written; AVAIL: BUF's fill level. */
3609 nbits += dest_offset;
3610 avail = dest_offset + 8 - source_offset;
3611
3612 /* Flush 8 bits from BUF, if appropriate. */
3613 if (nbits >= 8 && avail >= 8)
3614 {
3615 *(bits_big_endian ? dest-- : dest++) = buf;
3616 buf >>= 8;
3617 avail -= 8;
3618 nbits -= 8;
3619 }
3620
3621 /* Copy the middle part. */
3622 if (nbits >= 8)
3623 {
3624 size_t len = nbits / 8;
3625
3626 /* Use a faster method for byte-aligned copies. */
3627 if (avail == 0)
3628 {
3629 if (bits_big_endian)
3630 {
3631 dest -= len;
3632 source -= len;
3633 memcpy (dest + 1, source + 1, len);
3634 }
3635 else
3636 {
3637 memcpy (dest, source, len);
3638 dest += len;
3639 source += len;
3640 }
3641 }
3642 else
3643 {
3644 while (len--)
3645 {
3646 buf |= *(bits_big_endian ? source-- : source++) << avail;
3647 *(bits_big_endian ? dest-- : dest++) = buf;
3648 buf >>= 8;
3649 }
3650 }
3651 nbits %= 8;
3652 }
3653
3654 /* Write the last byte. */
3655 if (nbits)
3656 {
3657 if (avail < nbits)
3658 buf |= *source << avail;
3659
3660 buf &= (1 << nbits) - 1;
cf83625d 3661 *dest = (*dest & (~0U << nbits)) | buf;
a99bc3d2
JB
3662 }
3663}
3664
1217ae67
AB
3665/* See utils.h. */
3666
3667std::string
3668extract_single_filename_arg (const char *args)
3669{
3670 if (args == nullptr)
3671 return {};
3672
3673 std::string filename = extract_string_maybe_quoted (&args);
3674 args = skip_spaces (args);
3675 if (*args != '\0')
3676 error (_("Junk after filename \"%s\": %s"), filename.c_str (), args);
3677 if (!filename.empty ())
3678 filename = gdb_tilde_expand (filename.c_str ());
3679 return filename;
3680}
3681
2e12e798
TV
3682#if GDB_SELF_TEST
3683static void
3684test_assign_set_return_if_changed ()
3685{
3686 bool changed;
3687 int a;
3688
3689 for (bool initial : { false, true })
3690 {
3691 changed = initial;
3692 a = 1;
3693 assign_set_if_changed (a, 1, changed);
3694 SELF_CHECK (a == 1);
3695 SELF_CHECK (changed == initial);
3696 }
3697
3698 for (bool initial : { false, true })
3699 {
3700 changed = initial;
3701 a = 1;
3702 assign_set_if_changed (a, 2, changed);
3703 SELF_CHECK (a == 2);
3704 SELF_CHECK (changed == true);
3705 }
3706
3707 a = 1;
3708 changed = assign_return_if_changed (a, 1);
3709 SELF_CHECK (a == 1);
3710 SELF_CHECK (changed == false);
3711
3712 a = 1;
3713 assign_set_if_changed (a, 2, changed);
3714 SELF_CHECK (a == 2);
3715 SELF_CHECK (changed == true);
3716}
3717#endif
3718
5fe70629 3719INIT_GDB_FILE (utils)
3c16cced 3720{
12904d37
TT
3721 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
3722Set number of characters where GDB should wrap lines of its output."), _("\
3723Show number of characters where GDB should wrap lines of its output."), _("\
3724This affects where GDB wraps its output to fit the screen width.\n\
3725Setting this to \"unlimited\" or zero prevents GDB from wrapping its output."),
3726 set_width_command,
3727 show_chars_per_line,
3728 &setlist, &showlist);
3729
3730 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
3731Set number of lines in a page for GDB output pagination."), _("\
3732Show number of lines in a page for GDB output pagination."), _("\
3733This affects the number of lines after which GDB will pause\n\
3734its output and ask you whether to continue.\n\
3735Setting this to \"unlimited\" or zero causes GDB never pause during output."),
3736 set_height_command,
3737 show_lines_per_page,
3738 &setlist, &showlist);
3739
3740 add_setshow_boolean_cmd ("pagination", class_support,
3741 &pagination_enabled, _("\
3742Set state of GDB output pagination."), _("\
3743Show state of GDB output pagination."), _("\
3744When pagination is ON, GDB pauses at end of each screenful of\n\
3745its output and asks you whether to continue.\n\
3746Turning pagination off is an alternative to \"set height unlimited\"."),
3747 NULL,
3748 show_pagination_enabled,
3749 &setlist, &showlist);
3750
3751 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
3752 &sevenbit_strings, _("\
3753Set printing of 8-bit characters in strings as \\nnn."), _("\
3754Show printing of 8-bit characters in strings as \\nnn."), NULL,
3755 NULL,
3756 show_sevenbit_strings,
3757 &setprintlist, &showprintlist);
3758
3759 add_setshow_boolean_cmd ("timestamp", class_maintenance,
3760 &debug_timestamp, _("\
3761Set timestamping of debugging messages."), _("\
3762Show timestamping of debugging messages."), _("\
3763When set, debugging messages will be marked with seconds and microseconds."),
3764 NULL,
3765 show_debug_timestamp,
3766 &setdebuglist, &showdebuglist);
3767
3c16cced
PA
3768 add_internal_problem_command (&internal_error_problem);
3769 add_internal_problem_command (&internal_warning_problem);
57fcfb1b 3770 add_internal_problem_command (&demangler_warning_problem);
14278e1f 3771
f1531d04
TV
3772 add_cmd ("screen", class_maintenance, &maintenance_info_screen,
3773 _("Show screen characteristics."), &maintenanceinfolist);
3774
14278e1f 3775#if GDB_SELF_TEST
1526853e 3776 selftests::register_test ("gdb_realpath", gdb_realpath_tests);
d369b608 3777 selftests::register_test ("gdb_argv_array_view", gdb_argv_as_array_view_test);
b05752c2
KS
3778 selftests::register_test ("strncmp_iw_with_mode",
3779 strncmp_iw_with_mode_tests);
1f0f8b5d 3780 selftests::register_test ("pager", test_pager);
2e12e798
TV
3781 selftests::register_test ("assign_set_return_if_changed",
3782 test_assign_set_return_if_changed);
14278e1f 3783#endif
3c16cced 3784}