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