Fix null pointer dereference in process_debug_info()
[binutils-gdb.git] / gdb / completer.h
blob98a12f3907c64b04ab60a2b347110ad627bbeb77
1 /* Header for GDB line completion.
2 Copyright (C) 2000-2024 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 #if !defined (COMPLETER_H)
18 #define COMPLETER_H 1
20 #include "gdbsupport/gdb-hashtab.h"
21 #include "gdbsupport/gdb_vecs.h"
22 #include "command.h"
24 /* Types of functions in struct match_list_displayer. */
26 struct match_list_displayer;
28 typedef void mld_crlf_ftype (const struct match_list_displayer *);
29 typedef void mld_putch_ftype (const struct match_list_displayer *, int);
30 typedef void mld_puts_ftype (const struct match_list_displayer *,
31 const char *);
32 typedef void mld_flush_ftype (const struct match_list_displayer *);
33 typedef void mld_erase_entire_line_ftype (const struct match_list_displayer *);
34 typedef void mld_beep_ftype (const struct match_list_displayer *);
35 typedef int mld_read_key_ftype (const struct match_list_displayer *);
37 /* Interface between CLI/TUI and gdb_match_list_displayer. */
39 struct match_list_displayer
41 /* The screen dimensions to work with when displaying matches. */
42 int height, width;
44 /* Print cr,lf. */
45 mld_crlf_ftype *crlf;
47 /* Not "putc" to avoid issues where it is a stdio macro. Sigh. */
48 mld_putch_ftype *putch;
50 /* Print a string. */
51 mld_puts_ftype *puts;
53 /* Flush all accumulated output. */
54 mld_flush_ftype *flush;
56 /* Erase the currently line on the terminal (but don't discard any text the
57 user has entered, readline may shortly re-print it). */
58 mld_erase_entire_line_ftype *erase_entire_line;
60 /* Ring the bell. */
61 mld_beep_ftype *beep;
63 /* Read one key. */
64 mld_read_key_ftype *read_key;
67 /* A list of completion candidates. Each element is a malloc string,
68 because ownership of the strings is transferred to readline, which
69 calls free on each element. */
70 typedef std::vector<gdb::unique_xmalloc_ptr<char>> completion_list;
72 /* The result of a successful completion match. When doing symbol
73 comparison, we use the symbol search name for the symbol name match
74 check, but the matched name that is shown to the user may be
75 different. For example, Ada uses encoded names for lookup, but
76 then wants to decode the symbol name to show to the user, and also
77 in some cases wrap the matched name in "<sym>" (meaning we can't
78 always use the symbol's print name). */
80 class completion_match
82 public:
83 /* Get the completion match result. See m_match/m_storage's
84 descriptions. */
85 const char *match ()
86 { return m_match; }
88 /* Set the completion match result. See m_match/m_storage's
89 descriptions. */
90 void set_match (const char *match)
91 { m_match = match; }
93 /* Get temporary storage for generating a match result, dynamically.
94 The built string is only good until the next clear() call. I.e.,
95 good until the next symbol comparison. */
96 std::string &storage ()
97 { return m_storage; }
99 /* Prepare for another completion matching sequence. */
100 void clear ()
102 m_match = NULL;
103 m_storage.clear ();
106 private:
107 /* The completion match result. This can either be a pointer into
108 M_STORAGE string, or it can be a pointer into the some other
109 string that outlives the completion matching sequence (usually, a
110 pointer to a symbol's name). */
111 const char *m_match;
113 /* Storage a symbol comparison routine can use for generating a
114 match result, dynamically. The built string is only good until
115 the next clear() call. I.e., good until the next symbol
116 comparison. */
117 std::string m_storage;
120 /* The result of a successful completion match, but for least common
121 denominator (LCD) computation. Some completers provide matches
122 that don't start with the completion "word". E.g., completing on
123 "b push_ba" on a C++ program usually completes to
124 std::vector<...>::push_back, std::string::push_back etc. In such
125 case, the symbol comparison routine will set the LCD match to point
126 into the "push_back" substring within the symbol's name string.
127 Also, in some cases, the symbol comparison routine will want to
128 ignore parts of the symbol name for LCD purposes, such as for
129 example symbols with abi tags in C++. In such cases, the symbol
130 comparison routine will set MARK_IGNORED_RANGE to mark the ignored
131 substrings of the matched string. The resulting LCD string with
132 the ignored parts stripped out is computed at the end of a
133 completion match sequence iff we had a positive match. */
135 class completion_match_for_lcd
137 public:
138 /* Get the resulting LCD, after a successful match. */
139 const char *match ()
140 { return m_match; }
142 /* Set the match for LCD. See m_match's description. */
143 void set_match (const char *match)
144 { m_match = match; }
146 /* Mark the range between [BEGIN, END) as ignored. */
147 void mark_ignored_range (const char *begin, const char *end)
149 gdb_assert (begin < end);
150 gdb_assert (m_ignored_ranges.empty ()
151 || m_ignored_ranges.back ().second < begin);
152 m_ignored_ranges.emplace_back (begin, end);
155 /* Get the resulting LCD, after a successful match. If there are
156 ignored ranges, then this builds a new string with the ignored
157 parts removed (and stores it internally). As such, the result of
158 this call is only good for the current completion match
159 sequence. */
160 const char *finish ()
162 if (m_ignored_ranges.empty ())
163 return m_match;
164 else
166 m_finished_storage.clear ();
168 gdb_assert (m_ignored_ranges.back ().second
169 <= (m_match + strlen (m_match)));
171 const char *prev = m_match;
172 for (const auto &range : m_ignored_ranges)
174 gdb_assert (prev < range.first);
175 gdb_assert (range.second > range.first);
176 m_finished_storage.append (prev, range.first);
177 prev = range.second;
179 m_finished_storage.append (prev);
181 return m_finished_storage.c_str ();
185 /* Prepare for another completion matching sequence. */
186 void clear ()
188 m_match = NULL;
189 m_ignored_ranges.clear ();
192 /* Return true if this object has had no match data set since its
193 creation, or the last call to clear. */
194 bool empty () const
196 return m_match == nullptr && m_ignored_ranges.empty ();
199 private:
200 /* The completion match result for LCD. This is usually either a
201 pointer into to a substring within a symbol's name, or to the
202 storage of the pairing completion_match object. */
203 const char *m_match;
205 /* The ignored substring ranges within M_MATCH. E.g., if we were
206 looking for completion matches for C++ functions starting with
207 "functio"
208 and successfully match:
209 "function[abi:cxx11](int)"
210 the ignored ranges vector will contain an entry that delimits the
211 "[abi:cxx11]" substring, such that calling finish() results in:
212 "function(int)"
214 std::vector<std::pair<const char *, const char *>> m_ignored_ranges;
216 /* Storage used by the finish() method, if it has to compute a new
217 string. */
218 std::string m_finished_storage;
221 /* Convenience aggregate holding info returned by the symbol name
222 matching routines (see symbol_name_matcher_ftype). */
223 struct completion_match_result
225 /* The completion match candidate. */
226 completion_match match;
228 /* The completion match, for LCD computation purposes. */
229 completion_match_for_lcd match_for_lcd;
231 /* Convenience that sets both MATCH and MATCH_FOR_LCD. M_FOR_LCD is
232 optional. If not specified, defaults to M. */
233 void set_match (const char *m, const char *m_for_lcd = NULL)
235 match.set_match (m);
236 if (m_for_lcd == NULL)
237 match_for_lcd.set_match (m);
238 else
239 match_for_lcd.set_match (m_for_lcd);
243 /* The final result of a completion that is handed over to either
244 readline or the "completion" command (which pretends to be
245 readline). Mainly a wrapper for a readline-style match list array,
246 though other bits of info are included too. */
248 struct completion_result
250 /* Create an empty result. */
251 completion_result ();
253 /* Create a result. */
254 completion_result (char **match_list, size_t number_matches,
255 bool completion_suppress_append);
257 /* Destroy a result. */
258 ~completion_result ();
260 DISABLE_COPY_AND_ASSIGN (completion_result);
262 /* Move a result. */
263 completion_result (completion_result &&rhs) noexcept;
265 /* Release ownership of the match list array. */
266 char **release_match_list ();
268 /* Sort the match list. */
269 void sort_match_list ();
271 private:
272 /* Destroy the match list array and its contents. */
273 void reset_match_list ();
275 public:
276 /* (There's no point in making these fields private, since the whole
277 point of this wrapper is to build data in the layout expected by
278 readline. Making them private would require adding getters for
279 the "complete" command, which would expose the same
280 implementation details anyway.) */
282 /* The match list array, in the format that readline expects.
283 match_list[0] contains the common prefix. The real match list
284 starts at index 1. The list is NULL terminated. If there's only
285 one match, then match_list[1] is NULL. If there are no matches,
286 then this is NULL. */
287 char **match_list;
288 /* The number of matched completions in MATCH_LIST. Does not
289 include the NULL terminator or the common prefix. */
290 size_t number_matches;
292 /* Whether readline should suppress appending a whitespace, when
293 there's only one possible completion. */
294 bool completion_suppress_append;
297 /* Object used by completers to build a completion match list to hand
298 over to readline. It tracks:
300 - How many unique completions have been generated, to terminate
301 completion list generation early if the list has grown to a size
302 so large as to be useless. This helps avoid GDB seeming to lock
303 up in the event the user requests to complete on something vague
304 that necessitates the time consuming expansion of many symbol
305 tables.
307 - The completer's idea of least common denominator (aka the common
308 prefix) between all completion matches to hand over to readline.
309 Some completers provide matches that don't start with the
310 completion "word". E.g., completing on "b push_ba" on a C++
311 program usually completes to std::vector<...>::push_back,
312 std::string::push_back etc. If all matches happen to start with
313 "std::", then readline would figure out that the lowest common
314 denominator is "std::", and thus would do a partial completion
315 with that. I.e., it would replace "push_ba" in the input buffer
316 with "std::", losing the original "push_ba", which is obviously
317 undesirable. To avoid that, such completers pass the substring
318 of the match that matters for common denominator computation as
319 MATCH_FOR_LCD argument to add_completion. The end result is
320 passed to readline in gdb_rl_attempted_completion_function.
322 - The custom word point to hand over to readline, for completers
323 that parse the input string in order to dynamically adjust
324 themselves depending on exactly what they're completing. E.g.,
325 the linespec completer needs to bypass readline's too-simple word
326 breaking algorithm.
328 class completion_tracker
330 public:
331 explicit completion_tracker (bool from_readline);
332 ~completion_tracker ();
334 DISABLE_COPY_AND_ASSIGN (completion_tracker);
336 /* Add the completion NAME to the list of generated completions if
337 it is not there already. If too many completions were already
338 found, this throws an error. */
339 void add_completion (gdb::unique_xmalloc_ptr<char> name,
340 completion_match_for_lcd *match_for_lcd = NULL,
341 const char *text = NULL, const char *word = NULL);
343 /* Add all completions matches in LIST. Elements are moved out of
344 LIST. */
345 void add_completions (completion_list &&list);
347 /* Remove completion matching NAME from the completion list, does nothing
348 if NAME is not already in the completion list. */
349 void remove_completion (const char *name);
351 /* Set the quote char to be appended after a unique completion is
352 added to the input line. Set to '\0' to clear. See
353 m_quote_char's description. */
354 void set_quote_char (int quote_char)
355 { m_quote_char = quote_char; }
357 /* The quote char to be appended after a unique completion is added
358 to the input line. Returns '\0' if no quote char has been set.
359 See m_quote_char's description. */
360 int quote_char () { return m_quote_char; }
362 /* Tell the tracker that the current completer wants to provide a
363 custom word point instead of a list of a break chars, in the
364 handle_brkchars phase. Such completers must also compute their
365 completions then. */
366 void set_use_custom_word_point (bool enable)
367 { m_use_custom_word_point = enable; }
369 /* Whether the current completer computes a custom word point. */
370 bool use_custom_word_point () const
371 { return m_use_custom_word_point; }
373 /* The custom word point. */
374 int custom_word_point () const
375 { return m_custom_word_point; }
377 /* Set the custom word point to POINT. */
378 void set_custom_word_point (int point)
379 { m_custom_word_point = point; }
381 /* Advance the custom word point by LEN. */
382 void advance_custom_word_point_by (int len);
384 /* Whether to tell readline to skip appending a whitespace after the
385 completion. See m_suppress_append_ws. */
386 bool suppress_append_ws () const
387 { return m_suppress_append_ws; }
389 /* Set whether to tell readline to skip appending a whitespace after
390 the completion. See m_suppress_append_ws. */
391 void set_suppress_append_ws (bool suppress)
392 { m_suppress_append_ws = suppress; }
394 /* Return true if we only have one completion, and it matches
395 exactly the completion word. I.e., completing results in what we
396 already have. */
397 bool completes_to_completion_word (const char *word);
399 /* Get a reference to the shared (between all the multiple symbol
400 name comparison calls) completion_match_result object, ready for
401 another symbol name match sequence. */
402 completion_match_result &reset_completion_match_result ()
404 completion_match_result &res = m_completion_match_result;
406 /* Clear any previous match. */
407 res.match.clear ();
408 res.match_for_lcd.clear ();
409 return m_completion_match_result;
412 /* True if we have any completion match recorded. */
413 bool have_completions () const
414 { return htab_elements (m_entries_hash.get ()) > 0; }
416 /* Discard the current completion match list and the current
417 LCD. */
418 void discard_completions ();
420 /* Build a completion_result containing the list of completion
421 matches to hand over to readline. The parameters are as in
422 rl_attempted_completion_function. */
423 completion_result build_completion_result (const char *text,
424 int start, int end);
426 /* Tells if the completion task is triggered by readline. See
427 m_from_readline. */
428 bool from_readline () const
429 { return m_from_readline; }
431 private:
433 /* The type that we place into the m_entries_hash hash table. */
434 class completion_hash_entry;
436 /* Add the completion NAME to the list of generated completions if
437 it is not there already. If false is returned, too many
438 completions were found. */
439 bool maybe_add_completion (gdb::unique_xmalloc_ptr<char> name,
440 completion_match_for_lcd *match_for_lcd,
441 const char *text, const char *word);
443 /* Ensure that the lowest common denominator held in the member variable
444 M_LOWEST_COMMON_DENOMINATOR is valid. This method must be called if
445 there is any chance that new completions have been added to the
446 tracker before the lowest common denominator is read. */
447 void recompute_lowest_common_denominator ();
449 /* Callback used from recompute_lowest_common_denominator, called for
450 every entry in m_entries_hash. */
451 void recompute_lcd_visitor (completion_hash_entry *entry);
453 /* Completion match outputs returned by the symbol name matching
454 routines (see symbol_name_matcher_ftype). These results are only
455 valid for a single match call. This is here in order to be able
456 to conveniently share the same storage among all the calls to the
457 symbol name matching routines. */
458 completion_match_result m_completion_match_result;
460 /* The completion matches found so far, in a hash table, for
461 duplicate elimination as entries are added. Otherwise the user
462 is left scratching his/her head: readline and complete_command
463 will remove duplicates, and if removal of duplicates there brings
464 the total under max_completions the user may think gdb quit
465 searching too early. */
466 htab_up m_entries_hash;
468 /* If non-zero, then this is the quote char that needs to be
469 appended after completion (iff we have a unique completion). We
470 don't rely on readline appending the quote char as delimiter as
471 then readline wouldn't append the ' ' after the completion.
472 I.e., we want this:
474 before tab: "b 'function("
475 after tab: "b 'function()' "
477 int m_quote_char = '\0';
479 /* If true, the completer has its own idea of "word" point, and
480 doesn't want to rely on readline computing it based on brkchars.
481 Set in the handle_brkchars phase. */
482 bool m_use_custom_word_point = false;
484 /* The completer's idea of where the "word" we were looking at is
485 relative to RL_LINE_BUFFER. This is advanced in the
486 handle_brkchars phase as the completer discovers potential
487 completable words. */
488 int m_custom_word_point = 0;
490 /* If true, tell readline to skip appending a whitespace after the
491 completion. Automatically set if we have a unique completion
492 that already has a space at the end. A completer may also
493 explicitly set this. E.g., the linespec completer sets this when
494 the completion ends with the ":" separator between filename and
495 function name. */
496 bool m_suppress_append_ws = false;
498 /* Our idea of lowest common denominator to hand over to readline.
499 See intro. */
500 char *m_lowest_common_denominator = NULL;
502 /* If true, the LCD is unique. I.e., all completions had the same
503 MATCH_FOR_LCD substring, even if the completions were different.
504 For example, if "break function<tab>" found "a::function()" and
505 "b::function()", the LCD will be "function()" in both cases and
506 so we want to tell readline to complete the line with
507 "function()", instead of showing all the possible
508 completions. */
509 bool m_lowest_common_denominator_unique = false;
511 /* True if the value in M_LOWEST_COMMON_DENOMINATOR is correct. This is
512 set to true each time RECOMPUTE_LOWEST_COMMON_DENOMINATOR is called,
513 and reset to false whenever a new completion is added. */
514 bool m_lowest_common_denominator_valid = false;
516 /* To avoid calls to xrealloc in RECOMPUTE_LOWEST_COMMON_DENOMINATOR, we
517 track the maximum possible size of the lowest common denominator,
518 which we know as each completion is added. */
519 size_t m_lowest_common_denominator_max_length = 0;
521 /* Indicates that the completions are to be displayed by readline
522 interactively. The 'complete' command is a way to generate completions
523 not to be displayed by readline. */
524 bool m_from_readline;
527 /* Return a string to hand off to readline as a completion match
528 candidate, potentially composed of parts of MATCH_NAME and of
529 TEXT/WORD. For a description of TEXT/WORD see completer_ftype. */
531 extern gdb::unique_xmalloc_ptr<char>
532 make_completion_match_str (const char *match_name,
533 const char *text, const char *word);
535 /* Like above, but takes ownership of MATCH_NAME (i.e., can
536 reuse/return it). */
538 extern gdb::unique_xmalloc_ptr<char>
539 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
540 const char *text, const char *word);
542 extern void gdb_display_match_list (char **matches, int len, int max,
543 const struct match_list_displayer *);
545 extern const char *get_max_completions_reached_message (void);
547 extern void complete_line (completion_tracker &tracker,
548 const char *text,
549 const char *line_buffer,
550 int point);
552 /* Complete LINE and return completion results. For completion purposes,
553 cursor position is assumed to be at the end of LINE. WORD is set to
554 the end of word to complete. QUOTE_CHAR is set to the opening quote
555 character if we found an unclosed quoted substring, '\0' otherwise. */
556 extern completion_result
557 complete (const char *line, char const **word, int *quote_char);
559 /* Assuming TEXT is an expression in the current language, find the
560 completion word point for TEXT, emulating the algorithm readline
561 uses to find the word point, using the current language's word
562 break characters. */
563 const char *advance_to_expression_complete_word_point
564 (completion_tracker &tracker, const char *text);
566 /* Assuming TEXT is an filename, find the completion word point for
567 TEXT, emulating the algorithm readline uses to find the word
568 point. */
569 extern const char *advance_to_filename_complete_word_point
570 (completion_tracker &tracker, const char *text);
572 extern void noop_completer (struct cmd_list_element *,
573 completion_tracker &tracker,
574 const char *, const char *);
576 extern void filename_completer (struct cmd_list_element *,
577 completion_tracker &tracker,
578 const char *, const char *);
580 extern void expression_completer (struct cmd_list_element *,
581 completion_tracker &tracker,
582 const char *, const char *);
584 extern void location_completer (struct cmd_list_element *,
585 completion_tracker &tracker,
586 const char *, const char *);
588 extern void symbol_completer (struct cmd_list_element *,
589 completion_tracker &tracker,
590 const char *, const char *);
592 extern void command_completer (struct cmd_list_element *,
593 completion_tracker &tracker,
594 const char *, const char *);
596 extern void signal_completer (struct cmd_list_element *,
597 completion_tracker &tracker,
598 const char *, const char *);
600 extern void reg_or_group_completer (struct cmd_list_element *,
601 completion_tracker &tracker,
602 const char *, const char *);
604 extern void reggroup_completer (struct cmd_list_element *,
605 completion_tracker &tracker,
606 const char *, const char *);
608 /* Get the matching completer_handle_brkchars_ftype function for FN.
609 FN is one of the core completer functions above (filename,
610 location, symbol, etc.). This function is useful for cases when
611 the completer doesn't know the type of the completion until some
612 calculation is done (e.g., for Python functions). */
614 extern completer_handle_brkchars_ftype *
615 completer_handle_brkchars_func_for_completer (completer_ftype *fn);
617 /* Exported to linespec.c */
619 /* Return a list of all source files whose names begin with matching
620 TEXT. */
621 extern completion_list complete_source_filenames (const char *text);
623 /* Complete on expressions. Often this means completing on symbol
624 names, but some language parsers also have support for completing
625 field names. */
626 extern void complete_expression (completion_tracker &tracker,
627 const char *text, const char *word);
629 /* Called by custom word point completers that want to recurse into
630 the completion machinery to complete a command. Used to complete
631 COMMAND in "thread apply all COMMAND", for example. Note that
632 unlike command_completer, this fully recurses into the proper
633 completer for COMMAND, so that e.g.,
635 (gdb) thread apply all print -[TAB]
637 does the right thing and show the print options. */
638 extern void complete_nested_command_line (completion_tracker &tracker,
639 const char *text);
641 /* Called from command completion function to skip over /FMT
642 specifications, allowing the rest of the line to be completed. Returns
643 true if the /FMT is at the end of the current line and there is nothing
644 left to complete, otherwise false is returned.
646 In either case *ARGS can be updated to point after any part of /FMT that
647 is present.
649 This function is designed so that trying to complete '/' will offer no
650 completions, the user needs to insert the format specification
651 themselves. Trying to complete '/FMT' (where FMT is any non-empty set
652 of alpha-numeric characters) will cause readline to insert a single
653 space, setting the user up to enter the expression. */
655 extern bool skip_over_slash_fmt (completion_tracker &tracker,
656 const char **args);
658 /* Maximum number of candidates to consider before the completer
659 bails by throwing MAX_COMPLETIONS_REACHED_ERROR. Negative values
660 disable limiting. */
662 extern int max_completions;
664 #endif /* defined (COMPLETER_H) */