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