]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/cli/cli-cmds.c
gdb, gdbserver, gdbsupport: remove includes of early headers
[thirdparty/binutils-gdb.git] / gdb / cli / cli-cmds.c
CommitLineData
d318976c 1/* GDB CLI commands.
8926118c 2
1d506c26 3 Copyright (C) 2000-2024 Free Software Foundation, Inc.
d318976c
FN
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
d318976c
FN
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
d318976c 19
13274fc3 20#include "arch-utils.h"
dbda9972 21#include "readline/tilde.h"
d318976c 22#include "completer.h"
ef0f16cc
TT
23#include "target.h"
24#include "gdbsupport/gdb_wait.h"
947d3946 25#include "gdbcmd.h"
ef0f16cc 26#include "gdbsupport/gdb_regex.h"
325ed089 27#include "gdb_vfork.h"
0378c332
FN
28#include "linespec.h"
29#include "expression.h"
83c31e7d
FN
30#include "frame.h"
31#include "value.h"
0378c332 32#include "language.h"
ef0f16cc 33#include "filenames.h"
0378c332
FN
34#include "objfiles.h"
35#include "source.h"
83c31e7d 36#include "disasm.h"
33da3f1c 37#include "tracepoint.h"
268a13a5 38#include "gdbsupport/filestuff.h"
f00aae0f 39#include "location.h"
e9480230 40#include "block.h"
91265a7d 41#include "valprint.h"
d318976c 42
d318976c 43#include "ui-out.h"
947d3946 44#include "interps.h"
d318976c
FN
45
46#include "top.h"
13d03262 47#include "ui.h"
d318976c
FN
48#include "cli/cli-decode.h"
49#include "cli/cli-script.h"
50#include "cli/cli-setshow.h"
51#include "cli/cli-cmds.h"
14309bb6 52#include "cli/cli-style.h"
529480d0 53#include "cli/cli-utils.h"
cf00cd6f 54#include "cli/cli-style.h"
d318976c 55
6dddc817 56#include "extension.h"
268a13a5 57#include "gdbsupport/pathstuff.h"
1845e254 58#include "gdbsupport/gdb_tilde_expand.h"
973817a3 59
6a83354a 60#ifdef TUI
ef0f16cc 61#include "tui/tui.h"
6a83354a
AC
62#endif
63
4b505b12 64#include <fcntl.h>
325fac50 65#include <algorithm>
a97e29d2 66#include <string>
4b505b12 67
0378c332
FN
68/* Prototypes for local utility functions */
69
06871ae8
PA
70static void print_sal_location (const symtab_and_line &sal);
71
6c5b2ebe 72static void ambiguous_line_spec (gdb::array_view<const symtab_and_line> sals,
e439fa14
PA
73 const char *format, ...)
74 ATTRIBUTE_PRINTF (2, 3);
f8eba3c6 75
6c5b2ebe 76static void filter_sals (std::vector<symtab_and_line> &);
f8eba3c6 77
d318976c 78\f
cc8dee1f 79/* See cli-cmds.h. */
37163dcf 80unsigned int max_user_call_depth = 1024;
20f01a46 81
d318976c
FN
82/* Define all cmd_list_elements. */
83
84/* Chain containing all defined commands. */
85
86struct cmd_list_element *cmdlist;
87
88/* Chain containing all defined info subcommands. */
89
90struct cmd_list_element *infolist;
91
ebcd3b23 92/* Chain containing all defined enable subcommands. */
d318976c
FN
93
94struct cmd_list_element *enablelist;
95
ebcd3b23 96/* Chain containing all defined disable subcommands. */
d318976c
FN
97
98struct cmd_list_element *disablelist;
99
ebcd3b23 100/* Chain containing all defined stop subcommands. */
d318976c
FN
101
102struct cmd_list_element *stoplist;
103
ebcd3b23 104/* Chain containing all defined delete subcommands. */
d318976c
FN
105
106struct cmd_list_element *deletelist;
107
ebcd3b23 108/* Chain containing all defined detach subcommands. */
f73adfeb
AS
109
110struct cmd_list_element *detachlist;
111
ebcd3b23 112/* Chain containing all defined kill subcommands. */
2277426b
PA
113
114struct cmd_list_element *killlist;
115
d318976c
FN
116/* Chain containing all defined set subcommands */
117
118struct cmd_list_element *setlist;
119
120/* Chain containing all defined unset subcommands */
121
122struct cmd_list_element *unsetlist;
123
124/* Chain containing all defined show subcommands. */
125
126struct cmd_list_element *showlist;
127
128/* Chain containing all defined \"set history\". */
129
130struct cmd_list_element *sethistlist;
131
132/* Chain containing all defined \"show history\". */
133
134struct cmd_list_element *showhistlist;
135
136/* Chain containing all defined \"unset history\". */
137
138struct cmd_list_element *unsethistlist;
139
ebcd3b23 140/* Chain containing all defined maintenance subcommands. */
d318976c
FN
141
142struct cmd_list_element *maintenancelist;
143
ebcd3b23 144/* Chain containing all defined "maintenance info" subcommands. */
d318976c
FN
145
146struct cmd_list_element *maintenanceinfolist;
147
ebcd3b23 148/* Chain containing all defined "maintenance print" subcommands. */
d318976c
FN
149
150struct cmd_list_element *maintenanceprintlist;
151
27d41eac
YQ
152/* Chain containing all defined "maintenance check" subcommands. */
153
154struct cmd_list_element *maintenancechecklist;
155
50a5f187
AB
156/* Chain containing all defined "maintenance flush" subcommands. */
157
158struct cmd_list_element *maintenanceflushlist;
159
d318976c
FN
160struct cmd_list_element *setprintlist;
161
162struct cmd_list_element *showprintlist;
163
164struct cmd_list_element *setdebuglist;
165
166struct cmd_list_element *showdebuglist;
167
168struct cmd_list_element *setchecklist;
169
170struct cmd_list_element *showchecklist;
16026cd7 171
fde1a9a3
AB
172struct cmd_list_element *setsourcelist;
173
174struct cmd_list_element *showsourcelist;
175
16026cd7
AS
176/* Command tracing state. */
177
178int source_verbose = 0;
491144b5 179bool trace_commands = false;
d318976c 180\f
973817a3
JB
181/* 'script-extension' option support. */
182
183static const char script_ext_off[] = "off";
184static const char script_ext_soft[] = "soft";
185static const char script_ext_strict[] = "strict";
186
40478521 187static const char *const script_ext_enums[] = {
973817a3
JB
188 script_ext_off,
189 script_ext_soft,
190 script_ext_strict,
191 NULL
192};
193
194static const char *script_ext_mode = script_ext_soft;
195\f
61fb7376
TBA
196
197/* User-controllable flag to suppress event notification on CLI. */
198
199static bool user_wants_cli_suppress_notification = false;
200
d318976c 201/* Utility used everywhere when at least one argument is needed and
ebcd3b23 202 none is supplied. */
d318976c
FN
203
204void
5b10184c 205error_no_arg (const char *why)
d318976c 206{
8a3fe4f8 207 error (_("Argument required (%s)."), why);
d318976c
FN
208}
209
4fd6c7e8
TT
210/* This implements the "info" prefix command. Normally such commands
211 are automatically handled by add_basic_prefix_cmd, but in this case
212 a separate command is used so that it can be hooked into by
213 gdb-gdb.gdb. */
214
215static void
216info_command (const char *arg, int from_tty)
217{
218 help_list (infolist, "info ", all_commands, gdb_stdout);
219}
220
fdbc9870
PA
221/* See cli/cli-cmds.h. */
222
223void
224with_command_1 (const char *set_cmd_prefix,
225 cmd_list_element *setlist, const char *args, int from_tty)
226{
26c957f1
PA
227 if (args == nullptr)
228 error (_("Missing arguments."));
229
fdbc9870
PA
230 const char *delim = strstr (args, "--");
231 const char *nested_cmd = nullptr;
232
233 if (delim == args)
234 error (_("Missing setting before '--' delimiter"));
235
236 if (delim == nullptr || *skip_spaces (&delim[2]) == '\0')
237 nested_cmd = repeat_previous ();
238
239 cmd_list_element *set_cmd = lookup_cmd (&args, setlist, set_cmd_prefix,
cf00cd6f 240 nullptr,
fdbc9870
PA
241 /*allow_unknown=*/ 0,
242 /*ignore_help_classes=*/ 1);
243 gdb_assert (set_cmd != nullptr);
244
1d7fe7f0 245 if (!set_cmd->var.has_value ())
fdbc9870
PA
246 error (_("Cannot use this setting with the \"with\" command"));
247
248 std::string temp_value
249 = (delim == nullptr ? args : std::string (args, delim - args));
250
251 if (nested_cmd == nullptr)
252 nested_cmd = skip_spaces (delim + 2);
253
1d7fe7f0
LS
254 gdb_assert (set_cmd->var.has_value ());
255 std::string org_value = get_setshow_command_value_string (*set_cmd->var);
fdbc9870
PA
256
257 /* Tweak the setting to the new temporary value. */
258 do_set_command (temp_value.c_str (), from_tty, set_cmd);
259
260 try
261 {
262 scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
263
264 /* Execute the nested command. */
265 execute_command (nested_cmd, from_tty);
266 }
267 catch (const gdb_exception &ex)
268 {
269 /* Restore the setting and rethrow. If restoring the setting
270 throws, swallow the new exception and warn. There's nothing
271 else we can reasonably do. */
272 try
273 {
274 do_set_command (org_value.c_str (), from_tty, set_cmd);
275 }
276 catch (const gdb_exception &ex2)
277 {
278 warning (_("Couldn't restore setting: %s"), ex2.what ());
279 }
280
281 throw;
282 }
283
284 /* Restore the setting. */
285 do_set_command (org_value.c_str (), from_tty, set_cmd);
286}
287
288/* See cli/cli-cmds.h. */
289
290void
291with_command_completer_1 (const char *set_cmd_prefix,
292 completion_tracker &tracker,
293 const char *text)
294{
295 tracker.set_use_custom_word_point (true);
296
297 const char *delim = strstr (text, "--");
298
299 /* If we're still not past the "--" delimiter, complete the "with"
300 command as if it was a "set" command. */
301 if (delim == text
302 || delim == nullptr
303 || !isspace (delim[-1])
304 || !(isspace (delim[2]) || delim[2] == '\0'))
305 {
306 std::string new_text = std::string (set_cmd_prefix) + text;
307 tracker.advance_custom_word_point_by (-(int) strlen (set_cmd_prefix));
308 complete_nested_command_line (tracker, new_text.c_str ());
309 return;
310 }
311
312 /* We're past the "--" delimiter. Complete on the sub command. */
313 const char *nested_cmd = skip_spaces (delim + 2);
314 tracker.advance_custom_word_point_by (nested_cmd - text);
315 complete_nested_command_line (tracker, nested_cmd);
316}
317
318/* The "with" command. */
319
320static void
321with_command (const char *args, int from_tty)
322{
323 with_command_1 ("set ", setlist, args, from_tty);
324}
325
326/* "with" command completer. */
327
328static void
329with_command_completer (struct cmd_list_element *ignore,
330 completion_tracker &tracker,
331 const char *text, const char * /*word*/)
332{
333 with_command_completer_1 ("set ", tracker, text);
334}
335
cf00cd6f
PW
336/* Look up the contents of TEXT as a command usable with default args.
337 Throws an error if no such command is found.
338 Return the found command and advances TEXT past the found command.
339 If the found command is a postfix command, set *PREFIX_CMD to its
340 prefix command. */
341
342static struct cmd_list_element *
343lookup_cmd_for_default_args (const char **text,
344 struct cmd_list_element **prefix_cmd)
345{
346 const char *orig_text = *text;
347 struct cmd_list_element *lcmd;
348
349 if (*text == nullptr || skip_spaces (*text) == nullptr)
350 error (_("ALIAS missing."));
351
352 /* We first use lookup_cmd to verify TEXT unambiguously identifies
353 a command. */
354 lcmd = lookup_cmd (text, cmdlist, "", NULL,
355 /*allow_unknown=*/ 0,
356 /*ignore_help_classes=*/ 1);
357
358 /* Note that we accept default args for prefix commands,
359 as a prefix command can also be a valid usable
360 command accepting some arguments.
361 For example, "thread apply" applies a command to a
362 list of thread ids, and is also the prefix command for
363 thread apply all. */
364
365 /* We have an unambiguous command for which default args
366 can be specified. What remains after having found LCMD
367 is either spaces, or the default args character. */
368
369 /* We then use lookup_cmd_composition to detect if the user
370 has specified an alias, and find the possible prefix_cmd
371 of cmd. */
372 struct cmd_list_element *alias, *cmd;
373 lookup_cmd_composition
374 (std::string (orig_text, *text - orig_text).c_str (),
375 &alias, prefix_cmd, &cmd);
376 gdb_assert (cmd != nullptr);
377 gdb_assert (cmd == lcmd);
378 if (alias != nullptr)
379 cmd = alias;
380
381 return cmd;
382}
383
d318976c
FN
384/* Provide documentation on command or list given by COMMAND. FROM_TTY
385 is ignored. */
386
d318976c 387static void
0b39b52e 388help_command (const char *command, int from_tty)
d318976c
FN
389{
390 help_cmd (command, gdb_stdout);
391}
392\f
eb3ff9a5 393
ef0b411a
GB
394/* Note: The "complete" command is used by Emacs to implement completion.
395 [Is that why this function writes output with *_unfiltered?] */
d318976c 396
d318976c 397static void
0b39b52e 398complete_command (const char *arg, int from_tty)
d318976c 399{
d318976c
FN
400 dont_repeat ();
401
ef0b411a
GB
402 if (max_completions == 0)
403 {
404 /* Only print this for non-mi frontends. An MI frontend may not
405 be able to handle this. */
112e8700 406 if (!current_uiout->is_mi_like_p ())
ef0b411a
GB
407 {
408 printf_unfiltered (_("max-completions is zero,"
409 " completion is disabled.\n"));
410 }
411 return;
412 }
413
d318976c
FN
414 if (arg == NULL)
415 arg = "";
d9b52655 416
6a2c1b87
PA
417 int quote_char = '\0';
418 const char *word;
419
6e035501 420 completion_result result = complete (arg, &word, &quote_char);
eb3ff9a5 421
eb3ff9a5
PA
422 if (result.number_matches != 0)
423 {
fb7806c7
TV
424 std::string arg_prefix (arg, word - arg);
425
eb3ff9a5
PA
426 if (result.number_matches == 1)
427 printf_unfiltered ("%s%s\n", arg_prefix.c_str (), result.match_list[0]);
428 else
83d31a92 429 {
eb3ff9a5
PA
430 result.sort_match_list ();
431
432 for (size_t i = 0; i < result.number_matches; i++)
83d31a92 433 {
eb3ff9a5
PA
434 printf_unfiltered ("%s%s",
435 arg_prefix.c_str (),
436 result.match_list[i + 1]);
6a2c1b87
PA
437 if (quote_char)
438 printf_unfiltered ("%c", quote_char);
eb3ff9a5 439 printf_unfiltered ("\n");
83d31a92 440 }
83d31a92
TT
441 }
442
eb3ff9a5 443 if (result.number_matches == max_completions)
ef0b411a 444 {
6a2c1b87 445 /* ARG_PREFIX and WORD are included in the output so that emacs
ef0b411a
GB
446 will include the message in the output. */
447 printf_unfiltered (_("%s%s %s\n"),
6a2c1b87 448 arg_prefix.c_str (), word,
ef0b411a
GB
449 get_max_completions_reached_message ());
450 }
d318976c
FN
451 }
452}
453
bbaca940
AC
454int
455is_complete_command (struct cmd_list_element *c)
d318976c 456{
3a553c80 457 return cmd_simple_func_eq (c, complete_command);
d318976c
FN
458}
459
d318976c 460static void
dede02ce 461show_version (const char *args, int from_tty)
d318976c 462{
c61b06a1 463 print_gdb_version (gdb_stdout, true);
6cb06a8c 464 gdb_printf ("\n");
d318976c
FN
465}
466
6eaaf48b 467static void
dede02ce 468show_configuration (const char *args, int from_tty)
6eaaf48b
EZ
469{
470 print_gdb_configuration (gdb_stdout);
471}
472
d318976c
FN
473/* Handle the quit command. */
474
475void
0b39b52e 476quit_command (const char *args, int from_tty)
d318976c 477{
36cf1806
TT
478 int exit_code = 0;
479
480 /* An optional expression may be used to cause gdb to terminate with
481 the value of that expression. */
482 if (args)
483 {
484 struct value *val = parse_and_eval (args);
485
486 exit_code = (int) value_as_long (val);
487 }
488
d318976c 489 if (!quit_confirm ())
8a3fe4f8 490 error (_("Not confirmed."));
d5551862 491
be6a2dca
TV
492 try
493 {
494 query_if_trace_running (from_tty);
495 }
496 catch (const gdb_exception_error &ex)
497 {
498 if (ex.error == TARGET_CLOSE_ERROR)
499 /* We don't care about this since we're quitting anyway, so keep
500 quitting. */
501 exception_print (gdb_stderr, ex);
502 else
503 /* Rethrow, to properly handle error (_("Not confirmed.")). */
504 throw;
505 }
d5551862 506
36cf1806 507 quit_force (args ? &exit_code : NULL, from_tty);
d318976c
FN
508}
509
d318976c 510static void
0b39b52e 511pwd_command (const char *args, int from_tty)
d318976c
FN
512{
513 if (args)
8a3fe4f8 514 error (_("The \"pwd\" command does not take an argument: %s"), args);
43573013
SDJ
515
516 gdb::unique_xmalloc_ptr<char> cwd (getcwd (NULL, 0));
517
518 if (cwd == NULL)
bf1d7d9c 519 error (_("Error finding name of working directory: %s"),
dda83cd7 520 safe_strerror (errno));
d318976c 521
43573013 522 if (strcmp (cwd.get (), current_directory) != 0)
6cb06a8c
TT
523 gdb_printf (_("Working directory %ps\n (canonically %ps).\n"),
524 styled_string (file_name_style.style (),
525 current_directory),
526 styled_string (file_name_style.style (), cwd.get ()));
d318976c 527 else
6cb06a8c
TT
528 gdb_printf (_("Working directory %ps.\n"),
529 styled_string (file_name_style.style (),
530 current_directory));
d318976c
FN
531}
532
533void
5e93d4c6 534cd_command (const char *dir, int from_tty)
d318976c
FN
535{
536 int len;
537 /* Found something other than leading repetitions of "/..". */
538 int found_real_path;
539 char *p;
540
541 /* If the new directory is absolute, repeat is a no-op; if relative,
542 repeat might be useful but is more likely to be a mistake. */
543 dont_repeat ();
544
6eecf35f
TT
545 gdb::unique_xmalloc_ptr<char> dir_holder
546 (tilde_expand (dir != NULL ? dir : "~"));
547 dir = dir_holder.get ();
d318976c
FN
548
549 if (chdir (dir) < 0)
550 perror_with_name (dir);
551
c3690141 552#ifdef HAVE_DOS_BASED_FILE_SYSTEM
d318976c
FN
553 /* There's too much mess with DOSish names like "d:", "d:.",
554 "d:./foo" etc. Instead of having lots of special #ifdef'ed code,
555 simply get the canonicalized name of the current directory. */
43573013
SDJ
556 gdb::unique_xmalloc_ptr<char> cwd (getcwd (NULL, 0));
557 dir = cwd.get ();
d318976c
FN
558#endif
559
560 len = strlen (dir);
fe4e3eb8 561 if (IS_DIR_SEPARATOR (dir[len - 1]))
d318976c
FN
562 {
563 /* Remove the trailing slash unless this is a root directory
dda83cd7 564 (including a drive letter on non-Unix systems). */
d318976c 565 if (!(len == 1) /* "/" */
c3690141 566#ifdef HAVE_DOS_BASED_FILE_SYSTEM
fe4e3eb8 567 && !(len == 3 && dir[1] == ':') /* "d:/" */
d318976c
FN
568#endif
569 )
570 len--;
571 }
572
6eecf35f
TT
573 dir_holder.reset (savestring (dir, len));
574 if (IS_ABSOLUTE_PATH (dir_holder.get ()))
43573013
SDJ
575 {
576 xfree (current_directory);
577 current_directory = dir_holder.release ();
578 }
d318976c
FN
579 else
580 {
fe4e3eb8 581 if (IS_DIR_SEPARATOR (current_directory[strlen (current_directory) - 1]))
6eecf35f
TT
582 current_directory = concat (current_directory, dir_holder.get (),
583 (char *) NULL);
d318976c 584 else
1754f103 585 current_directory = concat (current_directory, SLASH_STRING,
6eecf35f 586 dir_holder.get (), (char *) NULL);
d318976c
FN
587 }
588
589 /* Now simplify any occurrences of `.' and `..' in the pathname. */
590
591 found_real_path = 0;
592 for (p = current_directory; *p;)
593 {
fe4e3eb8
EZ
594 if (IS_DIR_SEPARATOR (p[0]) && p[1] == '.'
595 && (p[2] == 0 || IS_DIR_SEPARATOR (p[2])))
b2a3b509 596 memmove (p, p + 2, strlen (p + 2) + 1);
fe4e3eb8
EZ
597 else if (IS_DIR_SEPARATOR (p[0]) && p[1] == '.' && p[2] == '.'
598 && (p[3] == 0 || IS_DIR_SEPARATOR (p[3])))
d318976c
FN
599 {
600 if (found_real_path)
601 {
602 /* Search backwards for the directory just before the "/.."
dda83cd7 603 and obliterate it and the "/..". */
d318976c 604 char *q = p;
cdb27c12 605
fe4e3eb8 606 while (q != current_directory && !IS_DIR_SEPARATOR (q[-1]))
d318976c
FN
607 --q;
608
609 if (q == current_directory)
610 /* current_directory is
611 a relative pathname ("can't happen"--leave it alone). */
612 ++p;
613 else
614 {
b2a3b509 615 memmove (q - 1, p + 3, strlen (p + 3) + 1);
d318976c
FN
616 p = q - 1;
617 }
618 }
619 else
ebcd3b23
MS
620 /* We are dealing with leading repetitions of "/..", for
621 example "/../..", which is the Mach super-root. */
d318976c
FN
622 p += 3;
623 }
624 else
625 {
626 found_real_path = 1;
627 ++p;
628 }
629 }
630
631 forget_cached_source_info ();
632
633 if (from_tty)
634 pwd_command ((char *) 0, 1);
635}
636\f
973817a3
JB
637/* Show the current value of the 'script-extension' option. */
638
639static void
640show_script_ext_mode (struct ui_file *file, int from_tty,
641 struct cmd_list_element *c, const char *value)
d318976c 642{
6cb06a8c
TT
643 gdb_printf (file,
644 _("Script filename extension recognition is \"%s\".\n"),
645 value);
973817a3
JB
646}
647
3f7b2faa
DE
648/* Try to open SCRIPT_FILE.
649 If successful, the full path name is stored in *FULL_PATHP,
ed166945
TT
650 and the stream is returned.
651 If not successful, return NULL; errno is set for the last file
3f7b2faa
DE
652 we tried to open.
653
654 If SEARCH_PATH is non-zero, and the file isn't found in cwd,
f5b95b50 655 search for it in the source search path. */
3f7b2faa 656
6b09f134 657std::optional<open_script>
ed166945 658find_and_open_script (const char *script_file, int search_path)
973817a3 659{
4b505b12 660 int fd;
24b9144d 661 openp_flags search_flags = OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH;
6b09f134 662 std::optional<open_script> opened;
d318976c 663
ee0c3293 664 gdb::unique_xmalloc_ptr<char> file (tilde_expand (script_file));
d318976c 665
3f7b2faa
DE
666 if (search_path)
667 search_flags |= OPF_SEARCH_IN_PATH;
4b505b12 668
3f7b2faa
DE
669 /* Search for and open 'file' on the search path used for source
670 files. Put the full location in *FULL_PATHP. */
e0cc99a6 671 gdb::unique_xmalloc_ptr<char> full_path;
e0700ba4 672 fd = openp (source_path.c_str (), search_flags,
e0cc99a6 673 file.get (), O_RDONLY, &full_path);
4b505b12
AS
674
675 if (fd == -1)
ee0c3293 676 return opened;
973817a3 677
ed166945
TT
678 FILE *result = fdopen (fd, FOPEN_RT);
679 if (result == NULL)
77a35dd8
JK
680 {
681 int save_errno = errno;
682
683 close (fd);
77a35dd8 684 errno = save_errno;
77a35dd8 685 }
ed166945
TT
686 else
687 opened.emplace (gdb_file_up (result), std::move (full_path));
77a35dd8 688
ed166945 689 return opened;
973817a3
JB
690}
691
1a70ae97
DE
692/* Load script FILE, which has already been opened as STREAM.
693 FILE_TO_OPEN is the form of FILE to use if one needs to open the file.
694 This is provided as FILE may have been found via the source search path.
695 An important thing to note here is that FILE may be a symlink to a file
696 with a different or non-existing suffix, and thus one cannot infer the
697 extension language from FILE_TO_OPEN. */
973817a3 698
3f7b2faa 699static void
1a70ae97
DE
700source_script_from_stream (FILE *stream, const char *file,
701 const char *file_to_open)
3f7b2faa 702{
6dddc817 703 if (script_ext_mode != script_ext_off)
973817a3 704 {
6dddc817
DE
705 const struct extension_language_defn *extlang
706 = get_ext_lang_of_file (file);
707
708 if (extlang != NULL)
973817a3 709 {
6dddc817
DE
710 if (ext_lang_present_p (extlang))
711 {
712 script_sourcer_func *sourcer
713 = ext_lang_script_sourcer (extlang);
714
715 gdb_assert (sourcer != NULL);
1a70ae97 716 sourcer (extlang, stream, file_to_open);
6dddc817
DE
717 return;
718 }
719 else if (script_ext_mode == script_ext_soft)
720 {
721 /* Assume the file is a gdb script.
722 This is handled below. */
723 }
724 else
725 throw_ext_lang_unsupported (extlang);
973817a3
JB
726 }
727 }
6dddc817
DE
728
729 script_from_file (stream, file);
3f7b2faa 730}
d318976c 731
3f7b2faa
DE
732/* Worker to perform the "source" command.
733 Load script FILE.
734 If SEARCH_PATH is non-zero, and the file isn't found in cwd,
735 search for it in the source search path. */
736
737static void
738source_script_with_search (const char *file, int from_tty, int search_path)
739{
3f7b2faa
DE
740
741 if (file == NULL || *file == 0)
742 error (_("source command requires file name of file to source."));
743
6b09f134 744 std::optional<open_script> opened = find_and_open_script (file, search_path);
ed166945 745 if (!opened)
3f7b2faa 746 {
d234ef5c 747 /* The script wasn't found, or was otherwise inaccessible.
dda83cd7 748 If the source command was invoked interactively, throw an
ebcd3b23 749 error. Otherwise (e.g. if it was invoked by a script),
7c647d61 750 just emit a warning, rather than cause an error. */
3f7b2faa
DE
751 if (from_tty)
752 perror_with_name (file);
753 else
7c647d61
JB
754 {
755 perror_warning_with_name (file);
756 return;
757 }
3f7b2faa
DE
758 }
759
d234ef5c
DE
760 /* The python support reopens the file, so we need to pass full_path here
761 in case the file was found on the search path. It's useful to do this
762 anyway so that error messages show the actual file used. But only do
763 this if we (may have) used search_path, as printing the full path in
764 errors for the non-search case can be more noise than signal. */
1845e254 765 const char *file_to_open;
e0c34637 766 std::string tilde_expanded_file;
1845e254
AB
767 if (search_path)
768 file_to_open = opened->full_path.get ();
769 else
770 {
e0c34637
SM
771 tilde_expanded_file = gdb_tilde_expand (file);
772 file_to_open = tilde_expanded_file.c_str ();
1845e254
AB
773 }
774 source_script_from_stream (opened->stream.get (), file, file_to_open);
d318976c
FN
775}
776
3f7b2faa
DE
777/* Wrapper around source_script_with_search to export it to main.c
778 for use in loading .gdbinit scripts. */
779
780void
50dd9793 781source_script (const char *file, int from_tty)
3f7b2faa
DE
782{
783 source_script_with_search (file, from_tty, 0);
784}
785
16026cd7 786static void
dede02ce 787source_command (const char *args, int from_tty)
16026cd7 788{
dede02ce 789 const char *file = args;
3f7b2faa 790 int search_path = 0;
16026cd7 791
2ec845e7 792 scoped_restore save_source_verbose = make_scoped_restore (&source_verbose);
16026cd7
AS
793
794 /* -v causes the source command to run in verbose mode.
3f7b2faa
DE
795 -s causes the file to be searched in the source search path,
796 even if the file name contains a '/'.
16026cd7
AS
797 We still have to be able to handle filenames with spaces in a
798 backward compatible way, so buildargv is not appropriate. */
799
800 if (args)
801 {
3f7b2faa 802 while (args[0] != '\0')
16026cd7 803 {
ebcd3b23
MS
804 /* Make sure leading white space does not break the
805 comparisons. */
529480d0 806 args = skip_spaces (args);
3f7b2faa
DE
807
808 if (args[0] != '-')
809 break;
810
811 if (args[1] == 'v' && isspace (args[2]))
812 {
813 source_verbose = 1;
814
815 /* Skip passed -v. */
816 args = &args[3];
817 }
818 else if (args[1] == 's' && isspace (args[2]))
819 {
820 search_path = 1;
16026cd7 821
3f7b2faa
DE
822 /* Skip passed -s. */
823 args = &args[3];
824 }
825 else
826 break;
16026cd7 827 }
3f7b2faa 828
529480d0 829 file = skip_spaces (args);
16026cd7
AS
830 }
831
3f7b2faa 832 source_script_with_search (file, from_tty, search_path);
16026cd7
AS
833}
834
835
d318976c 836static void
0b39b52e 837echo_command (const char *text, int from_tty)
d318976c 838{
d7561cbb 839 const char *p = text;
d5b5ac79 840 int c;
d318976c
FN
841
842 if (text)
843 while ((c = *p++) != '\0')
844 {
845 if (c == '\\')
846 {
847 /* \ at end of argument is used after spaces
848 so they won't be lost. */
849 if (*p == 0)
850 return;
851
f870a310 852 c = parse_escape (get_current_arch (), &p);
d318976c 853 if (c >= 0)
6cb06a8c 854 gdb_printf ("%c", c);
d318976c
FN
855 }
856 else
6cb06a8c 857 gdb_printf ("%c", c);
d318976c
FN
858 }
859
3cd52293 860 gdb_stdout->reset_style ();
ef1dfa36 861
d318976c 862 /* Force this output to appear now. */
d318976c
FN
863 gdb_flush (gdb_stdout);
864}
865
947d3946
PW
866/* Sets the last launched shell command convenience variables based on
867 EXIT_STATUS. */
868
869static void
870exit_status_set_internal_vars (int exit_status)
871{
872 struct internalvar *var_code = lookup_internalvar ("_shell_exitcode");
873 struct internalvar *var_signal = lookup_internalvar ("_shell_exitsignal");
874
875 clear_internalvar (var_code);
876 clear_internalvar (var_signal);
91265a7d
PA
877
878 /* Keep the logic here in sync with shell_internal_fn. */
879
947d3946
PW
880 if (WIFEXITED (exit_status))
881 set_internalvar_integer (var_code, WEXITSTATUS (exit_status));
559e7e50
EZ
882#ifdef __MINGW32__
883 else if (WIFSIGNALED (exit_status) && WTERMSIG (exit_status) == -1)
884 {
885 /* The -1 condition can happen on MinGW, if we don't recognize
886 the fatal exception code encoded in the exit status; see
887 gdbsupport/gdb_wait.c. We don't want to lose information in
888 the exit status in that case. Record it as a normal exit
889 with the full exit status, including the higher 0xC0000000
890 bits. */
891 set_internalvar_integer (var_code, exit_status);
892 }
893#endif
947d3946
PW
894 else if (WIFSIGNALED (exit_status))
895 set_internalvar_integer (var_signal, WTERMSIG (exit_status));
896 else
422186a9 897 warning (_("unexpected shell command exit status %d"), exit_status);
947d3946
PW
898}
899
91265a7d
PA
900/* Run ARG under the shell, and return the exit status. If ARG is
901 NULL, run an interactive shell. */
902
903static int
904run_under_shell (const char *arg, int from_tty)
d318976c 905{
9b265ec2
MM
906#if defined(CANT_FORK) || \
907 (!defined(HAVE_WORKING_VFORK) && !defined(HAVE_WORKING_FORK))
d318976c
FN
908 /* If ARG is NULL, they want an inferior shell, but `system' just
909 reports if the shell is available when passed a NULL arg. */
910 int rc = system (arg ? arg : "");
911
912 if (!arg)
913 arg = "inferior shell";
914
915 if (rc == -1)
6cb06a8c
TT
916 gdb_printf (gdb_stderr, "Cannot execute %s: %s\n", arg,
917 safe_strerror (errno));
d318976c 918 else if (rc)
6cb06a8c 919 gdb_printf (gdb_stderr, "%s exited with status %d\n", arg, rc);
2584159e 920#ifdef GLOBAL_CURDIR
ebcd3b23
MS
921 /* Make sure to return to the directory GDB thinks it is, in case
922 the shell command we just ran changed it. */
d318976c
FN
923 chdir (current_directory);
924#endif
91265a7d 925 return rc;
d318976c 926#else /* Can fork. */
5be4dfca 927 int status, pid;
d318976c 928
325ed089 929 if ((pid = vfork ()) == 0)
d318976c 930 {
974e6844 931 const char *p, *user_shell = get_shell ();
30e94205 932
614c279d
TT
933 close_most_fds ();
934
ebcd3b23 935 /* Get the name of the shell for arg0. */
9f37bbcc 936 p = lbasename (user_shell);
30e94205 937
d318976c 938 if (!arg)
36662fde 939 execl (user_shell, p, (char *) 0);
d318976c 940 else
36662fde 941 execl (user_shell, p, "-c", arg, (char *) 0);
d318976c 942
6cb06a8c
TT
943 gdb_printf (gdb_stderr, "Cannot execute %s: %s\n", user_shell,
944 safe_strerror (errno));
d318976c
FN
945 _exit (0177);
946 }
947
948 if (pid != -1)
5be4dfca 949 waitpid (pid, &status, 0);
d318976c 950 else
8a3fe4f8 951 error (_("Fork failed"));
91265a7d 952 return status;
d318976c
FN
953#endif /* Can fork. */
954}
955
91265a7d
PA
956/* Escape out to the shell to run ARG. If ARG is NULL, launch and
957 interactive shell. Sets $_shell_exitcode and $_shell_exitsignal
958 convenience variables based on the exits status. */
959
960static void
961shell_escape (const char *arg, int from_tty)
962{
963 int status = run_under_shell (arg, from_tty);
964 exit_status_set_internal_vars (status);
965}
966
be47f9e8
PA
967/* Implementation of the "shell" command. */
968
969static void
0b39b52e 970shell_command (const char *arg, int from_tty)
be47f9e8
PA
971{
972 shell_escape (arg, from_tty);
973}
974
0378c332 975static void
0b39b52e 976edit_command (const char *arg, int from_tty)
0378c332 977{
0378c332
FN
978 struct symtab_and_line sal;
979 struct symbol *sym;
a121b7c1 980 const char *editor;
0b0865da 981 const char *fn;
0378c332 982
d5529a84 983 /* Pull in the current default source line if necessary. */
0378c332 984 if (arg == 0)
53cb0458
FN
985 {
986 set_default_source_symtab_and_line ();
987 sal = get_current_source_symtab_and_line ();
988 }
0378c332 989
ebcd3b23 990 /* Bare "edit" edits file with present line. */
0378c332
FN
991
992 if (arg == 0)
993 {
994 if (sal.symtab == 0)
8a3fe4f8 995 error (_("No default source file yet."));
0378c332
FN
996 sal.line += get_lines_to_list () / 2;
997 }
998 else
999 {
f2fc3015 1000 const char *arg1;
0378c332 1001
f00aae0f 1002 /* Now should only be one argument -- decode it in SAL. */
0378c332 1003 arg1 = arg;
264f9890
PA
1004 location_spec_up locspec = string_to_location_spec (&arg1,
1005 current_language);
82d0a72c
AB
1006
1007 if (*arg1)
1008 error (_("Junk at end of line specification."));
1009
264f9890 1010 std::vector<symtab_and_line> sals = decode_line_1 (locspec.get (),
6c5b2ebe
PA
1011 DECODE_LINE_LIST_MODE,
1012 NULL, NULL, 0);
0378c332 1013
6c5b2ebe
PA
1014 filter_sals (sals);
1015 if (sals.empty ())
d5529a84
TT
1016 {
1017 /* C++ */
1018 return;
1019 }
6c5b2ebe 1020 if (sals.size () > 1)
d5529a84 1021 {
6c5b2ebe 1022 ambiguous_line_spec (sals,
e439fa14 1023 _("Specified line is ambiguous:\n"));
d5529a84
TT
1024 return;
1025 }
0378c332 1026
6c5b2ebe 1027 sal = sals[0];
0378c332 1028
ebcd3b23 1029 /* If line was specified by address, first print exactly which
dda83cd7
SM
1030 line, and which file. In this case, sal.symtab == 0 means
1031 address is outside of all known source files, not that user
1032 failed to give a filename. */
0378c332 1033 if (*arg == '*')
dda83cd7 1034 {
5af949e3 1035 struct gdbarch *gdbarch;
cdb27c12 1036
dda83cd7 1037 if (sal.symtab == 0)
8a3fe4f8 1038 error (_("No source file for address %s."),
2b69941d 1039 paddress (get_current_arch (), sal.pc));
5af949e3 1040
3c86fae3 1041 gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
dda83cd7
SM
1042 sym = find_pc_function (sal.pc);
1043 if (sym)
6cb06a8c
TT
1044 gdb_printf ("%s is in %s (%s:%d).\n",
1045 paddress (gdbarch, sal.pc),
1046 sym->print_name (),
1047 symtab_to_filename_for_display (sal.symtab),
1048 sal.line);
dda83cd7 1049 else
6cb06a8c
TT
1050 gdb_printf ("%s is at %s:%d.\n",
1051 paddress (gdbarch, sal.pc),
1052 symtab_to_filename_for_display (sal.symtab),
1053 sal.line);
dda83cd7 1054 }
0378c332 1055
ebcd3b23 1056 /* If what was given does not imply a symtab, it must be an
dda83cd7 1057 undebuggable symbol which means no source code. */
0378c332
FN
1058
1059 if (sal.symtab == 0)
dda83cd7 1060 error (_("No line number known for %s."), arg);
0378c332
FN
1061 }
1062
081bca4d
TT
1063 if ((editor = getenv ("EDITOR")) == NULL)
1064 editor = "/bin/ex";
a955ca71 1065
f35a17b5 1066 fn = symtab_to_fullname (sal.symtab);
0378c332 1067
a955ca71
EZ
1068 /* Quote the file name, in case it has whitespace or other special
1069 characters. */
8579fd13
AB
1070 gdb::unique_xmalloc_ptr<char> p
1071 = xstrprintf ("%s +%d \"%s\"", editor, sal.line, fn);
1072 shell_escape (p.get (), from_tty);
0378c332
FN
1073}
1074
5f4ba3e7
PA
1075/* The options for the "pipe" command. */
1076
1077struct pipe_cmd_opts
1078{
1079 /* For "-d". */
e0700ba4 1080 std::string delimiter;
5f4ba3e7
PA
1081};
1082
1083static const gdb::option::option_def pipe_cmd_option_defs[] = {
1084
1085 gdb::option::string_option_def<pipe_cmd_opts> {
1086 "d",
1087 [] (pipe_cmd_opts *opts) { return &opts->delimiter; },
1088 nullptr,
1089 N_("Indicates to use the specified delimiter string to separate\n\
1090COMMAND from SHELL_COMMAND, in alternative to |. This is useful in\n\
1091case COMMAND contains a | character."),
1092 },
1093
1094};
1095
1096/* Create an option_def_group for the "pipe" command's options, with
1097 OPTS as context. */
1098
1099static inline gdb::option::option_def_group
1100make_pipe_cmd_options_def_group (pipe_cmd_opts *opts)
1101{
1102 return {{pipe_cmd_option_defs}, opts};
1103}
1104
947d3946
PW
1105/* Implementation of the "pipe" command. */
1106
1107static void
1108pipe_command (const char *arg, int from_tty)
1109{
5f4ba3e7 1110 pipe_cmd_opts opts;
947d3946 1111
5f4ba3e7
PA
1112 auto grp = make_pipe_cmd_options_def_group (&opts);
1113 gdb::option::process_options
1114 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
1115
1116 const char *delim = "|";
e0700ba4
SM
1117 if (!opts.delimiter.empty ())
1118 delim = opts.delimiter.c_str ();
947d3946
PW
1119
1120 const char *command = arg;
1121 if (command == nullptr)
1122 error (_("Missing COMMAND"));
1123
5f4ba3e7 1124 arg = strstr (arg, delim);
947d3946
PW
1125
1126 if (arg == nullptr)
1127 error (_("Missing delimiter before SHELL_COMMAND"));
1128
1129 std::string gdb_cmd (command, arg - command);
1130
5f4ba3e7 1131 arg += strlen (delim); /* Skip the delimiter. */
947d3946
PW
1132
1133 if (gdb_cmd.empty ())
fdbc9870 1134 gdb_cmd = repeat_previous ();
947d3946
PW
1135
1136 const char *shell_command = skip_spaces (arg);
1137 if (*shell_command == '\0')
1138 error (_("Missing SHELL_COMMAND"));
1139
1140 FILE *to_shell_command = popen (shell_command, "w");
1141
1142 if (to_shell_command == nullptr)
1143 error (_("Error launching \"%s\""), shell_command);
1144
1145 try
1146 {
1147 stdio_file pipe_file (to_shell_command);
1148
1149 execute_command_to_ui_file (&pipe_file, gdb_cmd.c_str (), from_tty);
1150 }
1151 catch (...)
1152 {
1153 pclose (to_shell_command);
1154 throw;
1155 }
1156
1157 int exit_status = pclose (to_shell_command);
1158
1159 if (exit_status < 0)
1160 error (_("shell command \"%s\" failed: %s"), shell_command,
dda83cd7 1161 safe_strerror (errno));
947d3946
PW
1162 exit_status_set_internal_vars (exit_status);
1163}
1164
5f4ba3e7
PA
1165/* Completer for the pipe command. */
1166
1167static void
1168pipe_command_completer (struct cmd_list_element *ignore,
1169 completion_tracker &tracker,
1170 const char *text, const char *word_ignored)
1171{
1172 pipe_cmd_opts opts;
1173
1174 const char *org_text = text;
1175 auto grp = make_pipe_cmd_options_def_group (&opts);
1176 if (gdb::option::complete_options
1177 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp))
1178 return;
1179
1180 const char *delimiter = "|";
e0700ba4
SM
1181 if (!opts.delimiter.empty ())
1182 delimiter = opts.delimiter.c_str ();
5f4ba3e7
PA
1183
1184 /* Check if we're past option values already. */
1185 if (text > org_text && !isspace (text[-1]))
1186 return;
1187
1188 const char *delim = strstr (text, delimiter);
1189
1190 /* If we're still not past the delimiter, complete the gdb
1191 command. */
1192 if (delim == nullptr || delim == text)
1193 {
1194 complete_nested_command_line (tracker, text);
1195 return;
1196 }
1197
1198 /* We're past the delimiter. What follows is a shell command, which
1199 we don't know how to complete. */
1200}
1201
0f819434
BL
1202/* Helper for the list_command function. Prints the lines around (and
1203 including) line stored in CURSAL. ARG contains the arguments used in
1204 the command invocation, and is used to determine a special case when
1205 printing backwards. */
1206static void
1207list_around_line (const char *arg, symtab_and_line cursal)
1208{
1209 int first;
1210
1211 first = std::max (cursal.line - get_lines_to_list () / 2, 1);
1212
1213 /* A small special case --- if listing backwards, and we
1214 should list only one line, list the preceding line,
1215 instead of the exact line we've just shown after e.g.,
1216 stopping for a breakpoint. */
1217 if (arg != NULL && arg[0] == '-'
1218 && get_lines_to_list () == 1 && first > 1)
1219 first -= 1;
1220
1221 print_source_lines (cursal.symtab, source_lines_range (first), 0);
1222}
1223
0378c332 1224static void
0b39b52e 1225list_command (const char *arg, int from_tty)
0378c332 1226{
0378c332 1227 struct symbol *sym;
f2fc3015 1228 const char *arg1;
0378c332
FN
1229 int no_end = 1;
1230 int dummy_end = 0;
1231 int dummy_beg = 0;
1232 int linenum_beg = 0;
0b39b52e 1233 const char *p;
0378c332 1234
ebcd3b23 1235 /* Pull in the current default source line if necessary. */
3e3a1874 1236 if (arg == NULL || ((arg[0] == '+' || arg[0] == '-' || arg[0] == '.') && arg[1] == '\0'))
53cb0458
FN
1237 {
1238 set_default_source_symtab_and_line ();
51abb421 1239 symtab_and_line cursal = get_current_source_symtab_and_line ();
5166082f
PA
1240
1241 /* If this is the first "list" since we've set the current
1242 source line, center the listing around that line. */
3e3a1874 1243 if (get_first_line_listed () == 0 && (arg == nullptr || arg[0] != '.'))
5166082f 1244 {
0f819434 1245 list_around_line (arg, cursal);
5166082f 1246 }
0378c332 1247
f52625f1
BL
1248 /* "l" and "l +" lists the next few lines, unless we're listing past
1249 the end of the file. */
1250 else if (arg == nullptr || arg[0] == '+')
1251 {
1252 if (last_symtab_line (cursal.symtab) >= cursal.line)
1253 print_source_lines (cursal.symtab,
1254 source_lines_range (cursal.line), 0);
1255 else
1256 {
1257 error (_("End of the file was already reached, use \"list .\" to"
1258 " list the current location again"));
1259 }
1260 }
0378c332 1261
1a48ce76
AB
1262 /* "l -" lists previous ten lines, the ones before the ten just
1263 listed. */
a0def019 1264 else if (arg[0] == '-')
3b2464a8
AB
1265 {
1266 if (get_first_line_listed () == 1)
1267 error (_("Already at the start of %s."),
1268 symtab_to_filename_for_display (cursal.symtab));
0e2a2133
AB
1269 source_lines_range range (get_first_line_listed (),
1270 source_lines_range::BACKWARD);
1271 print_source_lines (cursal.symtab, range, 0);
3b2464a8 1272 }
0378c332 1273
12f567bc 1274 /* "list ." lists the default location again. */
3e3a1874
BL
1275 else if (arg[0] == '.')
1276 {
12f567bc 1277 if (target_has_stack ())
3e3a1874
BL
1278 {
1279 /* Find the current line by getting the PC of the currently
1280 selected frame, and finding the line associated to it. */
1281 frame_info_ptr frame = get_selected_frame (nullptr);
1282 CORE_ADDR curr_pc = get_frame_pc (frame);
1283 cursal = find_pc_line (curr_pc, 0);
1284 }
12f567bc 1285 else
3e3a1874 1286 {
12f567bc
GL
1287 /* The inferior is not running, so reset the current source
1288 location to the default (usually the main function). */
3e3a1874
BL
1289 clear_current_source_symtab_and_line ();
1290 set_default_source_symtab_and_line ();
1291 cursal = get_current_source_symtab_and_line ();
1292 }
0068bd6f
GL
1293 if (cursal.symtab == nullptr)
1294 error (_("No debug information available to print source lines."));
3e3a1874 1295 list_around_line (arg, cursal);
12f567bc 1296 /* Set the repeat args so just pressing "enter" after using "list ."
3e3a1874 1297 will print the following lines instead of the same lines again. */
12f567bc
GL
1298 if (from_tty)
1299 set_repeat_arguments ("");
3e3a1874
BL
1300 }
1301
0378c332
FN
1302 return;
1303 }
1304
1305 /* Now if there is only one argument, decode it in SAL
1306 and set NO_END.
1307 If there are two arguments, decode them in SAL and SAL_END
1308 and clear NO_END; however, if one of the arguments is blank,
1309 set DUMMY_BEG or DUMMY_END to record that fact. */
1310
1311 if (!have_full_symbols () && !have_partial_symbols ())
8a3fe4f8 1312 error (_("No symbol table is loaded. Use the \"file\" command."));
0378c332 1313
6c5b2ebe 1314 std::vector<symtab_and_line> sals;
51abb421 1315 symtab_and_line sal, sal_end;
6c5b2ebe 1316
0378c332
FN
1317 arg1 = arg;
1318 if (*arg1 == ',')
1319 dummy_beg = 1;
1320 else
1321 {
264f9890
PA
1322 location_spec_up locspec
1323 = string_to_location_spec (&arg1, current_language);
1324
1325 /* We know that the ARG string is not empty, yet the attempt to
1326 parse a location spec from the string consumed no characters.
1327 This most likely means that the first thing in ARG looks like
1328 a location spec condition, and so the string_to_location_spec
1329 call stopped parsing. */
3c5fcec6
AB
1330 if (arg1 == arg)
1331 error (_("Junk at end of line specification."));
1332
264f9890 1333 sals = decode_line_1 (locspec.get (), DECODE_LINE_LIST_MODE,
ffc2605c 1334 NULL, NULL, 0);
6c5b2ebe
PA
1335 filter_sals (sals);
1336 if (sals.empty ())
f00aae0f
KS
1337 {
1338 /* C++ */
f00aae0f
KS
1339 return;
1340 }
0378c332 1341
6c5b2ebe 1342 sal = sals[0];
0378c332
FN
1343 }
1344
1345 /* Record whether the BEG arg is all digits. */
1346
1347 for (p = arg; p != arg1 && *p >= '0' && *p <= '9'; p++);
1348 linenum_beg = (p == arg1);
1349
e439fa14
PA
1350 /* Save the range of the first argument, in case we need to let the
1351 user know it was ambiguous. */
1352 const char *beg = arg;
1353 size_t beg_len = arg1 - beg;
1354
0378c332
FN
1355 while (*arg1 == ' ' || *arg1 == '\t')
1356 arg1++;
1357 if (*arg1 == ',')
1358 {
1359 no_end = 0;
6c5b2ebe 1360 if (sals.size () > 1)
0d999a6e 1361 {
6c5b2ebe 1362 ambiguous_line_spec (sals,
e439fa14
PA
1363 _("Specified first line '%.*s' is ambiguous:\n"),
1364 (int) beg_len, beg);
0d999a6e
ZZ
1365 return;
1366 }
0378c332
FN
1367 arg1++;
1368 while (*arg1 == ' ' || *arg1 == '\t')
1369 arg1++;
1370 if (*arg1 == 0)
1371 dummy_end = 1;
1372 else
1373 {
e439fa14
PA
1374 /* Save the last argument, in case we need to let the user
1375 know it was ambiguous. */
1376 const char *end_arg = arg1;
1377
264f9890
PA
1378 location_spec_up locspec
1379 = string_to_location_spec (&arg1, current_language);
f00aae0f 1380
3c5fcec6
AB
1381 if (*arg1)
1382 error (_("Junk at end of line specification."));
1383
6c5b2ebe
PA
1384 std::vector<symtab_and_line> sals_end
1385 = (dummy_beg
264f9890 1386 ? decode_line_1 (locspec.get (), DECODE_LINE_LIST_MODE,
6c5b2ebe 1387 NULL, NULL, 0)
264f9890 1388 : decode_line_1 (locspec.get (), DECODE_LINE_LIST_MODE,
6c5b2ebe
PA
1389 NULL, sal.symtab, sal.line));
1390
1391 filter_sals (sals_end);
1392 if (sals_end.empty ())
1393 return;
1394 if (sals_end.size () > 1)
0d999a6e 1395 {
6c5b2ebe 1396 ambiguous_line_spec (sals_end,
e439fa14
PA
1397 _("Specified last line '%s' is ambiguous:\n"),
1398 end_arg);
0378c332
FN
1399 return;
1400 }
6c5b2ebe 1401 sal_end = sals_end[0];
0378c332
FN
1402 }
1403 }
1404
1405 if (*arg1)
8a3fe4f8 1406 error (_("Junk at end of line specification."));
0378c332
FN
1407
1408 if (!no_end && !dummy_beg && !dummy_end
1409 && sal.symtab != sal_end.symtab)
e439fa14 1410 error (_("Specified first and last lines are in different files."));
0378c332 1411 if (dummy_beg && dummy_end)
8a3fe4f8 1412 error (_("Two empty args do not say what lines to list."));
0378c332 1413
ebcd3b23 1414 /* If line was specified by address,
0378c332 1415 first print exactly which line, and which file.
ebcd3b23
MS
1416
1417 In this case, sal.symtab == 0 means address is outside of all
1418 known source files, not that user failed to give a filename. */
0378c332
FN
1419 if (*arg == '*')
1420 {
5af949e3 1421 struct gdbarch *gdbarch;
cdb27c12 1422
0378c332 1423 if (sal.symtab == 0)
8a3fe4f8 1424 error (_("No source file for address %s."),
2b69941d 1425 paddress (get_current_arch (), sal.pc));
5af949e3 1426
3c86fae3 1427 gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
0378c332
FN
1428 sym = find_pc_function (sal.pc);
1429 if (sym)
6cb06a8c
TT
1430 gdb_printf ("%s is in %s (%s:%d).\n",
1431 paddress (gdbarch, sal.pc),
1432 sym->print_name (),
1433 symtab_to_filename_for_display (sal.symtab), sal.line);
0378c332 1434 else
6cb06a8c
TT
1435 gdb_printf ("%s is at %s:%d.\n",
1436 paddress (gdbarch, sal.pc),
1437 symtab_to_filename_for_display (sal.symtab), sal.line);
0378c332
FN
1438 }
1439
ebcd3b23
MS
1440 /* If line was not specified by just a line number, and it does not
1441 imply a symtab, it must be an undebuggable symbol which means no
1442 source code. */
0378c332
FN
1443
1444 if (!linenum_beg && sal.symtab == 0)
8a3fe4f8 1445 error (_("No line number known for %s."), arg);
0378c332
FN
1446
1447 /* If this command is repeated with RET,
1448 turn it into the no-arg variant. */
1449
1450 if (from_tty)
85c4be7c 1451 set_repeat_arguments ("");
0378c332
FN
1452
1453 if (dummy_beg && sal_end.symtab == 0)
8a3fe4f8 1454 error (_("No default source file yet. Do \"help list\"."));
0378c332 1455 if (dummy_beg)
0e2a2133
AB
1456 {
1457 source_lines_range range (sal_end.line + 1,
1458 source_lines_range::BACKWARD);
1459 print_source_lines (sal_end.symtab, range, 0);
1460 }
0378c332 1461 else if (sal.symtab == 0)
8a3fe4f8 1462 error (_("No default source file yet. Do \"help list\"."));
0378c332
FN
1463 else if (no_end)
1464 {
6c5b2ebe 1465 for (int i = 0; i < sals.size (); i++)
0d999a6e 1466 {
6c5b2ebe 1467 sal = sals[i];
0d999a6e
ZZ
1468 int first_line = sal.line - get_lines_to_list () / 2;
1469 if (first_line < 1)
1470 first_line = 1;
6c5b2ebe 1471 if (sals.size () > 1)
06871ae8 1472 print_sal_location (sal);
0e2a2133 1473 print_source_lines (sal.symtab, source_lines_range (first_line), 0);
0d999a6e 1474 }
0378c332 1475 }
0e2a2133
AB
1476 else if (dummy_end)
1477 print_source_lines (sal.symtab, source_lines_range (sal.line), 0);
0378c332 1478 else
0e2a2133
AB
1479 print_source_lines (sal.symtab,
1480 source_lines_range (sal.line, (sal_end.line + 1)),
0378c332
FN
1481 0);
1482}
1483
d14508fe
DE
1484/* Subroutine of disassemble_command to simplify it.
1485 Perform the disassembly.
1486 NAME is the name of the function if known, or NULL.
1487 [LOW,HIGH) are the range of addresses to disassemble.
e9480230
KB
1488 BLOCK is the block to disassemble; it needs to be provided
1489 when non-contiguous blocks are disassembled; otherwise
1490 it can be NULL.
d14508fe
DE
1491 MIXED is non-zero to print source with the assembler. */
1492
1493static void
13274fc3 1494print_disassembly (struct gdbarch *gdbarch, const char *name,
9a24775b 1495 CORE_ADDR low, CORE_ADDR high,
e9480230 1496 const struct block *block,
9a24775b 1497 gdb_disassembly_flags flags)
d14508fe
DE
1498{
1499#if defined(TUI)
f9ba974d
TT
1500 if (tui_is_window_visible (DISASSEM_WIN))
1501 tui_show_assembly (gdbarch, low);
1502 else
d14508fe
DE
1503#endif
1504 {
6cb06a8c 1505 gdb_printf (_("Dump of assembler code "));
d14508fe 1506 if (name != NULL)
6cb06a8c
TT
1507 gdb_printf (_("for function %ps:\n"),
1508 styled_string (function_name_style.style (), name));
086d03c9 1509 if (block == nullptr || block->is_contiguous ())
dda83cd7 1510 {
e9480230 1511 if (name == NULL)
6cb06a8c
TT
1512 gdb_printf (_("from %ps to %ps:\n"),
1513 styled_string (address_style.style (),
1514 paddress (gdbarch, low)),
1515 styled_string (address_style.style (),
1516 paddress (gdbarch, high)));
d14508fe 1517
e9480230
KB
1518 /* Dump the specified range. */
1519 gdb_disassembly (gdbarch, current_uiout, flags, -1, low, high);
1520 }
1521 else
dda83cd7 1522 {
f73b4922 1523 for (const blockrange &range : block->ranges ())
e9480230 1524 {
f73b4922
SM
1525 CORE_ADDR range_low = range.start ();
1526 CORE_ADDR range_high = range.end ();
1527
6cb06a8c
TT
1528 gdb_printf (_("Address range %ps to %ps:\n"),
1529 styled_string (address_style.style (),
1530 paddress (gdbarch, range_low)),
1531 styled_string (address_style.style (),
1532 paddress (gdbarch, range_high)));
b926417a
TT
1533 gdb_disassembly (gdbarch, current_uiout, flags, -1,
1534 range_low, range_high);
e9480230
KB
1535 }
1536 }
6cb06a8c 1537 gdb_printf (_("End of assembler dump.\n"));
d14508fe 1538 }
d14508fe
DE
1539}
1540
1541/* Subroutine of disassemble_command to simplify it.
9c419145 1542 Print a disassembly of the current function according to FLAGS. */
d14508fe
DE
1543
1544static void
9a24775b 1545disassemble_current_function (gdb_disassembly_flags flags)
d14508fe 1546{
bd2b40ac 1547 frame_info_ptr frame;
13274fc3 1548 struct gdbarch *gdbarch;
d14508fe 1549 CORE_ADDR low, high, pc;
2c02bd72 1550 const char *name;
e9480230 1551 const struct block *block;
d14508fe 1552
13274fc3
UW
1553 frame = get_selected_frame (_("No frame selected."));
1554 gdbarch = get_frame_arch (frame);
9bf4bce9 1555 pc = get_frame_address_in_block (frame);
e9480230 1556 if (find_pc_partial_function (pc, &name, &low, &high, &block) == 0)
d14508fe
DE
1557 error (_("No function contains program counter for selected frame."));
1558#if defined(TUI)
1559 /* NOTE: cagney/2003-02-13 The `tui_active' was previously
1560 `tui_version'. */
1561 if (tui_active)
1562 /* FIXME: cagney/2004-02-07: This should be an observer. */
13274fc3 1563 low = tui_get_low_disassembly_address (gdbarch, low, pc);
d14508fe 1564#endif
13274fc3 1565 low += gdbarch_deprecated_function_start_offset (gdbarch);
d14508fe 1566
e9480230 1567 print_disassembly (gdbarch, name, low, high, block, flags);
d14508fe
DE
1568}
1569
1570/* Dump a specified section of assembly code.
1571
1572 Usage:
6ff0ba5f 1573 disassemble [/mrs]
d14508fe 1574 - dump the assembly code for the function of the current pc
6ff0ba5f 1575 disassemble [/mrs] addr
d14508fe 1576 - dump the assembly code for the function at ADDR
6ff0ba5f
DE
1577 disassemble [/mrs] low,high
1578 disassemble [/mrs] low,+length
53a71c06 1579 - dump the assembly code in the range [LOW,HIGH), or [LOW,LOW+length)
d14508fe 1580
6ff0ba5f
DE
1581 A /m modifier will include source code with the assembly in a
1582 "source centric" view. This view lists only the file of the first insn,
1583 even if other source files are involved (e.g., inlined functions), and
1584 the output is in source order, even with optimized code. This view is
1585 considered deprecated as it hasn't been useful in practice.
1586
1587 A /r modifier will include raw instructions in hex with the assembly.
1588
d4ce49b7
AB
1589 A /b modifier is similar to /r except the instruction bytes are printed
1590 as separate bytes with no grouping, or endian switching.
1591
6ff0ba5f
DE
1592 A /s modifier will include source code with the assembly, like /m, with
1593 two important differences:
1594 1) The output is still in pc address order.
1595 2) File names and contents for all relevant source files are displayed. */
83c31e7d 1596
83c31e7d 1597static void
0b39b52e 1598disassemble_command (const char *arg, int from_tty)
83c31e7d 1599{
13274fc3 1600 struct gdbarch *gdbarch = get_current_arch ();
83c31e7d 1601 CORE_ADDR low, high;
f75a0693 1602 const general_symbol_info *symbol = nullptr;
2c02bd72 1603 const char *name;
d36fc00b 1604 CORE_ADDR pc;
9a24775b 1605 gdb_disassembly_flags flags;
bbc13ae3 1606 const char *p;
e9480230 1607 const struct block *block = nullptr;
83c31e7d 1608
bbc13ae3 1609 p = arg;
83c31e7d 1610 name = NULL;
e6158f16 1611 flags = 0;
d14508fe 1612
bbc13ae3 1613 if (p && *p == '/')
83c31e7d 1614 {
bbc13ae3 1615 ++p;
d14508fe 1616
bbc13ae3 1617 if (*p == '\0')
d14508fe
DE
1618 error (_("Missing modifier."));
1619
bbc13ae3 1620 while (*p && ! isspace (*p))
d14508fe 1621 {
bbc13ae3 1622 switch (*p++)
d14508fe
DE
1623 {
1624 case 'm':
6ff0ba5f 1625 flags |= DISASSEMBLY_SOURCE_DEPRECATED;
e6158f16
HZ
1626 break;
1627 case 'r':
1628 flags |= DISASSEMBLY_RAW_INSN;
d14508fe 1629 break;
d4ce49b7
AB
1630 case 'b':
1631 flags |= DISASSEMBLY_RAW_BYTES;
1632 break;
6ff0ba5f
DE
1633 case 's':
1634 flags |= DISASSEMBLY_SOURCE;
1635 break;
d14508fe
DE
1636 default:
1637 error (_("Invalid disassembly modifier."));
1638 }
1639 }
1640
f1735a53 1641 p = skip_spaces (p);
d14508fe
DE
1642 }
1643
6ff0ba5f
DE
1644 if ((flags & (DISASSEMBLY_SOURCE_DEPRECATED | DISASSEMBLY_SOURCE))
1645 == (DISASSEMBLY_SOURCE_DEPRECATED | DISASSEMBLY_SOURCE))
1646 error (_("Cannot specify both /m and /s."));
1647
f3a8a979
AB
1648 if ((flags & (DISASSEMBLY_RAW_INSN | DISASSEMBLY_RAW_BYTES))
1649 == (DISASSEMBLY_RAW_INSN | DISASSEMBLY_RAW_BYTES))
1650 error (_("Cannot specify both /r and /b."));
1651
bbc13ae3 1652 if (! p || ! *p)
d14508fe 1653 {
9c419145 1654 flags |= DISASSEMBLY_OMIT_FNAME;
e6158f16 1655 disassemble_current_function (flags);
d14508fe 1656 return;
83c31e7d 1657 }
d14508fe 1658
bbc13ae3
KS
1659 pc = value_as_address (parse_to_comma_and_eval (&p));
1660 if (p[0] == ',')
1661 ++p;
1662 if (p[0] == '\0')
83c31e7d
FN
1663 {
1664 /* One argument. */
f75a0693 1665 if (!find_pc_partial_function_sym (pc, &symbol, &low, &high, &block))
8a3fe4f8 1666 error (_("No function contains specified address."));
f75a0693
AB
1667
1668 if (asm_demangle)
1669 name = symbol->print_name ();
1670 else
1671 name = symbol->linkage_name ();
1672
83c31e7d 1673#if defined(TUI)
021e7609
AC
1674 /* NOTE: cagney/2003-02-13 The `tui_active' was previously
1675 `tui_version'. */
22940a24
AC
1676 if (tui_active)
1677 /* FIXME: cagney/2004-02-07: This should be an observer. */
13274fc3 1678 low = tui_get_low_disassembly_address (gdbarch, low, pc);
83c31e7d 1679#endif
13274fc3 1680 low += gdbarch_deprecated_function_start_offset (gdbarch);
9c419145 1681 flags |= DISASSEMBLY_OMIT_FNAME;
83c31e7d
FN
1682 }
1683 else
1684 {
1685 /* Two arguments. */
53a71c06 1686 int incl_flag = 0;
21a0512e 1687 low = pc;
f1735a53 1688 p = skip_spaces (p);
bbc13ae3 1689 if (p[0] == '+')
53a71c06 1690 {
bbc13ae3 1691 ++p;
53a71c06
CR
1692 incl_flag = 1;
1693 }
bbc13ae3 1694 high = parse_and_eval_address (p);
53a71c06
CR
1695 if (incl_flag)
1696 high += low;
83c31e7d
FN
1697 }
1698
e9480230 1699 print_disassembly (gdbarch, name, low, high, block, flags);
83c31e7d
FN
1700}
1701
b20885b0
AB
1702/* Command completion for the disassemble command. */
1703
1704static void
1705disassemble_command_completer (struct cmd_list_element *ignore,
1706 completion_tracker &tracker,
1707 const char *text, const char * /* word */)
1708{
1709 if (skip_over_slash_fmt (tracker, &text))
1710 return;
1711
1712 const char *word = advance_to_expression_complete_word_point (tracker, text);
1713 expression_completer (ignore, tracker, text, word);
1714}
1715
d318976c 1716static void
0b39b52e 1717make_command (const char *arg, int from_tty)
d318976c 1718{
d318976c 1719 if (arg == 0)
be47f9e8 1720 shell_escape ("make", from_tty);
d318976c
FN
1721 else
1722 {
be47f9e8 1723 std::string cmd = std::string ("make ") + arg;
d318976c 1724
be47f9e8
PA
1725 shell_escape (cmd.c_str (), from_tty);
1726 }
d318976c
FN
1727}
1728
d318976c 1729static void
dede02ce 1730show_user (const char *args, int from_tty)
d318976c
FN
1731{
1732 struct cmd_list_element *c;
d318976c
FN
1733
1734 if (args)
1735 {
6f937416 1736 const char *comname = args;
cdb27c12 1737
cf00cd6f 1738 c = lookup_cmd (&comname, cmdlist, "", NULL, 0, 1);
a9f116cb 1739 if (!cli_user_command_p (c))
8a3fe4f8 1740 error (_("Not a user command."));
adb483fe 1741 show_user_1 (c, "", args, gdb_stdout);
d318976c
FN
1742 }
1743 else
1744 {
1745 for (c = cmdlist; c; c = c->next)
1746 {
3d0b3564 1747 if (cli_user_command_p (c) || c->is_prefix ())
adb483fe 1748 show_user_1 (c, "", c->name, gdb_stdout);
d318976c
FN
1749 }
1750 }
1751}
1752
cc81bc2d
LS
1753/* Return true if COMMAND or any of its sub-commands is a user defined command.
1754 This is a helper function for show_user_completer. */
1755
1756static bool
1757has_user_subcmd (struct cmd_list_element *command)
1758{
1759 if (cli_user_command_p (command))
1760 return true;
1761
1762 /* Alias command can yield false positive. Ignore them as the targeted
1763 command should be reachable anyway. */
1764 if (command->is_alias ())
1765 return false;
1766
1767 if (command->is_prefix ())
1768 for (struct cmd_list_element *subcommand = *command->subcommands;
1769 subcommand != nullptr;
1770 subcommand = subcommand->next)
1771 if (has_user_subcmd (subcommand))
1772 return true;
1773
1774 return false;
1775}
1776
1777/* Implement completer for the 'show user' command. */
1778
1779static void
1780show_user_completer (cmd_list_element *,
1781 completion_tracker &tracker, const char *text,
1782 const char *word)
1783{
1784 struct cmd_list_element *cmd_group = cmdlist;
1785
1786 /* TEXT can contain a chain of commands and subcommands. Follow the
1787 commands chain until we reach the point where the user wants a
1788 completion. */
1789 while (word > text)
1790 {
1791 const char *curr_cmd = text;
1792 const char *after = skip_to_space (text);
1793 const size_t curr_cmd_len = after - text;
1794 text = skip_spaces (after);
1795
1796 for (struct cmd_list_element *c = cmd_group; c != nullptr; c = c->next)
1797 {
1798 if (strlen (c->name) == curr_cmd_len
1799 && strncmp (c->name, curr_cmd, curr_cmd_len) == 0)
1800 {
1801 if (c->subcommands == nullptr)
1802 /* We arrived after a command with no child, so nothing more
1803 to complete. */
1804 return;
1805
1806 cmd_group = *c->subcommands;
1807 break;
1808 }
1809 }
1810 }
1811
1812 const int wordlen = strlen (word);
1813 for (struct cmd_list_element *c = cmd_group; c != nullptr; c = c->next)
1814 if (has_user_subcmd (c))
1815 {
1816 if (strncmp (c->name, word, wordlen) == 0)
1817 tracker.add_completion
1818 (gdb::unique_xmalloc_ptr<char> (xstrdup (c->name)));
1819 }
1820}
1821
d318976c 1822/* Search through names of commands and documentations for a certain
ebcd3b23
MS
1823 regular expression. */
1824
66d8c862
PW
1825static void
1826apropos_command (const char *arg, int from_tty)
d318976c 1827{
66d8c862
PW
1828 bool verbose = arg && check_for_argument (&arg, "-v", 2);
1829
66d8c862 1830 if (arg == NULL || *arg == '\0')
f55af66d 1831 error (_("REGEXP string is empty"));
d318976c 1832
66d8c862 1833 compiled_regex pattern (arg, REG_ICASE,
2d7cc5c7 1834 _("Error in regular expression"));
dc92e161 1835
c4e37fa8 1836 apropos_cmd (gdb_stdout, cmdlist, verbose, pattern);
d318976c 1837}
5a56e9c5 1838
cf00cd6f
PW
1839/* The options for the "alias" command. */
1840
1841struct alias_opts
1842{
1843 /* For "-a". */
1844 bool abbrev_flag = false;
1845};
1846
1847static const gdb::option::option_def alias_option_defs[] = {
1848
1849 gdb::option::flag_option_def<alias_opts> {
1850 "a",
1851 [] (alias_opts *opts) { return &opts->abbrev_flag; },
1852 N_("Specify that ALIAS is an abbreviation of COMMAND.\n\
1853Abbreviations are not used in command completion."),
1854 },
1855
1856};
1857
1858/* Create an option_def_group for the "alias" options, with
1859 A_OPTS as context. */
1860
1861static gdb::option::option_def_group
1862make_alias_options_def_group (alias_opts *a_opts)
1863{
1864 return {{alias_option_defs}, a_opts};
1865}
1866
1867/* Completer for the "alias_command". */
1868
1869static void
1870alias_command_completer (struct cmd_list_element *ignore,
1871 completion_tracker &tracker,
1872 const char *text, const char *word)
1873{
1874 const auto grp = make_alias_options_def_group (nullptr);
1875
1876 tracker.set_use_custom_word_point (true);
1877
1878 if (gdb::option::complete_options
1879 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1880 return;
1881
1882 const char *delim = strchr (text, '=');
1883
1884 /* If we're past the "=" delimiter, complete the
1885 "alias ALIAS = COMMAND [DEFAULT-ARGS...]" as if the user is
1886 typing COMMAND DEFAULT-ARGS... */
1887 if (delim != text
1888 && delim != nullptr
1889 && isspace (delim[-1])
1890 && (isspace (delim[1]) || delim[1] == '\0'))
1891 {
1892 std::string new_text = std::string (delim + 1);
1893
1894 tracker.advance_custom_word_point_by (delim + 1 - text);
1895 complete_nested_command_line (tracker, new_text.c_str ());
1896 return;
1897 }
1898
1899 /* We're not yet past the "=" delimiter. Complete a command, as
1900 the user might type an alias following a prefix command. */
1901 complete_nested_command_line (tracker, text);
1902}
1903
5a56e9c5
DE
1904/* Subroutine of alias_command to simplify it.
1905 Return the first N elements of ARGV flattened back to a string
1906 with a space separating each element.
1907 ARGV may not be NULL.
1908 This does not take care of quoting elements in case they contain spaces
1909 on purpose. */
1910
a97e29d2
TT
1911static std::string
1912argv_to_string (char **argv, int n)
5a56e9c5
DE
1913{
1914 int i;
a97e29d2 1915 std::string result;
5a56e9c5
DE
1916
1917 gdb_assert (argv != NULL);
1918 gdb_assert (n >= 0 && n <= countargv (argv));
1919
1920 for (i = 0; i < n; ++i)
1921 {
1922 if (i > 0)
a97e29d2
TT
1923 result += " ";
1924 result += argv[i];
5a56e9c5
DE
1925 }
1926
1927 return result;
1928}
1929
1930/* Subroutine of alias_command to simplify it.
cf00cd6f
PW
1931 Verifies that COMMAND can have an alias:
1932 COMMAND must exist.
1933 COMMAND must not have default args.
1934 This last condition is to avoid the following:
1935 alias aaa = backtrace -full
1936 alias bbb = aaa -past-main
1937 as (at least currently), alias default args are not cumulative
1938 and the user would expect bbb to execute 'backtrace -full -past-main'
1939 while it will execute 'backtrace -past-main'. */
5a56e9c5 1940
3947f654 1941static cmd_list_element *
cf00cd6f 1942validate_aliased_command (const char *command)
5a56e9c5 1943{
cf00cd6f 1944 std::string default_args;
3947f654
SM
1945 cmd_list_element *c
1946 = lookup_cmd_1 (& command, cmdlist, NULL, &default_args, 1);
5a56e9c5
DE
1947
1948 if (c == NULL || c == (struct cmd_list_element *) -1)
cf00cd6f
PW
1949 error (_("Invalid command to alias to: %s"), command);
1950
1951 if (!default_args.empty ())
1952 error (_("Cannot define an alias of an alias that has default args"));
3947f654
SM
1953
1954 return c;
5a56e9c5
DE
1955}
1956
7f31862a
PA
1957/* Called when "alias" was incorrectly used. */
1958
1959static void
1960alias_usage_error (void)
1961{
cf00cd6f 1962 error (_("Usage: alias [-a] [--] ALIAS = COMMAND [DEFAULT-ARGS...]"));
7f31862a
PA
1963}
1964
5a56e9c5
DE
1965/* Make an alias of an existing command. */
1966
1967static void
0b39b52e 1968alias_command (const char *args, int from_tty)
5a56e9c5 1969{
cf00cd6f
PW
1970 alias_opts a_opts;
1971
1972 auto grp = make_alias_options_def_group (&a_opts);
1973 gdb::option::process_options
1974 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1975
5a56e9c5 1976 int i, alias_argc, command_argc;
0b39b52e 1977 const char *equals;
a97e29d2 1978 const char *alias, *command;
5a56e9c5
DE
1979
1980 if (args == NULL || strchr (args, '=') == NULL)
7f31862a 1981 alias_usage_error ();
5a56e9c5 1982
773a1edc
TT
1983 equals = strchr (args, '=');
1984 std::string args2 (args, equals - args);
1985
1986 gdb_argv built_alias_argv (args2.c_str ());
cf00cd6f
PW
1987
1988 const char *default_args = equals + 1;
1989 struct cmd_list_element *c_command_prefix;
1990
1991 lookup_cmd_for_default_args (&default_args, &c_command_prefix);
1992 std::string command_argv_str (equals + 1,
1993 default_args == nullptr
1994 ? strlen (equals + 1)
1995 : default_args - equals - 1);
1996 gdb_argv command_argv (command_argv_str.c_str ());
5a56e9c5 1997
773a1edc 1998 char **alias_argv = built_alias_argv.get ();
5a56e9c5
DE
1999
2000 if (alias_argv[0] == NULL || command_argv[0] == NULL
2001 || *alias_argv[0] == '\0' || *command_argv[0] == '\0')
7f31862a 2002 alias_usage_error ();
5a56e9c5
DE
2003
2004 for (i = 0; alias_argv[i] != NULL; ++i)
2005 {
2006 if (! valid_user_defined_cmd_name_p (alias_argv[i]))
2007 {
2008 if (i == 0)
2009 error (_("Invalid command name: %s"), alias_argv[i]);
2010 else
2011 error (_("Invalid command element name: %s"), alias_argv[i]);
2012 }
2013 }
2014
2015 alias_argc = countargv (alias_argv);
773a1edc 2016 command_argc = command_argv.count ();
5a56e9c5 2017
cf00cd6f 2018 /* COMMAND must exist, and cannot have default args.
5a56e9c5
DE
2019 Reconstruct the command to remove any extraneous spaces,
2020 for better error messages. */
773a1edc
TT
2021 std::string command_string (argv_to_string (command_argv.get (),
2022 command_argc));
a97e29d2 2023 command = command_string.c_str ();
3947f654 2024 cmd_list_element *target_cmd = validate_aliased_command (command);
5a56e9c5
DE
2025
2026 /* ALIAS must not exist. */
a97e29d2
TT
2027 std::string alias_string (argv_to_string (alias_argv, alias_argc));
2028 alias = alias_string.c_str ();
0605465f
PW
2029 {
2030 cmd_list_element *alias_cmd, *prefix_cmd, *cmd;
2031
2032 if (lookup_cmd_composition (alias, &alias_cmd, &prefix_cmd, &cmd))
2033 {
2034 const char *alias_name = alias_argv[alias_argc-1];
2035
2036 /* If we found an existing ALIAS_CMD, check that the prefix differ or
2037 the name differ. */
2038
2039 if (alias_cmd != nullptr
2040 && alias_cmd->prefix == prefix_cmd
2041 && strcmp (alias_name, alias_cmd->name) == 0)
2042 error (_("Alias already exists: %s"), alias);
2043
2044 /* Check ALIAS differs from the found CMD. */
2045
2046 if (cmd->prefix == prefix_cmd
2047 && strcmp (alias_name, cmd->name) == 0)
2048 error (_("Alias %s is the name of an existing command"), alias);
2049 }
2050 }
2051
5a56e9c5 2052
cf00cd6f
PW
2053 struct cmd_list_element *alias_cmd;
2054
5a56e9c5
DE
2055 /* If ALIAS is one word, it is an alias for the entire COMMAND.
2056 Example: alias spe = set print elements
2057
2058 Otherwise ALIAS and COMMAND must have the same number of words,
b65b566c
PW
2059 and every word except the last must identify the same prefix command;
2060 and the last word of ALIAS is made an alias of the last word of COMMAND.
5a56e9c5
DE
2061 Example: alias set print elms = set pr elem
2062 Note that unambiguous abbreviations are allowed. */
2063
2064 if (alias_argc == 1)
2065 {
2066 /* add_cmd requires *we* allocate space for name, hence the xstrdup. */
3947f654
SM
2067 alias_cmd = add_com_alias (xstrdup (alias_argv[0]), target_cmd,
2068 class_alias, a_opts.abbrev_flag);
5a56e9c5
DE
2069 }
2070 else
2071 {
6f937416 2072 const char *alias_prefix, *command_prefix;
5a56e9c5
DE
2073 struct cmd_list_element *c_alias, *c_command;
2074
2075 if (alias_argc != command_argc)
2076 error (_("Mismatched command length between ALIAS and COMMAND."));
2077
2078 /* Create copies of ALIAS and COMMAND without the last word,
b65b566c
PW
2079 and use that to verify the leading elements give the same
2080 prefix command. */
a97e29d2
TT
2081 std::string alias_prefix_string (argv_to_string (alias_argv,
2082 alias_argc - 1));
b65b566c 2083 std::string command_prefix_string (argv_to_string (command_argv.get (),
a97e29d2
TT
2084 command_argc - 1));
2085 alias_prefix = alias_prefix_string.c_str ();
2086 command_prefix = command_prefix_string.c_str ();
5a56e9c5 2087
cf00cd6f 2088 c_command = lookup_cmd_1 (& command_prefix, cmdlist, NULL, NULL, 1);
5a56e9c5
DE
2089 /* We've already tried to look up COMMAND. */
2090 gdb_assert (c_command != NULL
2091 && c_command != (struct cmd_list_element *) -1);
3d0b3564 2092 gdb_assert (c_command->is_prefix ());
cf00cd6f 2093 c_alias = lookup_cmd_1 (& alias_prefix, cmdlist, NULL, NULL, 1);
5a56e9c5
DE
2094 if (c_alias != c_command)
2095 error (_("ALIAS and COMMAND prefixes do not match."));
2096
2097 /* add_cmd requires *we* allocate space for name, hence the xstrdup. */
cf00cd6f 2098 alias_cmd = add_alias_cmd (xstrdup (alias_argv[alias_argc - 1]),
5e84b7ee 2099 target_cmd, class_alias, a_opts.abbrev_flag,
14b42fc4 2100 c_command->subcommands);
cf00cd6f
PW
2101 }
2102
2103 gdb_assert (alias_cmd != nullptr);
2104 gdb_assert (alias_cmd->default_args.empty ());
2105 if (default_args != nullptr)
2106 {
2107 default_args = skip_spaces (default_args);
2108
2109 alias_cmd->default_args = default_args;
5a56e9c5
DE
2110 }
2111}
d318976c 2112\f
06871ae8
PA
2113/* Print the file / line number / symbol name of the location
2114 specified by SAL. */
2115
2116static void
2117print_sal_location (const symtab_and_line &sal)
2118{
2119 scoped_restore_current_program_space restore_pspace;
2120 set_current_program_space (sal.pspace);
2121
2122 const char *sym_name = NULL;
2123 if (sal.symbol != NULL)
987012b8 2124 sym_name = sal.symbol->print_name ();
6cb06a8c
TT
2125 gdb_printf (_("file: \"%s\", line number: %d, symbol: \"%s\"\n"),
2126 symtab_to_filename_for_display (sal.symtab),
2127 sal.line, sym_name != NULL ? sym_name : "???");
06871ae8
PA
2128}
2129
0378c332 2130/* Print a list of files and line numbers which a user may choose from
ebcd3b23 2131 in order to list a function which was specified ambiguously (as
6c5b2ebe
PA
2132 with `list classname::overloadedfuncname', for example). The SALS
2133 array provides the filenames and line numbers. FORMAT is a
2134 printf-style format string used to tell the user what was
e439fa14 2135 ambiguous. */
0378c332
FN
2136
2137static void
6c5b2ebe
PA
2138ambiguous_line_spec (gdb::array_view<const symtab_and_line> sals,
2139 const char *format, ...)
0378c332 2140{
e439fa14
PA
2141 va_list ap;
2142 va_start (ap, format);
19a7b8ab 2143 gdb_vprintf (format, ap);
e439fa14
PA
2144 va_end (ap);
2145
6c5b2ebe 2146 for (const auto &sal : sals)
06871ae8 2147 print_sal_location (sal);
0378c332
FN
2148}
2149
6c5b2ebe
PA
2150/* Comparison function for filter_sals. Returns a qsort-style
2151 result. */
f8eba3c6
TT
2152
2153static int
6c5b2ebe 2154cmp_symtabs (const symtab_and_line &sala, const symtab_and_line &salb)
f8eba3c6 2155{
e4730328
SM
2156 const char *dira = sala.symtab->compunit ()->dirname ();
2157 const char *dirb = salb.symtab->compunit ()->dirname ();
f8eba3c6
TT
2158 int r;
2159
ee6f8984 2160 if (dira == NULL)
f8eba3c6 2161 {
ee6f8984 2162 if (dirb != NULL)
f8eba3c6
TT
2163 return -1;
2164 }
ee6f8984 2165 else if (dirb == NULL)
f8eba3c6 2166 {
ee6f8984 2167 if (dira != NULL)
f8eba3c6
TT
2168 return 1;
2169 }
2170 else
2171 {
ee6f8984 2172 r = filename_cmp (dira, dirb);
f8eba3c6
TT
2173 if (r)
2174 return r;
2175 }
2176
6c5b2ebe 2177 r = filename_cmp (sala.symtab->filename, salb.symtab->filename);
f8eba3c6
TT
2178 if (r)
2179 return r;
2180
6c5b2ebe 2181 if (sala.line < salb.line)
f8eba3c6 2182 return -1;
6c5b2ebe 2183 return sala.line == salb.line ? 0 : 1;
f8eba3c6
TT
2184}
2185
2186/* Remove any SALs that do not match the current program space, or
2187 which appear to be "file:line" duplicates. */
2188
2189static void
6c5b2ebe 2190filter_sals (std::vector<symtab_and_line> &sals)
f8eba3c6 2191{
6c5b2ebe
PA
2192 /* Remove SALs that do not match. */
2193 auto from = std::remove_if (sals.begin (), sals.end (),
2194 [&] (const symtab_and_line &sal)
2195 { return (sal.pspace != current_program_space || sal.symtab == NULL); });
2196
2197 /* Remove dups. */
2198 std::sort (sals.begin (), from,
2199 [] (const symtab_and_line &sala, const symtab_and_line &salb)
2200 { return cmp_symtabs (sala, salb) < 0; });
2201
2202 from = std::unique (sals.begin (), from,
2203 [&] (const symtab_and_line &sala,
2204 const symtab_and_line &salb)
2205 { return cmp_symtabs (sala, salb) == 0; });
2206
2207 sals.erase (from, sals.end ());
f8eba3c6
TT
2208}
2209
920d2a44
AC
2210static void
2211show_info_verbose (struct ui_file *file, int from_tty,
2212 struct cmd_list_element *c,
2213 const char *value)
2214{
2215 if (info_verbose)
6cb06a8c
TT
2216 gdb_printf (file,
2217 _("Verbose printing of informational messages is %s.\n"),
2218 value);
920d2a44 2219 else
6cb06a8c 2220 gdb_printf (file, _("Verbosity is %s.\n"), value);
920d2a44
AC
2221}
2222
2223static void
2224show_history_expansion_p (struct ui_file *file, int from_tty,
2225 struct cmd_list_element *c, const char *value)
2226{
6cb06a8c
TT
2227 gdb_printf (file, _("History expansion on command input is %s.\n"),
2228 value);
920d2a44
AC
2229}
2230
920d2a44
AC
2231static void
2232show_max_user_call_depth (struct ui_file *file, int from_tty,
2233 struct cmd_list_element *c, const char *value)
2234{
6cb06a8c
TT
2235 gdb_printf (file,
2236 _("The max call depth for user-defined commands is %s.\n"),
2237 value);
920d2a44
AC
2238}
2239
61fb7376
TBA
2240/* Implement 'show suppress-cli-notifications'. */
2241
2242static void
2243show_suppress_cli_notifications (ui_file *file, int from_tty,
2244 cmd_list_element *c, const char *value)
2245{
6cb06a8c
TT
2246 gdb_printf (file, _("Suppression of printing CLI notifications "
2247 "is %s.\n"), value);
61fb7376
TBA
2248}
2249
2250/* Implement 'set suppress-cli-notifications'. */
2251
2252static void
2253set_suppress_cli_notifications (const char *args, int from_tty,
2254 cmd_list_element *c)
2255{
2256 cli_suppress_notification.user_selected_context
2257 = user_wants_cli_suppress_notification;
2258 cli_suppress_notification.normal_stop
2259 = user_wants_cli_suppress_notification;
2260}
2261
9ad9b77d
PW
2262/* Returns the cmd_list_element in SHOWLIST corresponding to the first
2263 argument of ARGV, which must contain one single value.
2264 Throws an error if no value provided, or value not correct.
2265 FNNAME is used in the error message. */
2266
2267static cmd_list_element *
2268setting_cmd (const char *fnname, struct cmd_list_element *showlist,
2269 int argc, struct value **argv)
2270{
2271 if (argc == 0)
2272 error (_("You must provide an argument to %s"), fnname);
2273 if (argc != 1)
2274 error (_("You can only provide one argument to %s"), fnname);
2275
d0c97917 2276 struct type *type0 = check_typedef (argv[0]->type ());
9ad9b77d 2277
78134374
SM
2278 if (type0->code () != TYPE_CODE_ARRAY
2279 && type0->code () != TYPE_CODE_STRING)
9ad9b77d
PW
2280 error (_("First argument of %s must be a string."), fnname);
2281
ec5e9488
AB
2282 /* Not all languages null-terminate their strings, by moving the string
2283 content into a std::string we ensure that a null-terminator is added.
2284 For languages that do add a null-terminator the std::string might end
2285 up with two null characters at the end, but that's harmless. */
2286 const std::string setting ((const char *) argv[0]->contents ().data (),
2287 type0->length ());
2288 const char *a0 = setting.c_str ();
cf00cd6f 2289 cmd_list_element *cmd = lookup_cmd (&a0, showlist, "", NULL, -1, 0);
9ad9b77d 2290
cd4c4c07 2291 if (cmd == nullptr || cmd->type != show_cmd)
a02fcd08
AB
2292 {
2293 gdb_assert (showlist->prefix != nullptr);
2294 std::vector<std::string> components
2295 = showlist->prefix->command_components ();
2296 std::string full_name = components[0];
2297 for (int i = 1; i < components.size (); ++i)
2298 full_name += " " + components[i];
2299 error (_("First argument of %s must be a valid setting of the "
2300 "'%s' command."), fnname, full_name.c_str ());
2301 }
9ad9b77d
PW
2302
2303 return cmd;
2304}
2305
2306/* Builds a value from the show CMD. */
2307
2308static struct value *
1d7fe7f0 2309value_from_setting (const setting &var, struct gdbarch *gdbarch)
9ad9b77d 2310{
1d7fe7f0 2311 switch (var.type ())
9ad9b77d 2312 {
7aeb03e2 2313 case var_uinteger:
9ad9b77d 2314 case var_integer:
7aeb03e2
MR
2315 case var_pinteger:
2316 {
2317 LONGEST value
2318 = (var.type () == var_uinteger
2319 ? static_cast<LONGEST> (var.get<unsigned int> ())
2320 : static_cast<LONGEST> (var.get<int> ()));
2321
2322 if (var.extra_literals () != nullptr)
2323 for (const literal_def *l = var.extra_literals ();
2324 l->literal != nullptr;
2325 l++)
2326 if (value == l->use)
2327 {
2328 if (l->val.has_value ())
2329 value = *l->val;
2330 else
317c3ed9 2331 return value::allocate (builtin_type (gdbarch)->builtin_void);
7aeb03e2
MR
2332 break;
2333 }
2334
2335 if (var.type () == var_uinteger)
2336 return
2337 value_from_ulongest (builtin_type (gdbarch)->builtin_unsigned_int,
2338 static_cast<unsigned int> (value));
2339 else
2340 return
2341 value_from_longest (builtin_type (gdbarch)->builtin_int,
2342 static_cast<int> (value));
2343 }
9ad9b77d
PW
2344 case var_boolean:
2345 return value_from_longest (builtin_type (gdbarch)->builtin_int,
1d7fe7f0 2346 var.get<bool> () ? 1 : 0);
9ad9b77d
PW
2347 case var_auto_boolean:
2348 {
2349 int val;
2350
1d7fe7f0 2351 switch (var.get<enum auto_boolean> ())
9ad9b77d
PW
2352 {
2353 case AUTO_BOOLEAN_TRUE:
2354 val = 1;
2355 break;
2356 case AUTO_BOOLEAN_FALSE:
2357 val = 0;
2358 break;
2359 case AUTO_BOOLEAN_AUTO:
2360 val = -1;
2361 break;
2362 default:
2363 gdb_assert_not_reached ("invalid var_auto_boolean");
2364 }
2365 return value_from_longest (builtin_type (gdbarch)->builtin_int,
2366 val);
2367 }
9ad9b77d
PW
2368 case var_string:
2369 case var_string_noescape:
2370 case var_optional_filename:
2371 case var_filename:
2372 case var_enum:
1d7fe7f0
LS
2373 {
2374 const char *value;
e0700ba4 2375 size_t len;
1d7fe7f0 2376 if (var.type () == var_enum)
e0700ba4
SM
2377 {
2378 value = var.get<const char *> ();
2379 len = strlen (value);
2380 }
1d7fe7f0 2381 else
e0700ba4
SM
2382 {
2383 const std::string &st = var.get<std::string> ();
2384 value = st.c_str ();
2385 len = st.length ();
2386 }
1d7fe7f0 2387
baab3753 2388 return current_language->value_string (gdbarch, value, len);
1d7fe7f0 2389 }
9ad9b77d
PW
2390 default:
2391 gdb_assert_not_reached ("bad var_type");
2392 }
2393}
2394
2395/* Implementation of the convenience function $_gdb_setting. */
2396
2397static struct value *
2398gdb_setting_internal_fn (struct gdbarch *gdbarch,
2399 const struct language_defn *language,
2400 void *cookie, int argc, struct value **argv)
2401{
1d7fe7f0
LS
2402 cmd_list_element *show_cmd
2403 = setting_cmd ("$_gdb_setting", showlist, argc, argv);
2404
2405 gdb_assert (show_cmd->var.has_value ());
2406
2407 return value_from_setting (*show_cmd->var, gdbarch);
9ad9b77d
PW
2408}
2409
2410/* Implementation of the convenience function $_gdb_maint_setting. */
2411
2412static struct value *
2413gdb_maint_setting_internal_fn (struct gdbarch *gdbarch,
2414 const struct language_defn *language,
2415 void *cookie, int argc, struct value **argv)
2416{
1d7fe7f0
LS
2417 cmd_list_element *show_cmd
2418 = setting_cmd ("$_gdb_maint_setting", maintenance_show_cmdlist, argc, argv);
2419
2420 gdb_assert (show_cmd->var.has_value ());
2421
2422 return value_from_setting (*show_cmd->var, gdbarch);
9ad9b77d
PW
2423}
2424
2425/* Builds a string value from the show CMD. */
2426
2427static struct value *
1d7fe7f0 2428str_value_from_setting (const setting &var, struct gdbarch *gdbarch)
9ad9b77d 2429{
1d7fe7f0 2430 switch (var.type ())
9ad9b77d 2431 {
7aeb03e2 2432 case var_uinteger:
9ad9b77d 2433 case var_integer:
7aeb03e2 2434 case var_pinteger:
9ad9b77d 2435 case var_boolean:
9ad9b77d 2436 case var_auto_boolean:
9ad9b77d 2437 {
1d7fe7f0 2438 std::string cmd_val = get_setshow_command_value_string (var);
9ad9b77d 2439
baab3753
AB
2440 return current_language->value_string (gdbarch, cmd_val.c_str (),
2441 cmd_val.size ());
9ad9b77d
PW
2442 }
2443
2444 case var_string:
2445 case var_string_noescape:
2446 case var_optional_filename:
2447 case var_filename:
2448 case var_enum:
2449 /* For these cases, we do not use get_setshow_command_value_string,
2450 as this function handle some characters specially, e.g. by
1d7fe7f0
LS
2451 escaping quotevar. So, we directly use the var string value,
2452 similarly to the value_from_setting code for these casevar. */
2453 {
2454 const char *value;
e0700ba4 2455 size_t len;
1d7fe7f0 2456 if (var.type () == var_enum)
e0700ba4
SM
2457 {
2458 value = var.get<const char *> ();
2459 len = strlen (value);
2460 }
1d7fe7f0 2461 else
e0700ba4
SM
2462 {
2463 const std::string &st = var.get<std::string> ();
2464 value = st.c_str ();
2465 len = st.length ();
2466 }
9ad9b77d 2467
baab3753 2468 return current_language->value_string (gdbarch, value, len);
1d7fe7f0 2469 }
9ad9b77d
PW
2470 default:
2471 gdb_assert_not_reached ("bad var_type");
2472 }
2473}
2474
2475/* Implementation of the convenience function $_gdb_setting_str. */
2476
2477static struct value *
2478gdb_setting_str_internal_fn (struct gdbarch *gdbarch,
2479 const struct language_defn *language,
2480 void *cookie, int argc, struct value **argv)
2481{
1d7fe7f0
LS
2482 cmd_list_element *show_cmd
2483 = setting_cmd ("$_gdb_setting_str", showlist, argc, argv);
2484
2485 gdb_assert (show_cmd->var.has_value ());
2486
2487 return str_value_from_setting (*show_cmd->var, gdbarch);
9ad9b77d
PW
2488}
2489
2490
2491/* Implementation of the convenience function $_gdb_maint_setting_str. */
2492
2493static struct value *
2494gdb_maint_setting_str_internal_fn (struct gdbarch *gdbarch,
2495 const struct language_defn *language,
2496 void *cookie, int argc, struct value **argv)
2497{
1d7fe7f0
LS
2498 cmd_list_element *show_cmd
2499 = setting_cmd ("$_gdb_maint_setting_str", maintenance_show_cmdlist, argc,
2500 argv);
2501
2502 gdb_assert (show_cmd->var.has_value ());
2503
2504 return str_value_from_setting (*show_cmd->var, gdbarch);
9ad9b77d
PW
2505}
2506
91265a7d
PA
2507/* Implementation of the convenience function $_shell. */
2508
2509static struct value *
2510shell_internal_fn (struct gdbarch *gdbarch,
2511 const struct language_defn *language,
2512 void *cookie, int argc, struct value **argv)
2513{
2514 if (argc != 1)
2515 error (_("You must provide one argument for $_shell."));
2516
2517 value *val = argv[0];
2518 struct type *type = check_typedef (val->type ());
2519
2520 if (!language->is_string_type_p (type))
2521 error (_("Argument must be a string."));
2522
2523 value_print_options opts;
2524 get_no_prettyformat_print_options (&opts);
2525
2526 string_file stream;
2527 value_print (val, &stream, &opts);
2528
2529 /* We should always have two quote chars, which we'll strip. */
2530 gdb_assert (stream.size () >= 2);
2531
2532 /* Now strip them. We don't need the original string, so it's
2533 cheaper to do it in place, avoiding a string allocation. */
2534 std::string str = stream.release ();
2535 str[str.size () - 1] = 0;
2536 const char *command = str.c_str () + 1;
2537
2538 int exit_status = run_under_shell (command, 0);
2539
2540 struct type *int_type = builtin_type (gdbarch)->builtin_int;
2541
2542 /* Keep the logic here in sync with
2543 exit_status_set_internal_vars. */
2544
2545 if (WIFEXITED (exit_status))
2546 return value_from_longest (int_type, WEXITSTATUS (exit_status));
2547#ifdef __MINGW32__
2548 else if (WIFSIGNALED (exit_status) && WTERMSIG (exit_status) == -1)
2549 {
2550 /* See exit_status_set_internal_vars. */
2551 return value_from_longest (int_type, exit_status);
2552 }
2553#endif
2554 else if (WIFSIGNALED (exit_status))
2555 {
2556 /* (0x80 | SIGNO) is what most (all?) POSIX-like shells set as
2557 exit code on fatal signal termination. */
2558 return value_from_longest (int_type, 0x80 | WTERMSIG (exit_status));
2559 }
2560 else
2561 return value::allocate_optimized_out (int_type);
2562}
2563
6c265988 2564void _initialize_cli_cmds ();
d318976c 2565void
6c265988 2566_initialize_cli_cmds ()
d318976c
FN
2567{
2568 struct cmd_list_element *c;
2569
2570 /* Define the classes of commands.
1bfeeb0f 2571 They will appear in the help list in alphabetical order. */
d318976c 2572
0450cc4c 2573 add_cmd ("internals", class_maintenance, _("\
1a966eab 2574Maintenance commands.\n\
d318976c
FN
2575Some gdb commands are provided just for use by gdb maintainers.\n\
2576These commands are subject to frequent change, and may not be as\n\
1a966eab 2577well documented as user commands."),
d318976c 2578 &cmdlist);
0450cc4c
TT
2579 add_cmd ("obscure", class_obscure, _("Obscure features."), &cmdlist);
2580 add_cmd ("aliases", class_alias,
cf00cd6f 2581 _("User-defined aliases of other commands."), &cmdlist);
0450cc4c 2582 add_cmd ("user-defined", class_user, _("\
1a966eab 2583User-defined commands.\n\
d318976c 2584The commands in this class are those defined by the user.\n\
1a966eab 2585Use the \"define\" command to define a command."), &cmdlist);
0450cc4c 2586 add_cmd ("support", class_support, _("Support facilities."), &cmdlist);
49a82d50 2587 add_cmd ("status", class_info, _("Status inquiries."), &cmdlist);
0450cc4c 2588 add_cmd ("files", class_files, _("Specifying and examining files."),
1a966eab 2589 &cmdlist);
0450cc4c 2590 add_cmd ("breakpoints", class_breakpoint,
1a966eab 2591 _("Making program stop at certain points."), &cmdlist);
0450cc4c
TT
2592 add_cmd ("data", class_vars, _("Examining data."), &cmdlist);
2593 add_cmd ("stack", class_stack, _("\
1a966eab 2594Examining the stack.\n\
d318976c
FN
2595The stack is made up of stack frames. Gdb assigns numbers to stack frames\n\
2596counting from zero for the innermost (currently executing) frame.\n\n\
2597At any time gdb identifies one frame as the \"selected\" frame.\n\
2598Variable lookups are done with respect to the selected frame.\n\
2599When the program being debugged stops, gdb selects the innermost frame.\n\
1a966eab 2600The commands below can be used to select other frames by number or address."),
d318976c 2601 &cmdlist);
e98d2e6d
PW
2602#ifdef TUI
2603 add_cmd ("text-user-interface", class_tui,
2604 _("TUI is the GDB text based interface.\n\
2605In TUI mode, GDB can display several text windows showing\n\
2606the source file, the processor registers, the program disassembly, ..."), &cmdlist);
2607#endif
0450cc4c 2608 add_cmd ("running", class_run, _("Running the program."), &cmdlist);
d318976c 2609
ebcd3b23 2610 /* Define general commands. */
d318976c 2611
d729566a 2612 add_com ("pwd", class_files, pwd_command, _("\
590042fc
PW
2613Print working directory.\n\
2614This is used for your program as well."));
4f8d22e3 2615
1a966eab 2616 c = add_cmd ("cd", class_files, cd_command, _("\
d092c5a2
SDJ
2617Set working directory to DIR for debugger.\n\
2618The debugger's current working directory specifies where scripts and other\n\
2619files that can be loaded by GDB are located.\n\
2620In order to change the inferior's current working directory, the recommended\n\
2621way is to use the \"set cwd\" command."), &cmdlist);
5ba2abeb 2622 set_cmd_completer (c, filename_completer);
d318976c 2623
1bedd215
AC
2624 add_com ("echo", class_support, echo_command, _("\
2625Print a constant string. Give string as argument.\n\
d318976c
FN
2626C escape sequences may be used in the argument.\n\
2627No newline is added at the end of the argument;\n\
2628use \"\\n\" if you want a newline to be printed.\n\
2629Since leading and trailing whitespace are ignored in command arguments,\n\
2630if you want to print some you must use \"\\\" before leading whitespace\n\
1bedd215 2631to be printed or after trailing whitespace."));
d318976c 2632
973817a3
JB
2633 add_setshow_enum_cmd ("script-extension", class_support,
2634 script_ext_enums, &script_ext_mode, _("\
2635Set mode for script filename extension recognition."), _("\
2636Show mode for script filename extension recognition."), _("\
2637off == no filename extension recognition (all sourced files are GDB scripts)\n\
2638soft == evaluate script according to filename extension, fallback to GDB script"
2639 "\n\
2640strict == evaluate script according to filename extension, error if not supported"
2641 ),
2642 NULL,
2643 show_script_ext_mode,
2644 &setlist, &showlist);
2645
3947f654
SM
2646 cmd_list_element *quit_cmd
2647 = add_com ("quit", class_support, quit_command, _("\
bdb52a22 2648Exit gdb.\n\
fa8f0a0f 2649Usage: quit [EXPR] or exit [EXPR]\n\
bdb52a22
TT
2650The optional expression EXPR, if present, is evaluated and the result\n\
2651used as GDB's exit code. The default is zero."));
3947f654
SM
2652 cmd_list_element *help_cmd
2653 = add_com ("help", class_support, help_command,
1bedd215 2654 _("Print list of commands."));
3947f654
SM
2655 set_cmd_completer (help_cmd, command_completer);
2656 add_com_alias ("q", quit_cmd, class_support, 1);
fa8f0a0f 2657 add_com_alias ("exit", quit_cmd, class_support, 1);
3947f654 2658 add_com_alias ("h", help_cmd, class_support, 1);
d318976c 2659
5bf193a2
AC
2660 add_setshow_boolean_cmd ("verbose", class_support, &info_verbose, _("\
2661Set verbosity."), _("\
2662Show verbosity."), NULL,
2663 set_verbose,
920d2a44 2664 show_info_verbose,
5bf193a2 2665 &setlist, &showlist);
d318976c 2666
f54bdb6d
SM
2667 add_setshow_prefix_cmd
2668 ("history", class_support,
2669 _("Generic command for setting command history parameters."),
2670 _("Generic command for showing command history parameters."),
2671 &sethistlist, &showhistlist, &setlist, &showlist);
d318976c 2672
5bf193a2
AC
2673 add_setshow_boolean_cmd ("expansion", no_class, &history_expansion_p, _("\
2674Set history expansion on command input."), _("\
2675Show history expansion on command input."), _("\
2676Without an argument, history expansion is enabled."),
2677 NULL,
920d2a44 2678 show_history_expansion_p,
5bf193a2 2679 &sethistlist, &showhistlist);
d318976c 2680
3947f654
SM
2681 cmd_list_element *info_cmd
2682 = add_prefix_cmd ("info", class_info, info_command, _("\
1bedd215 2683Generic command for showing things about the program being debugged."),
3947f654
SM
2684 &infolist, 0, &cmdlist);
2685 add_com_alias ("i", info_cmd, class_info, 1);
2686 add_com_alias ("inf", info_cmd, class_info, 1);
d318976c
FN
2687
2688 add_com ("complete", class_obscure, complete_command,
1bedd215 2689 _("List the completions for the rest of the line as a command."));
d318976c 2690
a7b9ceb8 2691 c = add_show_prefix_cmd ("show", class_info, _("\
700b53b1 2692Generic command for showing things about the debugger."),
2f822da5 2693 &showlist, 0, &cmdlist);
d318976c 2694 /* Another way to get at the same thing. */
a7b9ceb8 2695 add_alias_cmd ("set", c, class_info, 0, &infolist);
d318976c 2696
3947f654
SM
2697 cmd_list_element *with_cmd
2698 = add_com ("with", class_vars, with_command, _("\
fdbc9870
PA
2699Temporarily set SETTING to VALUE, run COMMAND, and restore SETTING.\n\
2700Usage: with SETTING [VALUE] [-- COMMAND]\n\
2701Usage: w SETTING [VALUE] [-- COMMAND]\n\
2702With no COMMAND, repeats the last executed command.\n\
2703\n\
2704SETTING is any setting you can change with the \"set\" subcommands.\n\
2705E.g.:\n\
2706 with language pascal -- print obj\n\
2707 with print elements unlimited -- print obj\n\
2708\n\
2709You can change multiple settings using nested with, and use\n\
2710abbreviations for commands and/or values. E.g.:\n\
2711 w la p -- w p el u -- p obj"));
3947f654
SM
2712 set_cmd_completer_handle_brkchars (with_cmd, with_command_completer);
2713 add_com_alias ("w", with_cmd, class_vars, 1);
fdbc9870 2714
9ad9b77d
PW
2715 add_internal_function ("_gdb_setting_str", _("\
2716$_gdb_setting_str - returns the value of a GDB setting as a string.\n\
2717Usage: $_gdb_setting_str (setting)\n\
2718\n\
2719auto-boolean values are \"off\", \"on\", \"auto\".\n\
2720boolean values are \"off\", \"on\".\n\
2721Some integer settings accept an unlimited value, returned\n\
2722as \"unlimited\"."),
2723 gdb_setting_str_internal_fn, NULL);
2724
2725 add_internal_function ("_gdb_setting", _("\
2726$_gdb_setting - returns the value of a GDB setting.\n\
2727Usage: $_gdb_setting (setting)\n\
2728auto-boolean values are \"off\", \"on\", \"auto\".\n\
2729boolean values are \"off\", \"on\".\n\
2730Some integer settings accept an unlimited value, returned\n\
2731as 0 or -1 depending on the setting."),
2732 gdb_setting_internal_fn, NULL);
2733
2734 add_internal_function ("_gdb_maint_setting_str", _("\
2735$_gdb_maint_setting_str - returns the value of a GDB maintenance setting as a string.\n\
2736Usage: $_gdb_maint_setting_str (setting)\n\
2737\n\
2738auto-boolean values are \"off\", \"on\", \"auto\".\n\
2739boolean values are \"off\", \"on\".\n\
2740Some integer settings accept an unlimited value, returned\n\
2741as \"unlimited\"."),
2742 gdb_maint_setting_str_internal_fn, NULL);
2743
2744 add_internal_function ("_gdb_maint_setting", _("\
2745$_gdb_maint_setting - returns the value of a GDB maintenance setting.\n\
2746Usage: $_gdb_maint_setting (setting)\n\
2747auto-boolean values are \"off\", \"on\", \"auto\".\n\
2748boolean values are \"off\", \"on\".\n\
2749Some integer settings accept an unlimited value, returned\n\
2750as 0 or -1 depending on the setting."),
2751 gdb_maint_setting_internal_fn, NULL);
2752
91265a7d
PA
2753 add_internal_function ("_shell", _("\
2754$_shell - execute a shell command and return the result.\n\
2755\n\
2756 Usage: $_shell (COMMAND)\n\
2757\n\
2758 Arguments:\n\
2759\n\
2760 COMMAND: The command to execute. Must be a string.\n\
2761\n\
2762 Returns:\n\
2763 The command's exit code: zero on success, non-zero otherwise."),
2764 shell_internal_fn, NULL);
2765
db5f229b 2766 add_cmd ("commands", no_set_class, show_commands, _("\
1a966eab 2767Show the history of commands you typed.\n\
d318976c 2768You can supply a command number to start with, or a `+' to start after\n\
1a966eab 2769the previous command number shown."),
d318976c
FN
2770 &showlist);
2771
db5f229b 2772 add_cmd ("version", no_set_class, show_version,
1a966eab 2773 _("Show what version of GDB this is."), &showlist);
d318976c 2774
6eaaf48b
EZ
2775 add_cmd ("configuration", no_set_class, show_configuration,
2776 _("Show how GDB was configured at build time."), &showlist);
2777
f54bdb6d
SM
2778 add_setshow_prefix_cmd ("debug", no_class,
2779 _("Generic command for setting gdb debugging flags."),
2780 _("Generic command for showing gdb debugging flags."),
2781 &setdebuglist, &showdebuglist,
2782 &setlist, &showlist);
d318976c 2783
3947f654
SM
2784 cmd_list_element *shell_cmd
2785 = add_com ("shell", class_support, shell_command, _("\
1bedd215
AC
2786Execute the rest of the line as a shell command.\n\
2787With no arguments, run an inferior shell."));
3947f654 2788 set_cmd_completer (shell_cmd, filename_completer);
d318976c 2789
3947f654 2790 add_com_alias ("!", shell_cmd, class_support, 0);
d563b953 2791
1bedd215
AC
2792 c = add_com ("edit", class_files, edit_command, _("\
2793Edit specified file or function.\n\
0378c332 2794With no argument, edits file containing most recent line listed.\n\
0378c332
FN
2795Editing targets can be specified in these ways:\n\
2796 FILE:LINENUM, to edit at that line in that file,\n\
2797 FUNCTION, to edit at the beginning of that function,\n\
2798 FILE:FUNCTION, to distinguish among like-named static functions.\n\
2799 *ADDRESS, to edit at the line containing that address.\n\
1bedd215 2800Uses EDITOR environment variable contents as editor (or ex as default)."));
0378c332
FN
2801
2802 c->completer = location_completer;
2803
3947f654
SM
2804 cmd_list_element *pipe_cmd
2805 = add_com ("pipe", class_support, pipe_command, _("\
947d3946
PW
2806Send the output of a gdb command to a shell command.\n\
2807Usage: | [COMMAND] | SHELL_COMMAND\n\
2808Usage: | -d DELIM COMMAND DELIM SHELL_COMMAND\n\
2809Usage: pipe [COMMAND] | SHELL_COMMAND\n\
2810Usage: pipe -d DELIM COMMAND DELIM SHELL_COMMAND\n\
2811\n\
2812Executes COMMAND and sends its output to SHELL_COMMAND.\n\
2813\n\
2814The -d option indicates to use the string DELIM to separate COMMAND\n\
2815from SHELL_COMMAND, in alternative to |. This is useful in\n\
2816case COMMAND contains a | character.\n\
2817\n\
2818With no COMMAND, repeat the last executed command\n\
2819and send its output to SHELL_COMMAND."));
3947f654
SM
2820 set_cmd_completer_handle_brkchars (pipe_cmd, pipe_command_completer);
2821 add_com_alias ("|", pipe_cmd, class_support, 0);
947d3946 2822
3947f654
SM
2823 cmd_list_element *list_cmd
2824 = add_com ("list", class_files, list_command, _("\
1bedd215 2825List specified function or line.\n\
0378c332 2826With no argument, lists ten more lines after or around previous listing.\n\
a4e5901b 2827\"list +\" lists the ten lines following a previous ten-line listing.\n\
0378c332 2828\"list -\" lists the ten lines before a previous ten-line listing.\n\
12f567bc 2829\"list .\" lists ten lines around the point of execution in the current frame.\n\
0378c332
FN
2830One argument specifies a line, and ten lines are listed around that line.\n\
2831Two arguments with comma between specify starting and ending lines to list.\n\
0378c332
FN
2832Lines can be specified in these ways:\n\
2833 LINENUM, to list around that line in current file,\n\
2834 FILE:LINENUM, to list around that line in that file,\n\
2835 FUNCTION, to list around beginning of that function,\n\
2836 FILE:FUNCTION, to distinguish among like-named static functions.\n\
2837 *ADDRESS, to list around the line containing that address.\n\
4fdd372d
AB
2838With two args, if one is empty, it stands for ten lines away from\n\
2839the other arg.\n\
2840\n\
2841By default, when a single location is given, display ten lines.\n\
2842This can be changed using \"set listsize\", and the current value\n\
2843can be shown using \"show listsize\"."));
0378c332 2844
3947f654 2845 add_com_alias ("l", list_cmd, class_files, 1);
0378c332 2846
1bedd215
AC
2847 c = add_com ("disassemble", class_vars, disassemble_command, _("\
2848Disassemble a specified section of memory.\n\
16f3242c 2849Usage: disassemble[/m|/r|/s] START [, END]\n\
83c31e7d 2850Default is the function surrounding the pc of the selected frame.\n\
6ff0ba5f 2851\n\
16f3242c
TT
2852With a /s modifier, source lines are included (if available).\n\
2853In this mode, the output is displayed in PC address order, and\n\
2854file names and contents for all relevant source files are displayed.\n\
2855\n\
d14508fe 2856With a /m modifier, source lines are included (if available).\n\
6ff0ba5f
DE
2857This view is \"source centric\": the output is in source line order,\n\
2858regardless of any optimization that is present. Only the main source file\n\
2859is displayed, not those of, e.g., any inlined functions.\n\
2860This modifier hasn't proved useful in practice and is deprecated\n\
2861in favor of /s.\n\
2862\n\
e6158f16 2863With a /r modifier, raw instructions in hex are included.\n\
6ff0ba5f 2864\n\
83c31e7d 2865With a single argument, the function surrounding that address is dumped.\n\
53a71c06 2866Two arguments (separated by a comma) are taken as a range of memory to dump,\n\
7e1e0340
DE
2867 in the form of \"start,end\", or \"start,+length\".\n\
2868\n\
2869Note that the address is interpreted as an expression, not as a location\n\
2870like in the \"break\" command.\n\
2871So, for example, if you want to disassemble function bar in file foo.c\n\
2872you must type \"disassemble 'foo.c'::bar\" and not \"disassemble foo.c:bar\"."));
b20885b0 2873 set_cmd_completer_handle_brkchars (c, disassemble_command_completer);
0378c332 2874
1bedd215
AC
2875 c = add_com ("make", class_support, make_command, _("\
2876Run the ``make'' program using the rest of the line as arguments."));
5ba2abeb 2877 set_cmd_completer (c, filename_completer);
cc81bc2d 2878 c = add_cmd ("user", no_class, show_user, _("\
ed3ef339 2879Show definitions of non-python/scheme user defined commands.\n\
d318976c 2880Argument is the name of the user defined command.\n\
1a966eab 2881With no argument, show definitions of all user defined commands."), &showlist);
cc81bc2d 2882 set_cmd_completer (c, show_user_completer);
66d8c862 2883 add_com ("apropos", class_support, apropos_command, _("\
590042fc 2884Search for commands matching a REGEXP.\n\
66d8c862
PW
2885Usage: apropos [-v] REGEXP\n\
2886Flag -v indicates to produce a verbose output, showing full documentation\n\
2887of the matching commands."));
20f01a46 2888
883b9c6c 2889 add_setshow_uinteger_cmd ("max-user-call-depth", no_class,
c0d88b1b 2890 &max_user_call_depth, _("\
ed3ef339
DE
2891Set the max call depth for non-python/scheme user-defined commands."), _("\
2892Show the max call depth for non-python/scheme user-defined commands."), NULL,
883b9c6c
YQ
2893 NULL,
2894 show_max_user_call_depth,
2895 &setlist, &showlist);
16026cd7
AS
2896
2897 add_setshow_boolean_cmd ("trace-commands", no_class, &trace_commands, _("\
2898Set tracing of GDB CLI commands."), _("\
2899Show state of GDB CLI command tracing."), _("\
2900When 'on', each command is displayed as it is executed."),
2901 NULL,
2902 NULL,
2903 &setlist, &showlist);
5a56e9c5 2904
cf00cd6f
PW
2905 const auto alias_opts = make_alias_options_def_group (nullptr);
2906
2907 static std::string alias_help
2908 = gdb::option::build_help (_("\
5a56e9c5 2909Define a new command that is an alias of an existing command.\n\
cf00cd6f 2910Usage: alias [-a] [--] ALIAS = COMMAND [DEFAULT-ARGS...]\n\
5a56e9c5
DE
2911ALIAS is the name of the alias command to create.\n\
2912COMMAND is the command being aliased to.\n\
cf00cd6f
PW
2913\n\
2914Options:\n\
2915%OPTIONS%\n\
2916\n\
2917GDB will automatically prepend the provided DEFAULT-ARGS to the list\n\
2918of arguments explicitly provided when using ALIAS.\n\
2919Use \"help aliases\" to list all user defined aliases and their default args.\n\
5a56e9c5
DE
2920\n\
2921Examples:\n\
2922Make \"spe\" an alias of \"set print elements\":\n\
e0c45ded 2923 alias spe = set print elements\n\
5a56e9c5 2924Make \"elms\" an alias of \"elements\" in the \"set print\" command:\n\
e0c45ded 2925 alias -a set print elms = set print elements\n\
cf00cd6f
PW
2926Make \"btf\" an alias of \"backtrace -full -past-entry -past-main\" :\n\
2927 alias btf = backtrace -full -past-entry -past-main\n\
2928Make \"wLapPeu\" an alias of 2 nested \"with\":\n\
2929 alias wLapPeu = with language pascal -- with print elements unlimited --"),
2930 alias_opts);
2931
2932 c = add_com ("alias", class_support, alias_command,
2933 alias_help.c_str ());
2934
2935 set_cmd_completer_handle_brkchars (c, alias_command_completer);
43e4916f 2936
61fb7376
TBA
2937 add_setshow_boolean_cmd ("suppress-cli-notifications", no_class,
2938 &user_wants_cli_suppress_notification,
2939 _("\
2940Set whether printing notifications on CLI is suppressed."), _("\
2941Show whether printing notifications on CLI is suppressed."), _("\
2942When on, printing notifications (such as inferior/thread switch)\n\
2943on CLI is suppressed."),
2944 set_suppress_cli_notifications,
2945 show_suppress_cli_notifications,
2946 &setlist,
2947 &showlist);
2948
b777eb6d 2949 const char *source_help_text = xstrprintf (_("\
43e4916f
TT
2950Read commands from a file named FILE.\n\
2951\n\
2952Usage: source [-s] [-v] FILE\n\
2953-s: search for the script in the source search path,\n\
2954 even if FILE contains directories.\n\
2955-v: each command in FILE is echoed as it is executed.\n\
2956\n\
2957Note that the file \"%s\" is read automatically in this way\n\
8579fd13 2958when GDB is started."), GDBINIT).release ();
43e4916f
TT
2959 c = add_cmd ("source", class_support, source_command,
2960 source_help_text, &cmdlist);
2961 set_cmd_completer (c, filename_completer);
2962}