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