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