]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/completer.c
Fix latent bug in custom word point completion handling
[thirdparty/binutils-gdb.git] / gdb / completer.c
1 /* Line completion stuff for GDB, the GNU debugger.
2 Copyright (C) 2000-2019 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "defs.h"
20 #include "symtab.h"
21 #include "gdbtypes.h"
22 #include "expression.h"
23 #include "filenames.h" /* For DOSish file names. */
24 #include "language.h"
25 #include "common/gdb_signals.h"
26 #include "target.h"
27 #include "reggroups.h"
28 #include "user-regs.h"
29 #include "arch-utils.h"
30 #include "location.h"
31 #include <algorithm>
32 #include "linespec.h"
33 #include "cli/cli-decode.h"
34
35 /* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
37 #include "gdbcmd.h"
38
39 /* Needed for rl_completer_word_break_characters() and for
40 rl_filename_completion_function. */
41 #include "readline/readline.h"
42
43 /* readline defines this. */
44 #undef savestring
45
46 #include "completer.h"
47
48 /* Misc state that needs to be tracked across several different
49 readline completer entry point calls, all related to a single
50 completion invocation. */
51
52 struct gdb_completer_state
53 {
54 /* The current completion's completion tracker. This is a global
55 because a tracker can be shared between the handle_brkchars and
56 handle_completion phases, which involves different readline
57 callbacks. */
58 completion_tracker *tracker = NULL;
59
60 /* Whether the current completion was aborted. */
61 bool aborted = false;
62 };
63
64 /* The current completion state. */
65 static gdb_completer_state current_completion;
66
67 /* An enumeration of the various things a user might attempt to
68 complete for a location. If you change this, remember to update
69 the explicit_options array below too. */
70
71 enum explicit_location_match_type
72 {
73 /* The filename of a source file. */
74 MATCH_SOURCE,
75
76 /* The name of a function or method. */
77 MATCH_FUNCTION,
78
79 /* The fully-qualified name of a function or method. */
80 MATCH_QUALIFIED,
81
82 /* A line number. */
83 MATCH_LINE,
84
85 /* The name of a label. */
86 MATCH_LABEL
87 };
88
89 /* Prototypes for local functions. */
90
91 /* readline uses the word breaks for two things:
92 (1) In figuring out where to point the TEXT parameter to the
93 rl_completion_entry_function. Since we don't use TEXT for much,
94 it doesn't matter a lot what the word breaks are for this purpose,
95 but it does affect how much stuff M-? lists.
96 (2) If one of the matches contains a word break character, readline
97 will quote it. That's why we switch between
98 current_language->la_word_break_characters() and
99 gdb_completer_command_word_break_characters. I'm not sure when
100 we need this behavior (perhaps for funky characters in C++
101 symbols?). */
102
103 /* Variables which are necessary for fancy command line editing. */
104
105 /* When completing on command names, we remove '-' from the list of
106 word break characters, since we use it in command names. If the
107 readline library sees one in any of the current completion strings,
108 it thinks that the string needs to be quoted and automatically
109 supplies a leading quote. */
110 static const char gdb_completer_command_word_break_characters[] =
111 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
112
113 /* When completing on file names, we remove from the list of word
114 break characters any characters that are commonly used in file
115 names, such as '-', '+', '~', etc. Otherwise, readline displays
116 incorrect completion candidates. */
117 /* MS-DOS and MS-Windows use colon as part of the drive spec, and most
118 programs support @foo style response files. */
119 static const char gdb_completer_file_name_break_characters[] =
120 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
121 " \t\n*|\"';?><@";
122 #else
123 " \t\n*|\"';:?><";
124 #endif
125
126 /* Characters that can be used to quote completion strings. Note that
127 we can't include '"' because the gdb C parser treats such quoted
128 sequences as strings. */
129 static const char gdb_completer_quote_characters[] = "'";
130 \f
131 /* Accessor for some completer data that may interest other files. */
132
133 const char *
134 get_gdb_completer_quote_characters (void)
135 {
136 return gdb_completer_quote_characters;
137 }
138
139 /* This can be used for functions which don't want to complete on
140 symbols but don't want to complete on anything else either. */
141
142 void
143 noop_completer (struct cmd_list_element *ignore,
144 completion_tracker &tracker,
145 const char *text, const char *prefix)
146 {
147 }
148
149 /* Complete on filenames. */
150
151 void
152 filename_completer (struct cmd_list_element *ignore,
153 completion_tracker &tracker,
154 const char *text, const char *word)
155 {
156 int subsequent_name;
157
158 subsequent_name = 0;
159 while (1)
160 {
161 gdb::unique_xmalloc_ptr<char> p_rl
162 (rl_filename_completion_function (text, subsequent_name));
163 if (p_rl == NULL)
164 break;
165 /* We need to set subsequent_name to a non-zero value before the
166 continue line below, because otherwise, if the first file
167 seen by GDB is a backup file whose name ends in a `~', we
168 will loop indefinitely. */
169 subsequent_name = 1;
170 /* Like emacs, don't complete on old versions. Especially
171 useful in the "source" command. */
172 const char *p = p_rl.get ();
173 if (p[strlen (p) - 1] == '~')
174 continue;
175
176 tracker.add_completion
177 (make_completion_match_str (std::move (p_rl), text, word));
178 }
179 #if 0
180 /* There is no way to do this just long enough to affect quote
181 inserting without also affecting the next completion. This
182 should be fixed in readline. FIXME. */
183 /* Ensure that readline does the right thing
184 with respect to inserting quotes. */
185 rl_completer_word_break_characters = "";
186 #endif
187 }
188
189 /* The corresponding completer_handle_brkchars
190 implementation. */
191
192 static void
193 filename_completer_handle_brkchars (struct cmd_list_element *ignore,
194 completion_tracker &tracker,
195 const char *text, const char *word)
196 {
197 set_rl_completer_word_break_characters
198 (gdb_completer_file_name_break_characters);
199 }
200
201 /* Possible values for the found_quote flags word used by the completion
202 functions. It says what kind of (shell-like) quoting we found anywhere
203 in the line. */
204 #define RL_QF_SINGLE_QUOTE 0x01
205 #define RL_QF_DOUBLE_QUOTE 0x02
206 #define RL_QF_BACKSLASH 0x04
207 #define RL_QF_OTHER_QUOTE 0x08
208
209 /* Find the bounds of the current word for completion purposes, and
210 return a pointer to the end of the word. This mimics (and is a
211 modified version of) readline's _rl_find_completion_word internal
212 function.
213
214 This function skips quoted substrings (characters between matched
215 pairs of characters in rl_completer_quote_characters). We try to
216 find an unclosed quoted substring on which to do matching. If one
217 is not found, we use the word break characters to find the
218 boundaries of the current word. QC, if non-null, is set to the
219 opening quote character if we found an unclosed quoted substring,
220 '\0' otherwise. DP, if non-null, is set to the value of the
221 delimiter character that caused a word break. */
222
223 struct gdb_rl_completion_word_info
224 {
225 const char *word_break_characters;
226 const char *quote_characters;
227 const char *basic_quote_characters;
228 };
229
230 static const char *
231 gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
232 int *qc, int *dp,
233 const char *line_buffer)
234 {
235 int scan, end, found_quote, delimiter, pass_next, isbrk;
236 char quote_char;
237 const char *brkchars;
238 int point = strlen (line_buffer);
239
240 /* The algorithm below does '--point'. Avoid buffer underflow with
241 the empty string. */
242 if (point == 0)
243 {
244 if (qc != NULL)
245 *qc = '\0';
246 if (dp != NULL)
247 *dp = '\0';
248 return line_buffer;
249 }
250
251 end = point;
252 found_quote = delimiter = 0;
253 quote_char = '\0';
254
255 brkchars = info->word_break_characters;
256
257 if (info->quote_characters != NULL)
258 {
259 /* We have a list of characters which can be used in pairs to
260 quote substrings for the completer. Try to find the start of
261 an unclosed quoted substring. */
262 /* FOUND_QUOTE is set so we know what kind of quotes we
263 found. */
264 for (scan = pass_next = 0;
265 scan < end;
266 scan++)
267 {
268 if (pass_next)
269 {
270 pass_next = 0;
271 continue;
272 }
273
274 /* Shell-like semantics for single quotes -- don't allow
275 backslash to quote anything in single quotes, especially
276 not the closing quote. If you don't like this, take out
277 the check on the value of quote_char. */
278 if (quote_char != '\'' && line_buffer[scan] == '\\')
279 {
280 pass_next = 1;
281 found_quote |= RL_QF_BACKSLASH;
282 continue;
283 }
284
285 if (quote_char != '\0')
286 {
287 /* Ignore everything until the matching close quote
288 char. */
289 if (line_buffer[scan] == quote_char)
290 {
291 /* Found matching close. Abandon this
292 substring. */
293 quote_char = '\0';
294 point = end;
295 }
296 }
297 else if (strchr (info->quote_characters, line_buffer[scan]))
298 {
299 /* Found start of a quoted substring. */
300 quote_char = line_buffer[scan];
301 point = scan + 1;
302 /* Shell-like quoting conventions. */
303 if (quote_char == '\'')
304 found_quote |= RL_QF_SINGLE_QUOTE;
305 else if (quote_char == '"')
306 found_quote |= RL_QF_DOUBLE_QUOTE;
307 else
308 found_quote |= RL_QF_OTHER_QUOTE;
309 }
310 }
311 }
312
313 if (point == end && quote_char == '\0')
314 {
315 /* We didn't find an unclosed quoted substring upon which to do
316 completion, so use the word break characters to find the
317 substring on which to complete. */
318 while (--point)
319 {
320 scan = line_buffer[point];
321
322 if (strchr (brkchars, scan) != 0)
323 break;
324 }
325 }
326
327 /* If we are at an unquoted word break, then advance past it. */
328 scan = line_buffer[point];
329
330 if (scan)
331 {
332 isbrk = strchr (brkchars, scan) != 0;
333
334 if (isbrk)
335 {
336 /* If the character that caused the word break was a quoting
337 character, then remember it as the delimiter. */
338 if (info->basic_quote_characters
339 && strchr (info->basic_quote_characters, scan)
340 && (end - point) > 1)
341 delimiter = scan;
342
343 point++;
344 }
345 }
346
347 if (qc != NULL)
348 *qc = quote_char;
349 if (dp != NULL)
350 *dp = delimiter;
351
352 return line_buffer + point;
353 }
354
355 /* See completer.h. */
356
357 const char *
358 advance_to_expression_complete_word_point (completion_tracker &tracker,
359 const char *text)
360 {
361 gdb_rl_completion_word_info info;
362
363 info.word_break_characters
364 = current_language->la_word_break_characters ();
365 info.quote_characters = gdb_completer_quote_characters;
366 info.basic_quote_characters = rl_basic_quote_characters;
367
368 int delimiter;
369 const char *start
370 = gdb_rl_find_completion_word (&info, NULL, &delimiter, text);
371
372 tracker.advance_custom_word_point_by (start - text);
373
374 if (delimiter)
375 {
376 tracker.set_quote_char (delimiter);
377 tracker.set_suppress_append_ws (true);
378 }
379
380 return start;
381 }
382
383 /* See completer.h. */
384
385 bool
386 completion_tracker::completes_to_completion_word (const char *word)
387 {
388 if (m_lowest_common_denominator_unique)
389 {
390 const char *lcd = m_lowest_common_denominator;
391
392 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
393 {
394 /* Maybe skip the function and complete on keywords. */
395 size_t wordlen = strlen (word);
396 if (word[wordlen - 1] == ' ')
397 return true;
398 }
399 }
400
401 return false;
402 }
403
404 /* Complete on linespecs, which might be of two possible forms:
405
406 file:line
407 or
408 symbol+offset
409
410 This is intended to be used in commands that set breakpoints
411 etc. */
412
413 static void
414 complete_files_symbols (completion_tracker &tracker,
415 const char *text, const char *word)
416 {
417 completion_list fn_list;
418 const char *p;
419 int quote_found = 0;
420 int quoted = *text == '\'' || *text == '"';
421 int quote_char = '\0';
422 const char *colon = NULL;
423 char *file_to_match = NULL;
424 const char *symbol_start = text;
425 const char *orig_text = text;
426
427 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
428 for (p = text; *p != '\0'; ++p)
429 {
430 if (*p == '\\' && p[1] == '\'')
431 p++;
432 else if (*p == '\'' || *p == '"')
433 {
434 quote_found = *p;
435 quote_char = *p++;
436 while (*p != '\0' && *p != quote_found)
437 {
438 if (*p == '\\' && p[1] == quote_found)
439 p++;
440 p++;
441 }
442
443 if (*p == quote_found)
444 quote_found = 0;
445 else
446 break; /* Hit the end of text. */
447 }
448 #if HAVE_DOS_BASED_FILE_SYSTEM
449 /* If we have a DOS-style absolute file name at the beginning of
450 TEXT, and the colon after the drive letter is the only colon
451 we found, pretend the colon is not there. */
452 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
453 ;
454 #endif
455 else if (*p == ':' && !colon)
456 {
457 colon = p;
458 symbol_start = p + 1;
459 }
460 else if (strchr (current_language->la_word_break_characters(), *p))
461 symbol_start = p + 1;
462 }
463
464 if (quoted)
465 text++;
466
467 /* Where is the file name? */
468 if (colon)
469 {
470 char *s;
471
472 file_to_match = (char *) xmalloc (colon - text + 1);
473 strncpy (file_to_match, text, colon - text);
474 file_to_match[colon - text] = '\0';
475 /* Remove trailing colons and quotes from the file name. */
476 for (s = file_to_match + (colon - text);
477 s > file_to_match;
478 s--)
479 if (*s == ':' || *s == quote_char)
480 *s = '\0';
481 }
482 /* If the text includes a colon, they want completion only on a
483 symbol name after the colon. Otherwise, we need to complete on
484 symbols as well as on files. */
485 if (colon)
486 {
487 collect_file_symbol_completion_matches (tracker,
488 complete_symbol_mode::EXPRESSION,
489 symbol_name_match_type::EXPRESSION,
490 symbol_start, word,
491 file_to_match);
492 xfree (file_to_match);
493 }
494 else
495 {
496 size_t text_len = strlen (text);
497
498 collect_symbol_completion_matches (tracker,
499 complete_symbol_mode::EXPRESSION,
500 symbol_name_match_type::EXPRESSION,
501 symbol_start, word);
502 /* If text includes characters which cannot appear in a file
503 name, they cannot be asking for completion on files. */
504 if (strcspn (text,
505 gdb_completer_file_name_break_characters) == text_len)
506 fn_list = make_source_files_completion_list (text, text);
507 }
508
509 if (!fn_list.empty () && !tracker.have_completions ())
510 {
511 /* If we only have file names as possible completion, we should
512 bring them in sync with what rl_complete expects. The
513 problem is that if the user types "break /foo/b TAB", and the
514 possible completions are "/foo/bar" and "/foo/baz"
515 rl_complete expects us to return "bar" and "baz", without the
516 leading directories, as possible completions, because `word'
517 starts at the "b". But we ignore the value of `word' when we
518 call make_source_files_completion_list above (because that
519 would not DTRT when the completion results in both symbols
520 and file names), so make_source_files_completion_list returns
521 the full "/foo/bar" and "/foo/baz" strings. This produces
522 wrong results when, e.g., there's only one possible
523 completion, because rl_complete will prepend "/foo/" to each
524 candidate completion. The loop below removes that leading
525 part. */
526 for (const auto &fn_up: fn_list)
527 {
528 char *fn = fn_up.get ();
529 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
530 }
531 }
532
533 tracker.add_completions (std::move (fn_list));
534
535 if (!tracker.have_completions ())
536 {
537 /* No completions at all. As the final resort, try completing
538 on the entire text as a symbol. */
539 collect_symbol_completion_matches (tracker,
540 complete_symbol_mode::EXPRESSION,
541 symbol_name_match_type::EXPRESSION,
542 orig_text, word);
543 }
544 }
545
546 /* See completer.h. */
547
548 completion_list
549 complete_source_filenames (const char *text)
550 {
551 size_t text_len = strlen (text);
552
553 /* If text includes characters which cannot appear in a file name,
554 the user cannot be asking for completion on files. */
555 if (strcspn (text,
556 gdb_completer_file_name_break_characters)
557 == text_len)
558 return make_source_files_completion_list (text, text);
559
560 return {};
561 }
562
563 /* Complete address and linespec locations. */
564
565 static void
566 complete_address_and_linespec_locations (completion_tracker &tracker,
567 const char *text,
568 symbol_name_match_type match_type)
569 {
570 if (*text == '*')
571 {
572 tracker.advance_custom_word_point_by (1);
573 text++;
574 const char *word
575 = advance_to_expression_complete_word_point (tracker, text);
576 complete_expression (tracker, text, word);
577 }
578 else
579 {
580 linespec_complete (tracker, text, match_type);
581 }
582 }
583
584 /* The explicit location options. Note that indexes into this array
585 must match the explicit_location_match_type enumerators. */
586
587 static const char *const explicit_options[] =
588 {
589 "-source",
590 "-function",
591 "-qualified",
592 "-line",
593 "-label",
594 NULL
595 };
596
597 /* The probe modifier options. These can appear before a location in
598 breakpoint commands. */
599 static const char *const probe_options[] =
600 {
601 "-probe",
602 "-probe-stap",
603 "-probe-dtrace",
604 NULL
605 };
606
607 /* Returns STRING if not NULL, the empty string otherwise. */
608
609 static const char *
610 string_or_empty (const char *string)
611 {
612 return string != NULL ? string : "";
613 }
614
615 /* A helper function to collect explicit location matches for the given
616 LOCATION, which is attempting to match on WORD. */
617
618 static void
619 collect_explicit_location_matches (completion_tracker &tracker,
620 struct event_location *location,
621 enum explicit_location_match_type what,
622 const char *word,
623 const struct language_defn *language)
624 {
625 const struct explicit_location *explicit_loc
626 = get_explicit_location (location);
627
628 /* True if the option expects an argument. */
629 bool needs_arg = true;
630
631 /* Note, in the various MATCH_* below, we complete on
632 explicit_loc->foo instead of WORD, because only the former will
633 have already skipped past any quote char. */
634 switch (what)
635 {
636 case MATCH_SOURCE:
637 {
638 const char *source = string_or_empty (explicit_loc->source_filename);
639 completion_list matches
640 = make_source_files_completion_list (source, source);
641 tracker.add_completions (std::move (matches));
642 }
643 break;
644
645 case MATCH_FUNCTION:
646 {
647 const char *function = string_or_empty (explicit_loc->function_name);
648 linespec_complete_function (tracker, function,
649 explicit_loc->func_name_match_type,
650 explicit_loc->source_filename);
651 }
652 break;
653
654 case MATCH_QUALIFIED:
655 needs_arg = false;
656 break;
657 case MATCH_LINE:
658 /* Nothing to offer. */
659 break;
660
661 case MATCH_LABEL:
662 {
663 const char *label = string_or_empty (explicit_loc->label_name);
664 linespec_complete_label (tracker, language,
665 explicit_loc->source_filename,
666 explicit_loc->function_name,
667 explicit_loc->func_name_match_type,
668 label);
669 }
670 break;
671
672 default:
673 gdb_assert_not_reached ("unhandled explicit_location_match_type");
674 }
675
676 if (!needs_arg || tracker.completes_to_completion_word (word))
677 {
678 tracker.discard_completions ();
679 tracker.advance_custom_word_point_by (strlen (word));
680 complete_on_enum (tracker, explicit_options, "", "");
681 complete_on_enum (tracker, linespec_keywords, "", "");
682 }
683 else if (!tracker.have_completions ())
684 {
685 /* Maybe we have an unterminated linespec keyword at the tail of
686 the string. Try completing on that. */
687 size_t wordlen = strlen (word);
688 const char *keyword = word + wordlen;
689
690 if (wordlen > 0 && keyword[-1] != ' ')
691 {
692 while (keyword > word && *keyword != ' ')
693 keyword--;
694 /* Don't complete on keywords if we'd be completing on the
695 whole explicit linespec option. E.g., "b -function
696 thr<tab>" should not complete to the "thread"
697 keyword. */
698 if (keyword != word)
699 {
700 keyword = skip_spaces (keyword);
701
702 tracker.advance_custom_word_point_by (keyword - word);
703 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
704 }
705 }
706 else if (wordlen > 0 && keyword[-1] == ' ')
707 {
708 /* Assume that we're maybe past the explicit location
709 argument, and we didn't manage to find any match because
710 the user wants to create a pending breakpoint. Offer the
711 keyword and explicit location options as possible
712 completions. */
713 tracker.advance_custom_word_point_by (keyword - word);
714 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
715 complete_on_enum (tracker, explicit_options, keyword, keyword);
716 }
717 }
718 }
719
720 /* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
721 then advance both TEXT_P and the word point in the tracker past the
722 keyword and return the (0-based) index in the KEYWORDS array that
723 matched. Otherwise, return -1. */
724
725 static int
726 skip_keyword (completion_tracker &tracker,
727 const char * const *keywords, const char **text_p)
728 {
729 const char *text = *text_p;
730 const char *after = skip_to_space (text);
731 size_t len = after - text;
732
733 if (text[len] != ' ')
734 return -1;
735
736 int found = -1;
737 for (int i = 0; keywords[i] != NULL; i++)
738 {
739 if (strncmp (keywords[i], text, len) == 0)
740 {
741 if (found == -1)
742 found = i;
743 else
744 return -1;
745 }
746 }
747
748 if (found != -1)
749 {
750 tracker.advance_custom_word_point_by (len + 1);
751 text += len + 1;
752 *text_p = text;
753 return found;
754 }
755
756 return -1;
757 }
758
759 /* A completer function for explicit locations. This function
760 completes both options ("-source", "-line", etc) and values. If
761 completing a quoted string, then QUOTED_ARG_START and
762 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
763 current language. */
764
765 static void
766 complete_explicit_location (completion_tracker &tracker,
767 struct event_location *location,
768 const char *text,
769 const language_defn *language,
770 const char *quoted_arg_start,
771 const char *quoted_arg_end)
772 {
773 if (*text != '-')
774 return;
775
776 int keyword = skip_keyword (tracker, explicit_options, &text);
777
778 if (keyword == -1)
779 complete_on_enum (tracker, explicit_options, text, text);
780 else
781 {
782 /* Completing on value. */
783 enum explicit_location_match_type what
784 = (explicit_location_match_type) keyword;
785
786 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
787 {
788 if (quoted_arg_end[1] == '\0')
789 {
790 /* If completing a quoted string with the cursor right
791 at the terminating quote char, complete the
792 completion word without interpretation, so that
793 readline advances the cursor one whitespace past the
794 quote, even if there's no match. This makes these
795 cases behave the same:
796
797 before: "b -function function()"
798 after: "b -function function() "
799
800 before: "b -function 'function()'"
801 after: "b -function 'function()' "
802
803 and trusts the user in this case:
804
805 before: "b -function 'not_loaded_function_yet()'"
806 after: "b -function 'not_loaded_function_yet()' "
807 */
808 tracker.add_completion (make_unique_xstrdup (text));
809 }
810 else if (quoted_arg_end[1] == ' ')
811 {
812 /* We're maybe past the explicit location argument.
813 Skip the argument without interpretion, assuming the
814 user may want to create pending breakpoint. Offer
815 the keyword and explicit location options as possible
816 completions. */
817 tracker.advance_custom_word_point_by (strlen (text));
818 complete_on_enum (tracker, linespec_keywords, "", "");
819 complete_on_enum (tracker, explicit_options, "", "");
820 }
821 return;
822 }
823
824 /* Now gather matches */
825 collect_explicit_location_matches (tracker, location, what, text,
826 language);
827 }
828 }
829
830 /* A completer for locations. */
831
832 void
833 location_completer (struct cmd_list_element *ignore,
834 completion_tracker &tracker,
835 const char *text, const char * /* word */)
836 {
837 int found_probe_option = -1;
838
839 /* If we have a probe modifier, skip it. This can only appear as
840 first argument. Until we have a specific completer for probes,
841 falling back to the linespec completer for the remainder of the
842 line is better than nothing. */
843 if (text[0] == '-' && text[1] == 'p')
844 found_probe_option = skip_keyword (tracker, probe_options, &text);
845
846 const char *option_text = text;
847 int saved_word_point = tracker.custom_word_point ();
848
849 const char *copy = text;
850
851 explicit_completion_info completion_info;
852 event_location_up location
853 = string_to_explicit_location (&copy, current_language,
854 &completion_info);
855 if (completion_info.quoted_arg_start != NULL
856 && completion_info.quoted_arg_end == NULL)
857 {
858 /* Found an unbalanced quote. */
859 tracker.set_quote_char (*completion_info.quoted_arg_start);
860 tracker.advance_custom_word_point_by (1);
861 }
862
863 if (completion_info.saw_explicit_location_option)
864 {
865 if (*copy != '\0')
866 {
867 tracker.advance_custom_word_point_by (copy - text);
868 text = copy;
869
870 /* We found a terminator at the tail end of the string,
871 which means we're past the explicit location options. We
872 may have a keyword to complete on. If we have a whole
873 keyword, then complete whatever comes after as an
874 expression. This is mainly for the "if" keyword. If the
875 "thread" and "task" keywords gain their own completers,
876 they should be used here. */
877 int keyword = skip_keyword (tracker, linespec_keywords, &text);
878
879 if (keyword == -1)
880 {
881 complete_on_enum (tracker, linespec_keywords, text, text);
882 }
883 else
884 {
885 const char *word
886 = advance_to_expression_complete_word_point (tracker, text);
887 complete_expression (tracker, text, word);
888 }
889 }
890 else
891 {
892 tracker.advance_custom_word_point_by (completion_info.last_option
893 - text);
894 text = completion_info.last_option;
895
896 complete_explicit_location (tracker, location.get (), text,
897 current_language,
898 completion_info.quoted_arg_start,
899 completion_info.quoted_arg_end);
900
901 }
902 }
903 /* This is an address or linespec location. */
904 else if (location != NULL)
905 {
906 /* Handle non-explicit location options. */
907
908 int keyword = skip_keyword (tracker, explicit_options, &text);
909 if (keyword == -1)
910 complete_on_enum (tracker, explicit_options, text, text);
911 else
912 {
913 tracker.advance_custom_word_point_by (copy - text);
914 text = copy;
915
916 symbol_name_match_type match_type
917 = get_explicit_location (location.get ())->func_name_match_type;
918 complete_address_and_linespec_locations (tracker, text, match_type);
919 }
920 }
921 else
922 {
923 /* No options. */
924 complete_address_and_linespec_locations (tracker, text,
925 symbol_name_match_type::WILD);
926 }
927
928 /* Add matches for option names, if either:
929
930 - Some completer above found some matches, but the word point did
931 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
932 matches all objc selectors), or;
933
934 - Some completer above advanced the word point, but found no
935 matches.
936 */
937 if ((text[0] == '-' || text[0] == '\0')
938 && (!tracker.have_completions ()
939 || tracker.custom_word_point () == saved_word_point))
940 {
941 tracker.set_custom_word_point (saved_word_point);
942 text = option_text;
943
944 if (found_probe_option == -1)
945 complete_on_enum (tracker, probe_options, text, text);
946 complete_on_enum (tracker, explicit_options, text, text);
947 }
948 }
949
950 /* The corresponding completer_handle_brkchars
951 implementation. */
952
953 static void
954 location_completer_handle_brkchars (struct cmd_list_element *ignore,
955 completion_tracker &tracker,
956 const char *text,
957 const char *word_ignored)
958 {
959 tracker.set_use_custom_word_point (true);
960
961 location_completer (ignore, tracker, text, NULL);
962 }
963
964 /* Helper for expression_completer which recursively adds field and
965 method names from TYPE, a struct or union type, to the OUTPUT
966 list. */
967
968 static void
969 add_struct_fields (struct type *type, completion_list &output,
970 const char *fieldname, int namelen)
971 {
972 int i;
973 int computed_type_name = 0;
974 const char *type_name = NULL;
975
976 type = check_typedef (type);
977 for (i = 0; i < TYPE_NFIELDS (type); ++i)
978 {
979 if (i < TYPE_N_BASECLASSES (type))
980 add_struct_fields (TYPE_BASECLASS (type, i),
981 output, fieldname, namelen);
982 else if (TYPE_FIELD_NAME (type, i))
983 {
984 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
985 {
986 if (! strncmp (TYPE_FIELD_NAME (type, i),
987 fieldname, namelen))
988 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
989 }
990 else if (TYPE_CODE (TYPE_FIELD_TYPE (type, i)) == TYPE_CODE_UNION)
991 {
992 /* Recurse into anonymous unions. */
993 add_struct_fields (TYPE_FIELD_TYPE (type, i),
994 output, fieldname, namelen);
995 }
996 }
997 }
998
999 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
1000 {
1001 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
1002
1003 if (name && ! strncmp (name, fieldname, namelen))
1004 {
1005 if (!computed_type_name)
1006 {
1007 type_name = TYPE_NAME (type);
1008 computed_type_name = 1;
1009 }
1010 /* Omit constructors from the completion list. */
1011 if (!type_name || strcmp (type_name, name))
1012 output.emplace_back (xstrdup (name));
1013 }
1014 }
1015 }
1016
1017 /* See completer.h. */
1018
1019 void
1020 complete_expression (completion_tracker &tracker,
1021 const char *text, const char *word)
1022 {
1023 struct type *type = NULL;
1024 gdb::unique_xmalloc_ptr<char> fieldname;
1025 enum type_code code = TYPE_CODE_UNDEF;
1026
1027 /* Perform a tentative parse of the expression, to see whether a
1028 field completion is required. */
1029 try
1030 {
1031 type = parse_expression_for_completion (text, &fieldname, &code);
1032 }
1033 catch (const gdb_exception_error &except)
1034 {
1035 return;
1036 }
1037
1038 if (fieldname != nullptr && type)
1039 {
1040 for (;;)
1041 {
1042 type = check_typedef (type);
1043 if (TYPE_CODE (type) != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
1044 break;
1045 type = TYPE_TARGET_TYPE (type);
1046 }
1047
1048 if (TYPE_CODE (type) == TYPE_CODE_UNION
1049 || TYPE_CODE (type) == TYPE_CODE_STRUCT)
1050 {
1051 completion_list result;
1052
1053 add_struct_fields (type, result, fieldname.get (),
1054 strlen (fieldname.get ()));
1055 tracker.add_completions (std::move (result));
1056 return;
1057 }
1058 }
1059 else if (fieldname != nullptr && code != TYPE_CODE_UNDEF)
1060 {
1061 collect_symbol_completion_matches_type (tracker, fieldname.get (),
1062 fieldname.get (), code);
1063 return;
1064 }
1065
1066 complete_files_symbols (tracker, text, word);
1067 }
1068
1069 /* Complete on expressions. Often this means completing on symbol
1070 names, but some language parsers also have support for completing
1071 field names. */
1072
1073 void
1074 expression_completer (struct cmd_list_element *ignore,
1075 completion_tracker &tracker,
1076 const char *text, const char *word)
1077 {
1078 complete_expression (tracker, text, word);
1079 }
1080
1081 /* See definition in completer.h. */
1082
1083 void
1084 set_rl_completer_word_break_characters (const char *break_chars)
1085 {
1086 rl_completer_word_break_characters = (char *) break_chars;
1087 }
1088
1089 /* See definition in completer.h. */
1090
1091 void
1092 set_gdb_completion_word_break_characters (completer_ftype *fn)
1093 {
1094 const char *break_chars;
1095
1096 /* So far we are only interested in differentiating filename
1097 completers from everything else. */
1098 if (fn == filename_completer)
1099 break_chars = gdb_completer_file_name_break_characters;
1100 else
1101 break_chars = gdb_completer_command_word_break_characters;
1102
1103 set_rl_completer_word_break_characters (break_chars);
1104 }
1105
1106 /* Complete on symbols. */
1107
1108 void
1109 symbol_completer (struct cmd_list_element *ignore,
1110 completion_tracker &tracker,
1111 const char *text, const char *word)
1112 {
1113 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
1114 symbol_name_match_type::EXPRESSION,
1115 text, word);
1116 }
1117
1118 /* Here are some useful test cases for completion. FIXME: These
1119 should be put in the test suite. They should be tested with both
1120 M-? and TAB.
1121
1122 "show output-" "radix"
1123 "show output" "-radix"
1124 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1125 "p " ambiguous (all symbols)
1126 "info t foo" no completions
1127 "info t " no completions
1128 "info t" ambiguous ("info target", "info terminal", etc.)
1129 "info ajksdlfk" no completions
1130 "info ajksdlfk " no completions
1131 "info" " "
1132 "info " ambiguous (all info commands)
1133 "p \"a" no completions (string constant)
1134 "p 'a" ambiguous (all symbols starting with a)
1135 "p b-a" ambiguous (all symbols starting with a)
1136 "p b-" ambiguous (all symbols)
1137 "file Make" "file" (word break hard to screw up here)
1138 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1139 */
1140
1141 enum complete_line_internal_reason
1142 {
1143 /* Preliminary phase, called by gdb_completion_word_break_characters
1144 function, is used to either:
1145
1146 #1 - Determine the set of chars that are word delimiters
1147 depending on the current command in line_buffer.
1148
1149 #2 - Manually advance RL_POINT to the "word break" point instead
1150 of letting readline do it (based on too-simple character
1151 matching).
1152
1153 Simpler completers that just pass a brkchars array to readline
1154 (#1 above) must defer generating the completions to the main
1155 phase (below). No completion list should be generated in this
1156 phase.
1157
1158 OTOH, completers that manually advance the word point(#2 above)
1159 must set "use_custom_word_point" in the tracker and generate
1160 their completion in this phase. Note that this is the convenient
1161 thing to do since they'll be parsing the input line anyway. */
1162 handle_brkchars,
1163
1164 /* Main phase, called by complete_line function, is used to get the
1165 list of possible completions. */
1166 handle_completions,
1167
1168 /* Special case when completing a 'help' command. In this case,
1169 once sub-command completions are exhausted, we simply return
1170 NULL. */
1171 handle_help,
1172 };
1173
1174 /* Helper for complete_line_internal to simplify it. */
1175
1176 static void
1177 complete_line_internal_normal_command (completion_tracker &tracker,
1178 const char *command, const char *word,
1179 const char *cmd_args,
1180 complete_line_internal_reason reason,
1181 struct cmd_list_element *c)
1182 {
1183 const char *p = cmd_args;
1184
1185 if (c->completer == filename_completer)
1186 {
1187 /* Many commands which want to complete on file names accept
1188 several file names, as in "run foo bar >>baz". So we don't
1189 want to complete the entire text after the command, just the
1190 last word. To this end, we need to find the beginning of the
1191 file name by starting at `word' and going backwards. */
1192 for (p = word;
1193 p > command
1194 && strchr (gdb_completer_file_name_break_characters,
1195 p[-1]) == NULL;
1196 p--)
1197 ;
1198 }
1199
1200 if (reason == handle_brkchars)
1201 {
1202 completer_handle_brkchars_ftype *brkchars_fn;
1203
1204 if (c->completer_handle_brkchars != NULL)
1205 brkchars_fn = c->completer_handle_brkchars;
1206 else
1207 {
1208 brkchars_fn
1209 = (completer_handle_brkchars_func_for_completer
1210 (c->completer));
1211 }
1212
1213 brkchars_fn (c, tracker, p, word);
1214 }
1215
1216 if (reason != handle_brkchars && c->completer != NULL)
1217 (*c->completer) (c, tracker, p, word);
1218 }
1219
1220 /* Internal function used to handle completions.
1221
1222
1223 TEXT is the caller's idea of the "word" we are looking at.
1224
1225 LINE_BUFFER is available to be looked at; it contains the entire
1226 text of the line. POINT is the offset in that line of the cursor.
1227 You should pretend that the line ends at POINT.
1228
1229 See complete_line_internal_reason for description of REASON. */
1230
1231 static void
1232 complete_line_internal_1 (completion_tracker &tracker,
1233 const char *text,
1234 const char *line_buffer, int point,
1235 complete_line_internal_reason reason)
1236 {
1237 char *tmp_command;
1238 const char *p;
1239 int ignore_help_classes;
1240 /* Pointer within tmp_command which corresponds to text. */
1241 const char *word;
1242 struct cmd_list_element *c, *result_list;
1243
1244 /* Choose the default set of word break characters to break
1245 completions. If we later find out that we are doing completions
1246 on command strings (as opposed to strings supplied by the
1247 individual command completer functions, which can be any string)
1248 then we will switch to the special word break set for command
1249 strings, which leaves out the '-' character used in some
1250 commands. */
1251 set_rl_completer_word_break_characters
1252 (current_language->la_word_break_characters());
1253
1254 /* Decide whether to complete on a list of gdb commands or on
1255 symbols. */
1256 tmp_command = (char *) alloca (point + 1);
1257 p = tmp_command;
1258
1259 /* The help command should complete help aliases. */
1260 ignore_help_classes = reason != handle_help;
1261
1262 strncpy (tmp_command, line_buffer, point);
1263 tmp_command[point] = '\0';
1264 if (reason == handle_brkchars)
1265 {
1266 gdb_assert (text == NULL);
1267 word = NULL;
1268 }
1269 else
1270 {
1271 /* Since text always contains some number of characters leading up
1272 to point, we can find the equivalent position in tmp_command
1273 by subtracting that many characters from the end of tmp_command. */
1274 word = tmp_command + point - strlen (text);
1275 }
1276
1277 /* Move P up to the start of the command. */
1278 p = skip_spaces (p);
1279
1280 if (*p == '\0')
1281 {
1282 /* An empty line is ambiguous; that is, it could be any
1283 command. */
1284 c = CMD_LIST_AMBIGUOUS;
1285 result_list = 0;
1286 }
1287 else
1288 {
1289 c = lookup_cmd_1 (&p, cmdlist, &result_list, ignore_help_classes);
1290 }
1291
1292 /* Move p up to the next interesting thing. */
1293 while (*p == ' ' || *p == '\t')
1294 {
1295 p++;
1296 }
1297
1298 tracker.advance_custom_word_point_by (p - tmp_command);
1299
1300 if (!c)
1301 {
1302 /* It is an unrecognized command. So there are no
1303 possible completions. */
1304 }
1305 else if (c == CMD_LIST_AMBIGUOUS)
1306 {
1307 const char *q;
1308
1309 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1310 doesn't advance over that thing itself. Do so now. */
1311 q = p;
1312 while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
1313 ++q;
1314 if (q != tmp_command + point)
1315 {
1316 /* There is something beyond the ambiguous
1317 command, so there are no possible completions. For
1318 example, "info t " or "info t foo" does not complete
1319 to anything, because "info t" can be "info target" or
1320 "info terminal". */
1321 }
1322 else
1323 {
1324 /* We're trying to complete on the command which was ambiguous.
1325 This we can deal with. */
1326 if (result_list)
1327 {
1328 if (reason != handle_brkchars)
1329 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
1330 word, ignore_help_classes);
1331 }
1332 else
1333 {
1334 if (reason != handle_brkchars)
1335 complete_on_cmdlist (cmdlist, tracker, p, word,
1336 ignore_help_classes);
1337 }
1338 /* Ensure that readline does the right thing with respect to
1339 inserting quotes. */
1340 set_rl_completer_word_break_characters
1341 (gdb_completer_command_word_break_characters);
1342 }
1343 }
1344 else
1345 {
1346 /* We've recognized a full command. */
1347
1348 if (p == tmp_command + point)
1349 {
1350 /* There is no non-whitespace in the line beyond the
1351 command. */
1352
1353 if (p[-1] == ' ' || p[-1] == '\t')
1354 {
1355 /* The command is followed by whitespace; we need to
1356 complete on whatever comes after command. */
1357 if (c->prefixlist)
1358 {
1359 /* It is a prefix command; what comes after it is
1360 a subcommand (e.g. "info "). */
1361 if (reason != handle_brkchars)
1362 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
1363 ignore_help_classes);
1364
1365 /* Ensure that readline does the right thing
1366 with respect to inserting quotes. */
1367 set_rl_completer_word_break_characters
1368 (gdb_completer_command_word_break_characters);
1369 }
1370 else if (reason == handle_help)
1371 ;
1372 else if (c->enums)
1373 {
1374 if (reason != handle_brkchars)
1375 complete_on_enum (tracker, c->enums, p, word);
1376 set_rl_completer_word_break_characters
1377 (gdb_completer_command_word_break_characters);
1378 }
1379 else
1380 {
1381 /* It is a normal command; what comes after it is
1382 completed by the command's completer function. */
1383 complete_line_internal_normal_command (tracker,
1384 tmp_command, word, p,
1385 reason, c);
1386 }
1387 }
1388 else
1389 {
1390 /* The command is not followed by whitespace; we need to
1391 complete on the command itself, e.g. "p" which is a
1392 command itself but also can complete to "print", "ptype"
1393 etc. */
1394 const char *q;
1395
1396 /* Find the command we are completing on. */
1397 q = p;
1398 while (q > tmp_command)
1399 {
1400 if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
1401 --q;
1402 else
1403 break;
1404 }
1405
1406 if (reason != handle_brkchars)
1407 complete_on_cmdlist (result_list, tracker, q, word,
1408 ignore_help_classes);
1409
1410 /* Ensure that readline does the right thing
1411 with respect to inserting quotes. */
1412 set_rl_completer_word_break_characters
1413 (gdb_completer_command_word_break_characters);
1414 }
1415 }
1416 else if (reason == handle_help)
1417 ;
1418 else
1419 {
1420 /* There is non-whitespace beyond the command. */
1421
1422 if (c->prefixlist && !c->allow_unknown)
1423 {
1424 /* It is an unrecognized subcommand of a prefix command,
1425 e.g. "info adsfkdj". */
1426 }
1427 else if (c->enums)
1428 {
1429 if (reason != handle_brkchars)
1430 complete_on_enum (tracker, c->enums, p, word);
1431 }
1432 else
1433 {
1434 /* It is a normal command. */
1435 complete_line_internal_normal_command (tracker,
1436 tmp_command, word, p,
1437 reason, c);
1438 }
1439 }
1440 }
1441 }
1442
1443 /* Wrapper around complete_line_internal_1 to handle
1444 MAX_COMPLETIONS_REACHED_ERROR. */
1445
1446 static void
1447 complete_line_internal (completion_tracker &tracker,
1448 const char *text,
1449 const char *line_buffer, int point,
1450 complete_line_internal_reason reason)
1451 {
1452 try
1453 {
1454 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1455 }
1456 catch (const gdb_exception_error &except)
1457 {
1458 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
1459 throw;
1460 }
1461 }
1462
1463 /* See completer.h. */
1464
1465 int max_completions = 200;
1466
1467 /* Initial size of the table. It automagically grows from here. */
1468 #define INITIAL_COMPLETION_HTAB_SIZE 200
1469
1470 /* See completer.h. */
1471
1472 completion_tracker::completion_tracker ()
1473 {
1474 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1475 htab_hash_string, streq_hash,
1476 NULL, xcalloc, xfree);
1477 }
1478
1479 /* See completer.h. */
1480
1481 void
1482 completion_tracker::discard_completions ()
1483 {
1484 xfree (m_lowest_common_denominator);
1485 m_lowest_common_denominator = NULL;
1486
1487 m_lowest_common_denominator_unique = false;
1488
1489 m_entries_vec.clear ();
1490
1491 htab_delete (m_entries_hash);
1492 m_entries_hash = htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1493 htab_hash_string, streq_hash,
1494 NULL, xcalloc, xfree);
1495 }
1496
1497 /* See completer.h. */
1498
1499 completion_tracker::~completion_tracker ()
1500 {
1501 xfree (m_lowest_common_denominator);
1502 htab_delete (m_entries_hash);
1503 }
1504
1505 /* See completer.h. */
1506
1507 bool
1508 completion_tracker::maybe_add_completion
1509 (gdb::unique_xmalloc_ptr<char> name,
1510 completion_match_for_lcd *match_for_lcd,
1511 const char *text, const char *word)
1512 {
1513 void **slot;
1514
1515 if (max_completions == 0)
1516 return false;
1517
1518 if (htab_elements (m_entries_hash) >= max_completions)
1519 return false;
1520
1521 slot = htab_find_slot (m_entries_hash, name.get (), INSERT);
1522 if (*slot == HTAB_EMPTY_ENTRY)
1523 {
1524 const char *match_for_lcd_str = NULL;
1525
1526 if (match_for_lcd != NULL)
1527 match_for_lcd_str = match_for_lcd->finish ();
1528
1529 if (match_for_lcd_str == NULL)
1530 match_for_lcd_str = name.get ();
1531
1532 gdb::unique_xmalloc_ptr<char> lcd
1533 = make_completion_match_str (match_for_lcd_str, text, word);
1534
1535 recompute_lowest_common_denominator (std::move (lcd));
1536
1537 *slot = name.get ();
1538 m_entries_vec.push_back (std::move (name));
1539 }
1540
1541 return true;
1542 }
1543
1544 /* See completer.h. */
1545
1546 void
1547 completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
1548 completion_match_for_lcd *match_for_lcd,
1549 const char *text, const char *word)
1550 {
1551 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
1552 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
1553 }
1554
1555 /* See completer.h. */
1556
1557 void
1558 completion_tracker::add_completions (completion_list &&list)
1559 {
1560 for (auto &candidate : list)
1561 add_completion (std::move (candidate));
1562 }
1563
1564 /* Helper for the make_completion_match_str overloads. Returns NULL
1565 as an indication that we want MATCH_NAME exactly. It is up to the
1566 caller to xstrdup that string if desired. */
1567
1568 static char *
1569 make_completion_match_str_1 (const char *match_name,
1570 const char *text, const char *word)
1571 {
1572 char *newobj;
1573
1574 if (word == text)
1575 {
1576 /* Return NULL as an indication that we want MATCH_NAME
1577 exactly. */
1578 return NULL;
1579 }
1580 else if (word > text)
1581 {
1582 /* Return some portion of MATCH_NAME. */
1583 newobj = xstrdup (match_name + (word - text));
1584 }
1585 else
1586 {
1587 /* Return some of WORD plus MATCH_NAME. */
1588 size_t len = strlen (match_name);
1589 newobj = (char *) xmalloc (text - word + len + 1);
1590 memcpy (newobj, word, text - word);
1591 memcpy (newobj + (text - word), match_name, len + 1);
1592 }
1593
1594 return newobj;
1595 }
1596
1597 /* See completer.h. */
1598
1599 gdb::unique_xmalloc_ptr<char>
1600 make_completion_match_str (const char *match_name,
1601 const char *text, const char *word)
1602 {
1603 char *newobj = make_completion_match_str_1 (match_name, text, word);
1604 if (newobj == NULL)
1605 newobj = xstrdup (match_name);
1606 return gdb::unique_xmalloc_ptr<char> (newobj);
1607 }
1608
1609 /* See completer.h. */
1610
1611 gdb::unique_xmalloc_ptr<char>
1612 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1613 const char *text, const char *word)
1614 {
1615 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1616 if (newobj == NULL)
1617 return std::move (match_name);
1618 return gdb::unique_xmalloc_ptr<char> (newobj);
1619 }
1620
1621 /* See complete.h. */
1622
1623 completion_result
1624 complete (const char *line, char const **word, int *quote_char)
1625 {
1626 completion_tracker tracker_handle_brkchars;
1627 completion_tracker tracker_handle_completions;
1628 completion_tracker *tracker;
1629
1630 /* The WORD should be set to the end of word to complete. We initialize
1631 to the completion point which is assumed to be at the end of LINE.
1632 This leaves WORD to be initialized to a sensible value in cases
1633 completion_find_completion_word() fails i.e., throws an exception.
1634 See bug 24587. */
1635 *word = line + strlen (line);
1636
1637 try
1638 {
1639 *word = completion_find_completion_word (tracker_handle_brkchars,
1640 line, quote_char);
1641
1642 /* Completers that provide a custom word point in the
1643 handle_brkchars phase also compute their completions then.
1644 Completers that leave the completion word handling to readline
1645 must be called twice. */
1646 if (tracker_handle_brkchars.use_custom_word_point ())
1647 tracker = &tracker_handle_brkchars;
1648 else
1649 {
1650 complete_line (tracker_handle_completions, *word, line, strlen (line));
1651 tracker = &tracker_handle_completions;
1652 }
1653 }
1654 catch (const gdb_exception &ex)
1655 {
1656 return {};
1657 }
1658
1659 return tracker->build_completion_result (*word, *word - line, strlen (line));
1660 }
1661
1662
1663 /* Generate completions all at once. Does nothing if max_completions
1664 is 0. If max_completions is non-negative, this will collect at
1665 most max_completions strings.
1666
1667 TEXT is the caller's idea of the "word" we are looking at.
1668
1669 LINE_BUFFER is available to be looked at; it contains the entire
1670 text of the line.
1671
1672 POINT is the offset in that line of the cursor. You
1673 should pretend that the line ends at POINT. */
1674
1675 void
1676 complete_line (completion_tracker &tracker,
1677 const char *text, const char *line_buffer, int point)
1678 {
1679 if (max_completions == 0)
1680 return;
1681 complete_line_internal (tracker, text, line_buffer, point,
1682 handle_completions);
1683 }
1684
1685 /* Complete on command names. Used by "help". */
1686
1687 void
1688 command_completer (struct cmd_list_element *ignore,
1689 completion_tracker &tracker,
1690 const char *text, const char *word)
1691 {
1692 complete_line_internal (tracker, word, text,
1693 strlen (text), handle_help);
1694 }
1695
1696 /* The corresponding completer_handle_brkchars implementation. */
1697
1698 static void
1699 command_completer_handle_brkchars (struct cmd_list_element *ignore,
1700 completion_tracker &tracker,
1701 const char *text, const char *word)
1702 {
1703 set_rl_completer_word_break_characters
1704 (gdb_completer_command_word_break_characters);
1705 }
1706
1707 /* Complete on signals. */
1708
1709 void
1710 signal_completer (struct cmd_list_element *ignore,
1711 completion_tracker &tracker,
1712 const char *text, const char *word)
1713 {
1714 size_t len = strlen (word);
1715 int signum;
1716 const char *signame;
1717
1718 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1719 {
1720 /* Can't handle this, so skip it. */
1721 if (signum == GDB_SIGNAL_0)
1722 continue;
1723
1724 signame = gdb_signal_to_name ((enum gdb_signal) signum);
1725
1726 /* Ignore the unknown signal case. */
1727 if (!signame || strcmp (signame, "?") == 0)
1728 continue;
1729
1730 if (strncasecmp (signame, word, len) == 0)
1731 tracker.add_completion (make_unique_xstrdup (signame));
1732 }
1733 }
1734
1735 /* Bit-flags for selecting what the register and/or register-group
1736 completer should complete on. */
1737
1738 enum reg_completer_target
1739 {
1740 complete_register_names = 0x1,
1741 complete_reggroup_names = 0x2
1742 };
1743 DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
1744
1745 /* Complete register names and/or reggroup names based on the value passed
1746 in TARGETS. At least one bit in TARGETS must be set. */
1747
1748 static void
1749 reg_or_group_completer_1 (completion_tracker &tracker,
1750 const char *text, const char *word,
1751 reg_completer_targets targets)
1752 {
1753 size_t len = strlen (word);
1754 struct gdbarch *gdbarch;
1755 const char *name;
1756
1757 gdb_assert ((targets & (complete_register_names
1758 | complete_reggroup_names)) != 0);
1759 gdbarch = get_current_arch ();
1760
1761 if ((targets & complete_register_names) != 0)
1762 {
1763 int i;
1764
1765 for (i = 0;
1766 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1767 i++)
1768 {
1769 if (*name != '\0' && strncmp (word, name, len) == 0)
1770 tracker.add_completion (make_unique_xstrdup (name));
1771 }
1772 }
1773
1774 if ((targets & complete_reggroup_names) != 0)
1775 {
1776 struct reggroup *group;
1777
1778 for (group = reggroup_next (gdbarch, NULL);
1779 group != NULL;
1780 group = reggroup_next (gdbarch, group))
1781 {
1782 name = reggroup_name (group);
1783 if (strncmp (word, name, len) == 0)
1784 tracker.add_completion (make_unique_xstrdup (name));
1785 }
1786 }
1787 }
1788
1789 /* Perform completion on register and reggroup names. */
1790
1791 void
1792 reg_or_group_completer (struct cmd_list_element *ignore,
1793 completion_tracker &tracker,
1794 const char *text, const char *word)
1795 {
1796 reg_or_group_completer_1 (tracker, text, word,
1797 (complete_register_names
1798 | complete_reggroup_names));
1799 }
1800
1801 /* Perform completion on reggroup names. */
1802
1803 void
1804 reggroup_completer (struct cmd_list_element *ignore,
1805 completion_tracker &tracker,
1806 const char *text, const char *word)
1807 {
1808 reg_or_group_completer_1 (tracker, text, word,
1809 complete_reggroup_names);
1810 }
1811
1812 /* The default completer_handle_brkchars implementation. */
1813
1814 static void
1815 default_completer_handle_brkchars (struct cmd_list_element *ignore,
1816 completion_tracker &tracker,
1817 const char *text, const char *word)
1818 {
1819 set_rl_completer_word_break_characters
1820 (current_language->la_word_break_characters ());
1821 }
1822
1823 /* See definition in completer.h. */
1824
1825 completer_handle_brkchars_ftype *
1826 completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1827 {
1828 if (fn == filename_completer)
1829 return filename_completer_handle_brkchars;
1830
1831 if (fn == location_completer)
1832 return location_completer_handle_brkchars;
1833
1834 if (fn == command_completer)
1835 return command_completer_handle_brkchars;
1836
1837 return default_completer_handle_brkchars;
1838 }
1839
1840 /* Used as brkchars when we want to tell readline we have a custom
1841 word point. We do that by making our rl_completion_word_break_hook
1842 set RL_POINT to the desired word point, and return the character at
1843 the word break point as the break char. This is two bytes in order
1844 to fit one break character plus the terminating null. */
1845 static char gdb_custom_word_point_brkchars[2];
1846
1847 /* Since rl_basic_quote_characters is not completer-specific, we save
1848 its original value here, in order to be able to restore it in
1849 gdb_rl_attempted_completion_function. */
1850 static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1851
1852 /* Get the list of chars that are considered as word breaks
1853 for the current command. */
1854
1855 static char *
1856 gdb_completion_word_break_characters_throw ()
1857 {
1858 /* New completion starting. Get rid of the previous tracker and
1859 start afresh. */
1860 delete current_completion.tracker;
1861 current_completion.tracker = new completion_tracker ();
1862
1863 completion_tracker &tracker = *current_completion.tracker;
1864
1865 complete_line_internal (tracker, NULL, rl_line_buffer,
1866 rl_point, handle_brkchars);
1867
1868 if (tracker.use_custom_word_point ())
1869 {
1870 gdb_assert (tracker.custom_word_point () > 0);
1871 rl_point = tracker.custom_word_point () - 1;
1872 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
1873 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
1874 rl_completer_quote_characters = NULL;
1875
1876 /* Clear this too, so that if we're completing a quoted string,
1877 readline doesn't consider the quote character a delimiter.
1878 If we didn't do this, readline would auto-complete {b
1879 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
1880 \', but, it wouldn't append the separator space either, which
1881 is not desirable. So instead we take care of appending the
1882 quote character to the LCD ourselves, in
1883 gdb_rl_attempted_completion_function. Since this global is
1884 not just completer-specific, we'll restore it back to the
1885 default in gdb_rl_attempted_completion_function. */
1886 rl_basic_quote_characters = NULL;
1887 }
1888
1889 return rl_completer_word_break_characters;
1890 }
1891
1892 char *
1893 gdb_completion_word_break_characters ()
1894 {
1895 /* New completion starting. */
1896 current_completion.aborted = false;
1897
1898 try
1899 {
1900 return gdb_completion_word_break_characters_throw ();
1901 }
1902 catch (const gdb_exception &ex)
1903 {
1904 /* Set this to that gdb_rl_attempted_completion_function knows
1905 to abort early. */
1906 current_completion.aborted = true;
1907 }
1908
1909 return NULL;
1910 }
1911
1912 /* See completer.h. */
1913
1914 const char *
1915 completion_find_completion_word (completion_tracker &tracker, const char *text,
1916 int *quote_char)
1917 {
1918 size_t point = strlen (text);
1919
1920 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
1921
1922 if (tracker.use_custom_word_point ())
1923 {
1924 gdb_assert (tracker.custom_word_point () > 0);
1925 *quote_char = tracker.quote_char ();
1926 return text + tracker.custom_word_point ();
1927 }
1928
1929 gdb_rl_completion_word_info info;
1930
1931 info.word_break_characters = rl_completer_word_break_characters;
1932 info.quote_characters = gdb_completer_quote_characters;
1933 info.basic_quote_characters = rl_basic_quote_characters;
1934
1935 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
1936 }
1937
1938 /* See completer.h. */
1939
1940 void
1941 completion_tracker::recompute_lowest_common_denominator
1942 (gdb::unique_xmalloc_ptr<char> &&new_match_up)
1943 {
1944 if (m_lowest_common_denominator == NULL)
1945 {
1946 /* We don't have a lowest common denominator yet, so simply take
1947 the whole NEW_MATCH_UP as being it. */
1948 m_lowest_common_denominator = new_match_up.release ();
1949 m_lowest_common_denominator_unique = true;
1950 }
1951 else
1952 {
1953 /* Find the common denominator between the currently-known
1954 lowest common denominator and NEW_MATCH_UP. That becomes the
1955 new lowest common denominator. */
1956 size_t i;
1957 const char *new_match = new_match_up.get ();
1958
1959 for (i = 0;
1960 (new_match[i] != '\0'
1961 && new_match[i] == m_lowest_common_denominator[i]);
1962 i++)
1963 ;
1964 if (m_lowest_common_denominator[i] != new_match[i])
1965 {
1966 m_lowest_common_denominator[i] = '\0';
1967 m_lowest_common_denominator_unique = false;
1968 }
1969 }
1970 }
1971
1972 /* See completer.h. */
1973
1974 void
1975 completion_tracker::advance_custom_word_point_by (size_t len)
1976 {
1977 m_custom_word_point += len;
1978 }
1979
1980 /* Build a new C string that is a copy of LCD with the whitespace of
1981 ORIG/ORIG_LEN preserved.
1982
1983 Say the user is completing a symbol name, with spaces, like:
1984
1985 "foo ( i"
1986
1987 and the resulting completion match is:
1988
1989 "foo(int)"
1990
1991 we want to end up with an input line like:
1992
1993 "foo ( int)"
1994 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
1995 ^^ => new text from LCD
1996
1997 [1] - We must take characters from the LCD instead of the original
1998 text, since some completions want to change upper/lowercase. E.g.:
1999
2000 "handle sig<>"
2001
2002 completes to:
2003
2004 "handle SIG[QUIT|etc.]"
2005 */
2006
2007 static char *
2008 expand_preserving_ws (const char *orig, size_t orig_len,
2009 const char *lcd)
2010 {
2011 const char *p_orig = orig;
2012 const char *orig_end = orig + orig_len;
2013 const char *p_lcd = lcd;
2014 std::string res;
2015
2016 while (p_orig < orig_end)
2017 {
2018 if (*p_orig == ' ')
2019 {
2020 while (p_orig < orig_end && *p_orig == ' ')
2021 res += *p_orig++;
2022 p_lcd = skip_spaces (p_lcd);
2023 }
2024 else
2025 {
2026 /* Take characters from the LCD instead of the original
2027 text, since some completions change upper/lowercase.
2028 E.g.:
2029 "handle sig<>"
2030 completes to:
2031 "handle SIG[QUIT|etc.]"
2032 */
2033 res += *p_lcd;
2034 p_orig++;
2035 p_lcd++;
2036 }
2037 }
2038
2039 while (*p_lcd != '\0')
2040 res += *p_lcd++;
2041
2042 return xstrdup (res.c_str ());
2043 }
2044
2045 /* See completer.h. */
2046
2047 completion_result
2048 completion_tracker::build_completion_result (const char *text,
2049 int start, int end)
2050 {
2051 completion_list &list = m_entries_vec; /* The completions. */
2052
2053 if (list.empty ())
2054 return {};
2055
2056 /* +1 for the LCD, and +1 for NULL termination. */
2057 char **match_list = XNEWVEC (char *, 1 + list.size () + 1);
2058
2059 /* Build replacement word, based on the LCD. */
2060
2061 match_list[0]
2062 = expand_preserving_ws (text, end - start,
2063 m_lowest_common_denominator);
2064
2065 if (m_lowest_common_denominator_unique)
2066 {
2067 /* We don't rely on readline appending the quote char as
2068 delimiter as then readline wouldn't append the ' ' after the
2069 completion. */
2070 char buf[2] = { (char) quote_char () };
2071
2072 match_list[0] = reconcat (match_list[0], match_list[0],
2073 buf, (char *) NULL);
2074 match_list[1] = NULL;
2075
2076 /* If the tracker wants to, or we already have a space at the
2077 end of the match, tell readline to skip appending
2078 another. */
2079 bool completion_suppress_append
2080 = (suppress_append_ws ()
2081 || match_list[0][strlen (match_list[0]) - 1] == ' ');
2082
2083 return completion_result (match_list, 1, completion_suppress_append);
2084 }
2085 else
2086 {
2087 int ix;
2088
2089 for (ix = 0; ix < list.size (); ++ix)
2090 match_list[ix + 1] = list[ix].release ();
2091 match_list[ix + 1] = NULL;
2092
2093 return completion_result (match_list, list.size (), false);
2094 }
2095 }
2096
2097 /* See completer.h */
2098
2099 completion_result::completion_result ()
2100 : match_list (NULL), number_matches (0),
2101 completion_suppress_append (false)
2102 {}
2103
2104 /* See completer.h */
2105
2106 completion_result::completion_result (char **match_list_,
2107 size_t number_matches_,
2108 bool completion_suppress_append_)
2109 : match_list (match_list_),
2110 number_matches (number_matches_),
2111 completion_suppress_append (completion_suppress_append_)
2112 {}
2113
2114 /* See completer.h */
2115
2116 completion_result::~completion_result ()
2117 {
2118 reset_match_list ();
2119 }
2120
2121 /* See completer.h */
2122
2123 completion_result::completion_result (completion_result &&rhs)
2124 {
2125 if (this == &rhs)
2126 return;
2127
2128 reset_match_list ();
2129 match_list = rhs.match_list;
2130 rhs.match_list = NULL;
2131 number_matches = rhs.number_matches;
2132 rhs.number_matches = 0;
2133 }
2134
2135 /* See completer.h */
2136
2137 char **
2138 completion_result::release_match_list ()
2139 {
2140 char **ret = match_list;
2141 match_list = NULL;
2142 return ret;
2143 }
2144
2145 /* See completer.h */
2146
2147 void
2148 completion_result::sort_match_list ()
2149 {
2150 if (number_matches > 1)
2151 {
2152 /* Element 0 is special (it's the common prefix), leave it
2153 be. */
2154 std::sort (&match_list[1],
2155 &match_list[number_matches + 1],
2156 compare_cstrings);
2157 }
2158 }
2159
2160 /* See completer.h */
2161
2162 void
2163 completion_result::reset_match_list ()
2164 {
2165 if (match_list != NULL)
2166 {
2167 for (char **p = match_list; *p != NULL; p++)
2168 xfree (*p);
2169 xfree (match_list);
2170 match_list = NULL;
2171 }
2172 }
2173
2174 /* Helper for gdb_rl_attempted_completion_function, which does most of
2175 the work. This is called by readline to build the match list array
2176 and to determine the lowest common denominator. The real matches
2177 list starts at match[1], while match[0] is the slot holding
2178 readline's idea of the lowest common denominator of all matches,
2179 which is what readline replaces the completion "word" with.
2180
2181 TEXT is the caller's idea of the "word" we are looking at, as
2182 computed in the handle_brkchars phase.
2183
2184 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2185 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2186 rl_point is).
2187
2188 You should thus pretend that the line ends at END (relative to
2189 RL_LINE_BUFFER).
2190
2191 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2192 the offset in that line of the cursor. You should pretend that the
2193 line ends at POINT.
2194
2195 Returns NULL if there are no completions. */
2196
2197 static char **
2198 gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2199 {
2200 /* Completers that provide a custom word point in the
2201 handle_brkchars phase also compute their completions then.
2202 Completers that leave the completion word handling to readline
2203 must be called twice. If rl_point (i.e., END) is at column 0,
2204 then readline skips the handle_brkchars phase, and so we create a
2205 tracker now in that case too. */
2206 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2207 {
2208 delete current_completion.tracker;
2209 current_completion.tracker = new completion_tracker ();
2210
2211 complete_line (*current_completion.tracker, text,
2212 rl_line_buffer, rl_point);
2213 }
2214
2215 completion_tracker &tracker = *current_completion.tracker;
2216
2217 completion_result result
2218 = tracker.build_completion_result (text, start, end);
2219
2220 rl_completion_suppress_append = result.completion_suppress_append;
2221 return result.release_match_list ();
2222 }
2223
2224 /* Function installed as "rl_attempted_completion_function" readline
2225 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2226 that catches C++ exceptions, which can't cross readline. */
2227
2228 char **
2229 gdb_rl_attempted_completion_function (const char *text, int start, int end)
2230 {
2231 /* Restore globals that might have been tweaked in
2232 gdb_completion_word_break_characters. */
2233 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2234
2235 /* If we end up returning NULL, either on error, or simple because
2236 there are no matches, inhibit readline's default filename
2237 completer. */
2238 rl_attempted_completion_over = 1;
2239
2240 /* If the handle_brkchars phase was aborted, don't try
2241 completing. */
2242 if (current_completion.aborted)
2243 return NULL;
2244
2245 try
2246 {
2247 return gdb_rl_attempted_completion_function_throw (text, start, end);
2248 }
2249 catch (const gdb_exception &ex)
2250 {
2251 }
2252
2253 return NULL;
2254 }
2255
2256 /* Skip over the possibly quoted word STR (as defined by the quote
2257 characters QUOTECHARS and the word break characters BREAKCHARS).
2258 Returns pointer to the location after the "word". If either
2259 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2260 completer. */
2261
2262 const char *
2263 skip_quoted_chars (const char *str, const char *quotechars,
2264 const char *breakchars)
2265 {
2266 char quote_char = '\0';
2267 const char *scan;
2268
2269 if (quotechars == NULL)
2270 quotechars = gdb_completer_quote_characters;
2271
2272 if (breakchars == NULL)
2273 breakchars = current_language->la_word_break_characters();
2274
2275 for (scan = str; *scan != '\0'; scan++)
2276 {
2277 if (quote_char != '\0')
2278 {
2279 /* Ignore everything until the matching close quote char. */
2280 if (*scan == quote_char)
2281 {
2282 /* Found matching close quote. */
2283 scan++;
2284 break;
2285 }
2286 }
2287 else if (strchr (quotechars, *scan))
2288 {
2289 /* Found start of a quoted string. */
2290 quote_char = *scan;
2291 }
2292 else if (strchr (breakchars, *scan))
2293 {
2294 break;
2295 }
2296 }
2297
2298 return (scan);
2299 }
2300
2301 /* Skip over the possibly quoted word STR (as defined by the quote
2302 characters and word break characters used by the completer).
2303 Returns pointer to the location after the "word". */
2304
2305 const char *
2306 skip_quoted (const char *str)
2307 {
2308 return skip_quoted_chars (str, NULL, NULL);
2309 }
2310
2311 /* Return a message indicating that the maximum number of completions
2312 has been reached and that there may be more. */
2313
2314 const char *
2315 get_max_completions_reached_message (void)
2316 {
2317 return _("*** List may be truncated, max-completions reached. ***");
2318 }
2319 \f
2320 /* GDB replacement for rl_display_match_list.
2321 Readline doesn't provide a clean interface for TUI(curses).
2322 A hack previously used was to send readline's rl_outstream through a pipe
2323 and read it from the event loop. Bleah. IWBN if readline abstracted
2324 away all the necessary bits, and this is what this code does. It
2325 replicates the parts of readline we need and then adds an abstraction
2326 layer, currently implemented as struct match_list_displayer, so that both
2327 CLI and TUI can use it. We copy all this readline code to minimize
2328 GDB-specific mods to readline. Once this code performs as desired then
2329 we can submit it to the readline maintainers.
2330
2331 N.B. A lot of the code is the way it is in order to minimize differences
2332 from readline's copy. */
2333
2334 /* Not supported here. */
2335 #undef VISIBLE_STATS
2336
2337 #if defined (HANDLE_MULTIBYTE)
2338 #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2339 #define MB_NULLWCH(x) ((x) == 0)
2340 #endif
2341
2342 #define ELLIPSIS_LEN 3
2343
2344 /* gdb version of readline/complete.c:get_y_or_n.
2345 'y' -> returns 1, and 'n' -> returns 0.
2346 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2347 If FOR_PAGER is non-zero, then also supported are:
2348 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2349
2350 static int
2351 gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2352 {
2353 int c;
2354
2355 for (;;)
2356 {
2357 RL_SETSTATE (RL_STATE_MOREINPUT);
2358 c = displayer->read_key (displayer);
2359 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2360
2361 if (c == 'y' || c == 'Y' || c == ' ')
2362 return 1;
2363 if (c == 'n' || c == 'N' || c == RUBOUT)
2364 return 0;
2365 if (c == ABORT_CHAR || c < 0)
2366 {
2367 /* Readline doesn't erase_entire_line here, but without it the
2368 --More-- prompt isn't erased and neither is the text entered
2369 thus far redisplayed. */
2370 displayer->erase_entire_line (displayer);
2371 /* Note: The arguments to rl_abort are ignored. */
2372 rl_abort (0, 0);
2373 }
2374 if (for_pager && (c == NEWLINE || c == RETURN))
2375 return 2;
2376 if (for_pager && (c == 'q' || c == 'Q'))
2377 return 0;
2378 displayer->beep (displayer);
2379 }
2380 }
2381
2382 /* Pager function for tab-completion.
2383 This is based on readline/complete.c:_rl_internal_pager.
2384 LINES is the number of lines of output displayed thus far.
2385 Returns:
2386 -1 -> user pressed 'n' or equivalent,
2387 0 -> user pressed 'y' or equivalent,
2388 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2389
2390 static int
2391 gdb_display_match_list_pager (int lines,
2392 const struct match_list_displayer *displayer)
2393 {
2394 int i;
2395
2396 displayer->puts (displayer, "--More--");
2397 displayer->flush (displayer);
2398 i = gdb_get_y_or_n (1, displayer);
2399 displayer->erase_entire_line (displayer);
2400 if (i == 0)
2401 return -1;
2402 else if (i == 2)
2403 return (lines - 1);
2404 else
2405 return 0;
2406 }
2407
2408 /* Return non-zero if FILENAME is a directory.
2409 Based on readline/complete.c:path_isdir. */
2410
2411 static int
2412 gdb_path_isdir (const char *filename)
2413 {
2414 struct stat finfo;
2415
2416 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2417 }
2418
2419 /* Return the portion of PATHNAME that should be output when listing
2420 possible completions. If we are hacking filename completion, we
2421 are only interested in the basename, the portion following the
2422 final slash. Otherwise, we return what we were passed. Since
2423 printing empty strings is not very informative, if we're doing
2424 filename completion, and the basename is the empty string, we look
2425 for the previous slash and return the portion following that. If
2426 there's no previous slash, we just return what we were passed.
2427
2428 Based on readline/complete.c:printable_part. */
2429
2430 static char *
2431 gdb_printable_part (char *pathname)
2432 {
2433 char *temp, *x;
2434
2435 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2436 return (pathname);
2437
2438 temp = strrchr (pathname, '/');
2439 #if defined (__MSDOS__)
2440 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2441 temp = pathname + 1;
2442 #endif
2443
2444 if (temp == 0 || *temp == '\0')
2445 return (pathname);
2446 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2447 Look for a previous slash and, if one is found, return the portion
2448 following that slash. If there's no previous slash, just return the
2449 pathname we were passed. */
2450 else if (temp[1] == '\0')
2451 {
2452 for (x = temp - 1; x > pathname; x--)
2453 if (*x == '/')
2454 break;
2455 return ((*x == '/') ? x + 1 : pathname);
2456 }
2457 else
2458 return ++temp;
2459 }
2460
2461 /* Compute width of STRING when displayed on screen by print_filename.
2462 Based on readline/complete.c:fnwidth. */
2463
2464 static int
2465 gdb_fnwidth (const char *string)
2466 {
2467 int width, pos;
2468 #if defined (HANDLE_MULTIBYTE)
2469 mbstate_t ps;
2470 int left, w;
2471 size_t clen;
2472 wchar_t wc;
2473
2474 left = strlen (string) + 1;
2475 memset (&ps, 0, sizeof (mbstate_t));
2476 #endif
2477
2478 width = pos = 0;
2479 while (string[pos])
2480 {
2481 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2482 {
2483 width += 2;
2484 pos++;
2485 }
2486 else
2487 {
2488 #if defined (HANDLE_MULTIBYTE)
2489 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2490 if (MB_INVALIDCH (clen))
2491 {
2492 width++;
2493 pos++;
2494 memset (&ps, 0, sizeof (mbstate_t));
2495 }
2496 else if (MB_NULLWCH (clen))
2497 break;
2498 else
2499 {
2500 pos += clen;
2501 w = wcwidth (wc);
2502 width += (w >= 0) ? w : 1;
2503 }
2504 #else
2505 width++;
2506 pos++;
2507 #endif
2508 }
2509 }
2510
2511 return width;
2512 }
2513
2514 /* Print TO_PRINT, one matching completion.
2515 PREFIX_BYTES is number of common prefix bytes.
2516 Based on readline/complete.c:fnprint. */
2517
2518 static int
2519 gdb_fnprint (const char *to_print, int prefix_bytes,
2520 const struct match_list_displayer *displayer)
2521 {
2522 int printed_len, w;
2523 const char *s;
2524 #if defined (HANDLE_MULTIBYTE)
2525 mbstate_t ps;
2526 const char *end;
2527 size_t tlen;
2528 int width;
2529 wchar_t wc;
2530
2531 end = to_print + strlen (to_print) + 1;
2532 memset (&ps, 0, sizeof (mbstate_t));
2533 #endif
2534
2535 printed_len = 0;
2536
2537 /* Don't print only the ellipsis if the common prefix is one of the
2538 possible completions */
2539 if (to_print[prefix_bytes] == '\0')
2540 prefix_bytes = 0;
2541
2542 if (prefix_bytes)
2543 {
2544 char ellipsis;
2545
2546 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2547 for (w = 0; w < ELLIPSIS_LEN; w++)
2548 displayer->putch (displayer, ellipsis);
2549 printed_len = ELLIPSIS_LEN;
2550 }
2551
2552 s = to_print + prefix_bytes;
2553 while (*s)
2554 {
2555 if (CTRL_CHAR (*s))
2556 {
2557 displayer->putch (displayer, '^');
2558 displayer->putch (displayer, UNCTRL (*s));
2559 printed_len += 2;
2560 s++;
2561 #if defined (HANDLE_MULTIBYTE)
2562 memset (&ps, 0, sizeof (mbstate_t));
2563 #endif
2564 }
2565 else if (*s == RUBOUT)
2566 {
2567 displayer->putch (displayer, '^');
2568 displayer->putch (displayer, '?');
2569 printed_len += 2;
2570 s++;
2571 #if defined (HANDLE_MULTIBYTE)
2572 memset (&ps, 0, sizeof (mbstate_t));
2573 #endif
2574 }
2575 else
2576 {
2577 #if defined (HANDLE_MULTIBYTE)
2578 tlen = mbrtowc (&wc, s, end - s, &ps);
2579 if (MB_INVALIDCH (tlen))
2580 {
2581 tlen = 1;
2582 width = 1;
2583 memset (&ps, 0, sizeof (mbstate_t));
2584 }
2585 else if (MB_NULLWCH (tlen))
2586 break;
2587 else
2588 {
2589 w = wcwidth (wc);
2590 width = (w >= 0) ? w : 1;
2591 }
2592 for (w = 0; w < tlen; ++w)
2593 displayer->putch (displayer, s[w]);
2594 s += tlen;
2595 printed_len += width;
2596 #else
2597 displayer->putch (displayer, *s);
2598 s++;
2599 printed_len++;
2600 #endif
2601 }
2602 }
2603
2604 return printed_len;
2605 }
2606
2607 /* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2608 are using it, check for and output a single character for `special'
2609 filenames. Return the number of characters we output.
2610 Based on readline/complete.c:print_filename. */
2611
2612 static int
2613 gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2614 const struct match_list_displayer *displayer)
2615 {
2616 int printed_len, extension_char, slen, tlen;
2617 char *s, c, *new_full_pathname;
2618 const char *dn;
2619 extern int _rl_complete_mark_directories;
2620
2621 extension_char = 0;
2622 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2623
2624 #if defined (VISIBLE_STATS)
2625 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2626 #else
2627 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2628 #endif
2629 {
2630 /* If to_print != full_pathname, to_print is the basename of the
2631 path passed. In this case, we try to expand the directory
2632 name before checking for the stat character. */
2633 if (to_print != full_pathname)
2634 {
2635 /* Terminate the directory name. */
2636 c = to_print[-1];
2637 to_print[-1] = '\0';
2638
2639 /* If setting the last slash in full_pathname to a NUL results in
2640 full_pathname being the empty string, we are trying to complete
2641 files in the root directory. If we pass a null string to the
2642 bash directory completion hook, for example, it will expand it
2643 to the current directory. We just want the `/'. */
2644 if (full_pathname == 0 || *full_pathname == 0)
2645 dn = "/";
2646 else if (full_pathname[0] != '/')
2647 dn = full_pathname;
2648 else if (full_pathname[1] == 0)
2649 dn = "//"; /* restore trailing slash to `//' */
2650 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2651 dn = "/"; /* don't turn /// into // */
2652 else
2653 dn = full_pathname;
2654 s = tilde_expand (dn);
2655 if (rl_directory_completion_hook)
2656 (*rl_directory_completion_hook) (&s);
2657
2658 slen = strlen (s);
2659 tlen = strlen (to_print);
2660 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2661 strcpy (new_full_pathname, s);
2662 if (s[slen - 1] == '/')
2663 slen--;
2664 else
2665 new_full_pathname[slen] = '/';
2666 new_full_pathname[slen] = '/';
2667 strcpy (new_full_pathname + slen + 1, to_print);
2668
2669 #if defined (VISIBLE_STATS)
2670 if (rl_visible_stats)
2671 extension_char = stat_char (new_full_pathname);
2672 else
2673 #endif
2674 if (gdb_path_isdir (new_full_pathname))
2675 extension_char = '/';
2676
2677 xfree (new_full_pathname);
2678 to_print[-1] = c;
2679 }
2680 else
2681 {
2682 s = tilde_expand (full_pathname);
2683 #if defined (VISIBLE_STATS)
2684 if (rl_visible_stats)
2685 extension_char = stat_char (s);
2686 else
2687 #endif
2688 if (gdb_path_isdir (s))
2689 extension_char = '/';
2690 }
2691
2692 xfree (s);
2693 if (extension_char)
2694 {
2695 displayer->putch (displayer, extension_char);
2696 printed_len++;
2697 }
2698 }
2699
2700 return printed_len;
2701 }
2702
2703 /* GDB version of readline/complete.c:complete_get_screenwidth. */
2704
2705 static int
2706 gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2707 {
2708 /* Readline has other stuff here which it's not clear we need. */
2709 return displayer->width;
2710 }
2711
2712 extern int _rl_completion_prefix_display_length;
2713 extern int _rl_print_completions_horizontally;
2714
2715 EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2716 typedef int QSFUNC (const void *, const void *);
2717
2718 /* GDB version of readline/complete.c:rl_display_match_list.
2719 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2720 Returns non-zero if all matches are displayed. */
2721
2722 static int
2723 gdb_display_match_list_1 (char **matches, int len, int max,
2724 const struct match_list_displayer *displayer)
2725 {
2726 int count, limit, printed_len, lines, cols;
2727 int i, j, k, l, common_length, sind;
2728 char *temp, *t;
2729 int page_completions = displayer->height != INT_MAX && pagination_enabled;
2730
2731 /* Find the length of the prefix common to all items: length as displayed
2732 characters (common_length) and as a byte index into the matches (sind) */
2733 common_length = sind = 0;
2734 if (_rl_completion_prefix_display_length > 0)
2735 {
2736 t = gdb_printable_part (matches[0]);
2737 temp = strrchr (t, '/');
2738 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2739 sind = temp ? strlen (temp) : strlen (t);
2740
2741 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
2742 max -= common_length - ELLIPSIS_LEN;
2743 else
2744 common_length = sind = 0;
2745 }
2746
2747 /* How many items of MAX length can we fit in the screen window? */
2748 cols = gdb_complete_get_screenwidth (displayer);
2749 max += 2;
2750 limit = cols / max;
2751 if (limit != 1 && (limit * max == cols))
2752 limit--;
2753
2754 /* If cols == 0, limit will end up -1 */
2755 if (cols < displayer->width && limit < 0)
2756 limit = 1;
2757
2758 /* Avoid a possible floating exception. If max > cols,
2759 limit will be 0 and a divide-by-zero fault will result. */
2760 if (limit == 0)
2761 limit = 1;
2762
2763 /* How many iterations of the printing loop? */
2764 count = (len + (limit - 1)) / limit;
2765
2766 /* Watch out for special case. If LEN is less than LIMIT, then
2767 just do the inner printing loop.
2768 0 < len <= limit implies count = 1. */
2769
2770 /* Sort the items if they are not already sorted. */
2771 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2772 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2773
2774 displayer->crlf (displayer);
2775
2776 lines = 0;
2777 if (_rl_print_completions_horizontally == 0)
2778 {
2779 /* Print the sorted items, up-and-down alphabetically, like ls. */
2780 for (i = 1; i <= count; i++)
2781 {
2782 for (j = 0, l = i; j < limit; j++)
2783 {
2784 if (l > len || matches[l] == 0)
2785 break;
2786 else
2787 {
2788 temp = gdb_printable_part (matches[l]);
2789 printed_len = gdb_print_filename (temp, matches[l], sind,
2790 displayer);
2791
2792 if (j + 1 < limit)
2793 for (k = 0; k < max - printed_len; k++)
2794 displayer->putch (displayer, ' ');
2795 }
2796 l += count;
2797 }
2798 displayer->crlf (displayer);
2799 lines++;
2800 if (page_completions && lines >= (displayer->height - 1) && i < count)
2801 {
2802 lines = gdb_display_match_list_pager (lines, displayer);
2803 if (lines < 0)
2804 return 0;
2805 }
2806 }
2807 }
2808 else
2809 {
2810 /* Print the sorted items, across alphabetically, like ls -x. */
2811 for (i = 1; matches[i]; i++)
2812 {
2813 temp = gdb_printable_part (matches[i]);
2814 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
2815 /* Have we reached the end of this line? */
2816 if (matches[i+1])
2817 {
2818 if (i && (limit > 1) && (i % limit) == 0)
2819 {
2820 displayer->crlf (displayer);
2821 lines++;
2822 if (page_completions && lines >= displayer->height - 1)
2823 {
2824 lines = gdb_display_match_list_pager (lines, displayer);
2825 if (lines < 0)
2826 return 0;
2827 }
2828 }
2829 else
2830 for (k = 0; k < max - printed_len; k++)
2831 displayer->putch (displayer, ' ');
2832 }
2833 }
2834 displayer->crlf (displayer);
2835 }
2836
2837 return 1;
2838 }
2839
2840 /* Utility for displaying completion list matches, used by both CLI and TUI.
2841
2842 MATCHES is the list of strings, in argv format, LEN is the number of
2843 strings in MATCHES, and MAX is the length of the longest string in
2844 MATCHES. */
2845
2846 void
2847 gdb_display_match_list (char **matches, int len, int max,
2848 const struct match_list_displayer *displayer)
2849 {
2850 /* Readline will never call this if complete_line returned NULL. */
2851 gdb_assert (max_completions != 0);
2852
2853 /* complete_line will never return more than this. */
2854 if (max_completions > 0)
2855 gdb_assert (len <= max_completions);
2856
2857 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
2858 {
2859 char msg[100];
2860
2861 /* We can't use *query here because they wait for <RET> which is
2862 wrong here. This follows the readline version as closely as possible
2863 for compatibility's sake. See readline/complete.c. */
2864
2865 displayer->crlf (displayer);
2866
2867 xsnprintf (msg, sizeof (msg),
2868 "Display all %d possibilities? (y or n)", len);
2869 displayer->puts (displayer, msg);
2870 displayer->flush (displayer);
2871
2872 if (gdb_get_y_or_n (0, displayer) == 0)
2873 {
2874 displayer->crlf (displayer);
2875 return;
2876 }
2877 }
2878
2879 if (gdb_display_match_list_1 (matches, len, max, displayer))
2880 {
2881 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
2882 if (len == max_completions)
2883 {
2884 /* The maximum number of completions has been reached. Warn the user
2885 that there may be more. */
2886 const char *message = get_max_completions_reached_message ();
2887
2888 displayer->puts (displayer, message);
2889 displayer->crlf (displayer);
2890 }
2891 }
2892 }
2893
2894 void
2895 _initialize_completer (void)
2896 {
2897 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
2898 &max_completions, _("\
2899 Set maximum number of completion candidates."), _("\
2900 Show maximum number of completion candidates."), _("\
2901 Use this to limit the number of candidates considered\n\
2902 during completion. Specifying \"unlimited\" or -1\n\
2903 disables limiting. Note that setting either no limit or\n\
2904 a very large limit can make completion slow."),
2905 NULL, NULL, &setlist, &showlist);
2906 }