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