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