PR gdb/20604 - fix "quit" when an invalid expression is used
[external/binutils.git] / gdb / cli / cli-cmds.c
1 /* GDB CLI commands.
2
3    Copyright (C) 2000-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "dyn-string.h"
23 #include "readline/readline.h"
24 #include "readline/tilde.h"
25 #include "completer.h"
26 #include "target.h"     /* For baud_rate, remote_debug and remote_timeout.  */
27 #include "gdb_wait.h"   /* For shell escape implementation.  */
28 #include "gdb_regex.h"  /* Used by apropos_command.  */
29 #include "gdb_vfork.h"
30 #include "linespec.h"
31 #include "expression.h"
32 #include "frame.h"
33 #include "value.h"
34 #include "language.h"
35 #include "filenames.h"  /* For DOSish file names.  */
36 #include "objfiles.h"
37 #include "source.h"
38 #include "disasm.h"
39 #include "tracepoint.h"
40 #include "filestuff.h"
41 #include "location.h"
42
43 #include "ui-out.h"
44
45 #include "top.h"
46 #include "cli/cli-decode.h"
47 #include "cli/cli-script.h"
48 #include "cli/cli-setshow.h"
49 #include "cli/cli-cmds.h"
50 #include "cli/cli-utils.h"
51
52 #include "extension.h"
53
54 #ifdef TUI
55 #include "tui/tui.h"    /* For tui_active et.al.  */
56 #endif
57
58 #include <fcntl.h>
59 #include <algorithm>
60
61 /* Prototypes for local command functions */
62
63 static void complete_command (char *, int);
64
65 static void echo_command (char *, int);
66
67 static void pwd_command (char *, int);
68
69 static void show_version (char *, int);
70
71 static void help_command (char *, int);
72
73 static void show_command (char *, int);
74
75 static void info_command (char *, int);
76
77 static void show_debug (char *, int);
78
79 static void set_debug (char *, int);
80
81 static void show_user (char *, int);
82
83 static void make_command (char *, int);
84
85 static void shell_escape (char *, int);
86
87 static void edit_command (char *, int);
88
89 static void list_command (char *, int);
90
91 /* Prototypes for local utility functions */
92
93 static void ambiguous_line_spec (struct symtabs_and_lines *);
94
95 static void filter_sals (struct symtabs_and_lines *);
96
97 \f
98 /* Limit the call depth of user-defined commands */
99 unsigned int max_user_call_depth;
100
101 /* Define all cmd_list_elements.  */
102
103 /* Chain containing all defined commands.  */
104
105 struct cmd_list_element *cmdlist;
106
107 /* Chain containing all defined info subcommands.  */
108
109 struct cmd_list_element *infolist;
110
111 /* Chain containing all defined enable subcommands.  */
112
113 struct cmd_list_element *enablelist;
114
115 /* Chain containing all defined disable subcommands.  */
116
117 struct cmd_list_element *disablelist;
118
119 /* Chain containing all defined stop subcommands.  */
120
121 struct cmd_list_element *stoplist;
122
123 /* Chain containing all defined delete subcommands.  */
124
125 struct cmd_list_element *deletelist;
126
127 /* Chain containing all defined detach subcommands.  */
128
129 struct cmd_list_element *detachlist;
130
131 /* Chain containing all defined kill subcommands.  */
132
133 struct cmd_list_element *killlist;
134
135 /* Chain containing all defined set subcommands */
136
137 struct cmd_list_element *setlist;
138
139 /* Chain containing all defined unset subcommands */
140
141 struct cmd_list_element *unsetlist;
142
143 /* Chain containing all defined show subcommands.  */
144
145 struct cmd_list_element *showlist;
146
147 /* Chain containing all defined \"set history\".  */
148
149 struct cmd_list_element *sethistlist;
150
151 /* Chain containing all defined \"show history\".  */
152
153 struct cmd_list_element *showhistlist;
154
155 /* Chain containing all defined \"unset history\".  */
156
157 struct cmd_list_element *unsethistlist;
158
159 /* Chain containing all defined maintenance subcommands.  */
160
161 struct cmd_list_element *maintenancelist;
162
163 /* Chain containing all defined "maintenance info" subcommands.  */
164
165 struct cmd_list_element *maintenanceinfolist;
166
167 /* Chain containing all defined "maintenance print" subcommands.  */
168
169 struct cmd_list_element *maintenanceprintlist;
170
171 struct cmd_list_element *setprintlist;
172
173 struct cmd_list_element *showprintlist;
174
175 struct cmd_list_element *setdebuglist;
176
177 struct cmd_list_element *showdebuglist;
178
179 struct cmd_list_element *setchecklist;
180
181 struct cmd_list_element *showchecklist;
182
183 /* Command tracing state.  */
184
185 int source_verbose = 0;
186 int trace_commands = 0;
187 \f
188 /* 'script-extension' option support.  */
189
190 static const char script_ext_off[] = "off";
191 static const char script_ext_soft[] = "soft";
192 static const char script_ext_strict[] = "strict";
193
194 static const char *const script_ext_enums[] = {
195   script_ext_off,
196   script_ext_soft,
197   script_ext_strict,
198   NULL
199 };
200
201 static const char *script_ext_mode = script_ext_soft;
202 \f
203 /* Utility used everywhere when at least one argument is needed and
204    none is supplied.  */
205
206 void
207 error_no_arg (const char *why)
208 {
209   error (_("Argument required (%s)."), why);
210 }
211
212 /* The "info" command is defined as a prefix, with allow_unknown = 0.
213    Therefore, its own definition is called only for "info" with no
214    args.  */
215
216 static void
217 info_command (char *arg, int from_tty)
218 {
219   printf_unfiltered (_("\"info\" must be followed by "
220                        "the name of an info command.\n"));
221   help_list (infolist, "info ", all_commands, gdb_stdout);
222 }
223
224 /* The "show" command with no arguments shows all the settings.  */
225
226 static void
227 show_command (char *arg, int from_tty)
228 {
229   cmd_show_list (showlist, from_tty, "");
230 }
231 \f
232 /* Provide documentation on command or list given by COMMAND.  FROM_TTY
233    is ignored.  */
234
235 static void
236 help_command (char *command, int from_tty)
237 {
238   help_cmd (command, gdb_stdout);
239 }
240 \f
241 /* Note: The "complete" command is used by Emacs to implement completion.
242    [Is that why this function writes output with *_unfiltered?]  */
243
244 static void
245 complete_command (char *arg, int from_tty)
246 {
247   int argpoint;
248   char *point, *arg_prefix;
249   VEC (char_ptr) *completions;
250
251   dont_repeat ();
252
253   if (max_completions == 0)
254     {
255       /* Only print this for non-mi frontends.  An MI frontend may not
256          be able to handle this.  */
257       if (!ui_out_is_mi_like_p (current_uiout))
258         {
259           printf_unfiltered (_("max-completions is zero,"
260                                " completion is disabled.\n"));
261         }
262       return;
263     }
264
265   if (arg == NULL)
266     arg = "";
267   argpoint = strlen (arg);
268
269   /* complete_line assumes that its first argument is somewhere
270      within, and except for filenames at the beginning of, the word to
271      be completed.  The following crude imitation of readline's
272      word-breaking tries to accomodate this.  */
273   point = arg + argpoint;
274   while (point > arg)
275     {
276       if (strchr (rl_completer_word_break_characters, point[-1]) != 0)
277         break;
278       point--;
279     }
280
281   arg_prefix = (char *) alloca (point - arg + 1);
282   memcpy (arg_prefix, arg, point - arg);
283   arg_prefix[point - arg] = 0;
284
285   completions = complete_line (point, arg, argpoint);
286
287   if (completions)
288     {
289       int ix, size = VEC_length (char_ptr, completions);
290       char *item, *prev = NULL;
291
292       qsort (VEC_address (char_ptr, completions), size,
293              sizeof (char *), compare_strings);
294
295       /* We do extra processing here since we only want to print each
296          unique item once.  */
297       for (ix = 0; VEC_iterate (char_ptr, completions, ix, item); ++ix)
298         {
299           if (prev == NULL || strcmp (item, prev) != 0)
300             {
301               printf_unfiltered ("%s%s\n", arg_prefix, item);
302               xfree (prev);
303               prev = item;
304             }
305           else
306             xfree (item);
307         }
308
309       xfree (prev);
310       VEC_free (char_ptr, completions);
311
312       if (size == max_completions)
313         {
314           /* ARG_PREFIX and POINT are included in the output so that emacs
315              will include the message in the output.  */
316           printf_unfiltered (_("%s%s %s\n"),
317                              arg_prefix, point,
318                              get_max_completions_reached_message ());
319         }
320     }
321 }
322
323 int
324 is_complete_command (struct cmd_list_element *c)
325 {
326   return cmd_cfunc_eq (c, complete_command);
327 }
328
329 static void
330 show_version (char *args, int from_tty)
331 {
332   print_gdb_version (gdb_stdout);
333   printf_filtered ("\n");
334 }
335
336 static void
337 show_configuration (char *args, int from_tty)
338 {
339   print_gdb_configuration (gdb_stdout);
340 }
341
342 /* Handle the quit command.  */
343
344 void
345 quit_command (char *args, int from_tty)
346 {
347   int exit_code = 0;
348
349   /* An optional expression may be used to cause gdb to terminate with
350      the value of that expression.  */
351   if (args)
352     {
353       struct value *val = parse_and_eval (args);
354
355       exit_code = (int) value_as_long (val);
356     }
357
358   if (!quit_confirm ())
359     error (_("Not confirmed."));
360
361   query_if_trace_running (from_tty);
362
363   quit_force (args ? &exit_code : NULL, from_tty);
364 }
365
366 static void
367 pwd_command (char *args, int from_tty)
368 {
369   if (args)
370     error (_("The \"pwd\" command does not take an argument: %s"), args);
371   if (! getcwd (gdb_dirbuf, sizeof (gdb_dirbuf)))
372     error (_("Error finding name of working directory: %s"),
373            safe_strerror (errno));
374
375   if (strcmp (gdb_dirbuf, current_directory) != 0)
376     printf_unfiltered (_("Working directory %s\n (canonically %s).\n"),
377                        current_directory, gdb_dirbuf);
378   else
379     printf_unfiltered (_("Working directory %s.\n"), current_directory);
380 }
381
382 void
383 cd_command (char *dir, int from_tty)
384 {
385   int len;
386   /* Found something other than leading repetitions of "/..".  */
387   int found_real_path;
388   char *p;
389   struct cleanup *cleanup;
390
391   /* If the new directory is absolute, repeat is a no-op; if relative,
392      repeat might be useful but is more likely to be a mistake.  */
393   dont_repeat ();
394
395   if (dir == 0)
396     dir = "~";
397
398   dir = tilde_expand (dir);
399   cleanup = make_cleanup (xfree, dir);
400
401   if (chdir (dir) < 0)
402     perror_with_name (dir);
403
404 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
405   /* There's too much mess with DOSish names like "d:", "d:.",
406      "d:./foo" etc.  Instead of having lots of special #ifdef'ed code,
407      simply get the canonicalized name of the current directory.  */
408   dir = getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
409 #endif
410
411   len = strlen (dir);
412   if (IS_DIR_SEPARATOR (dir[len - 1]))
413     {
414       /* Remove the trailing slash unless this is a root directory
415          (including a drive letter on non-Unix systems).  */
416       if (!(len == 1)           /* "/" */
417 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
418           && !(len == 3 && dir[1] == ':') /* "d:/" */
419 #endif
420           )
421         len--;
422     }
423
424   dir = savestring (dir, len);
425   if (IS_ABSOLUTE_PATH (dir))
426     current_directory = dir;
427   else
428     {
429       if (IS_DIR_SEPARATOR (current_directory[strlen (current_directory) - 1]))
430         current_directory = concat (current_directory, dir, (char *)NULL);
431       else
432         current_directory = concat (current_directory, SLASH_STRING,
433                                     dir, (char *)NULL);
434       xfree (dir);
435     }
436
437   /* Now simplify any occurrences of `.' and `..' in the pathname.  */
438
439   found_real_path = 0;
440   for (p = current_directory; *p;)
441     {
442       if (IS_DIR_SEPARATOR (p[0]) && p[1] == '.'
443           && (p[2] == 0 || IS_DIR_SEPARATOR (p[2])))
444         memmove (p, p + 2, strlen (p + 2) + 1);
445       else if (IS_DIR_SEPARATOR (p[0]) && p[1] == '.' && p[2] == '.'
446                && (p[3] == 0 || IS_DIR_SEPARATOR (p[3])))
447         {
448           if (found_real_path)
449             {
450               /* Search backwards for the directory just before the "/.."
451                  and obliterate it and the "/..".  */
452               char *q = p;
453
454               while (q != current_directory && !IS_DIR_SEPARATOR (q[-1]))
455                 --q;
456
457               if (q == current_directory)
458                 /* current_directory is
459                    a relative pathname ("can't happen"--leave it alone).  */
460                 ++p;
461               else
462                 {
463                   memmove (q - 1, p + 3, strlen (p + 3) + 1);
464                   p = q - 1;
465                 }
466             }
467           else
468             /* We are dealing with leading repetitions of "/..", for
469                example "/../..", which is the Mach super-root.  */
470             p += 3;
471         }
472       else
473         {
474           found_real_path = 1;
475           ++p;
476         }
477     }
478
479   forget_cached_source_info ();
480
481   if (from_tty)
482     pwd_command ((char *) 0, 1);
483
484   do_cleanups (cleanup);
485 }
486 \f
487 /* Show the current value of the 'script-extension' option.  */
488
489 static void
490 show_script_ext_mode (struct ui_file *file, int from_tty,
491                      struct cmd_list_element *c, const char *value)
492 {
493   fprintf_filtered (file,
494                     _("Script filename extension recognition is \"%s\".\n"),
495                     value);
496 }
497
498 /* Try to open SCRIPT_FILE.
499    If successful, the full path name is stored in *FULL_PATHP,
500    the stream is stored in *STREAMP, and return 1.
501    The caller is responsible for freeing *FULL_PATHP.
502    If not successful, return 0; errno is set for the last file
503    we tried to open.
504
505    If SEARCH_PATH is non-zero, and the file isn't found in cwd,
506    search for it in the source search path.  */
507
508 int
509 find_and_open_script (const char *script_file, int search_path,
510                       FILE **streamp, char **full_pathp)
511 {
512   char *file;
513   int fd;
514   struct cleanup *old_cleanups;
515   int search_flags = OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH;
516
517   file = tilde_expand (script_file);
518   old_cleanups = make_cleanup (xfree, file);
519
520   if (search_path)
521     search_flags |= OPF_SEARCH_IN_PATH;
522
523   /* Search for and open 'file' on the search path used for source
524      files.  Put the full location in *FULL_PATHP.  */
525   fd = openp (source_path, search_flags,
526               file, O_RDONLY, full_pathp);
527
528   if (fd == -1)
529     {
530       int save_errno = errno;
531       do_cleanups (old_cleanups);
532       errno = save_errno;
533       return 0;
534     }
535
536   do_cleanups (old_cleanups);
537
538   *streamp = fdopen (fd, FOPEN_RT);
539   if (*streamp == NULL)
540     {
541       int save_errno = errno;
542
543       close (fd);
544       if (full_pathp)
545         xfree (*full_pathp);
546       errno = save_errno;
547       return 0;
548     }
549
550   return 1;
551 }
552
553 /* Load script FILE, which has already been opened as STREAM.
554    FILE_TO_OPEN is the form of FILE to use if one needs to open the file.
555    This is provided as FILE may have been found via the source search path.
556    An important thing to note here is that FILE may be a symlink to a file
557    with a different or non-existing suffix, and thus one cannot infer the
558    extension language from FILE_TO_OPEN.  */
559
560 static void
561 source_script_from_stream (FILE *stream, const char *file,
562                            const char *file_to_open)
563 {
564   if (script_ext_mode != script_ext_off)
565     {
566       const struct extension_language_defn *extlang
567         = get_ext_lang_of_file (file);
568
569       if (extlang != NULL)
570         {
571           if (ext_lang_present_p (extlang))
572             {
573               script_sourcer_func *sourcer
574                 = ext_lang_script_sourcer (extlang);
575
576               gdb_assert (sourcer != NULL);
577               sourcer (extlang, stream, file_to_open);
578               return;
579             }
580           else if (script_ext_mode == script_ext_soft)
581             {
582               /* Assume the file is a gdb script.
583                  This is handled below.  */
584             }
585           else
586             throw_ext_lang_unsupported (extlang);
587         }
588     }
589
590   script_from_file (stream, file);
591 }
592
593 /* Worker to perform the "source" command.
594    Load script FILE.
595    If SEARCH_PATH is non-zero, and the file isn't found in cwd,
596    search for it in the source search path.  */
597
598 static void
599 source_script_with_search (const char *file, int from_tty, int search_path)
600 {
601   FILE *stream;
602   char *full_path;
603   struct cleanup *old_cleanups;
604
605   if (file == NULL || *file == 0)
606     error (_("source command requires file name of file to source."));
607
608   if (!find_and_open_script (file, search_path, &stream, &full_path))
609     {
610       /* The script wasn't found, or was otherwise inaccessible.
611          If the source command was invoked interactively, throw an
612          error.  Otherwise (e.g. if it was invoked by a script),
613          just emit a warning, rather than cause an error.  */
614       if (from_tty)
615         perror_with_name (file);
616       else
617         {
618           perror_warning_with_name (file);
619           return;
620         }
621     }
622
623   old_cleanups = make_cleanup (xfree, full_path);
624   make_cleanup_fclose (stream);
625   /* The python support reopens the file, so we need to pass full_path here
626      in case the file was found on the search path.  It's useful to do this
627      anyway so that error messages show the actual file used.  But only do
628      this if we (may have) used search_path, as printing the full path in
629      errors for the non-search case can be more noise than signal.  */
630   source_script_from_stream (stream, file, search_path ? full_path : file);
631   do_cleanups (old_cleanups);
632 }
633
634 /* Wrapper around source_script_with_search to export it to main.c
635    for use in loading .gdbinit scripts.  */
636
637 void
638 source_script (const char *file, int from_tty)
639 {
640   source_script_with_search (file, from_tty, 0);
641 }
642
643 /* Return the source_verbose global variable to its previous state
644    on exit from the source command, by whatever means.  */
645 static void
646 source_verbose_cleanup (void *old_value)
647 {
648   source_verbose = *(int *)old_value;
649   xfree (old_value);
650 }
651
652 static void
653 source_command (char *args, int from_tty)
654 {
655   struct cleanup *old_cleanups;
656   char *file = args;
657   int *old_source_verbose = XNEW (int);
658   int search_path = 0;
659
660   *old_source_verbose = source_verbose;
661   old_cleanups = make_cleanup (source_verbose_cleanup, 
662                                old_source_verbose);
663
664   /* -v causes the source command to run in verbose mode.
665      -s causes the file to be searched in the source search path,
666      even if the file name contains a '/'.
667      We still have to be able to handle filenames with spaces in a
668      backward compatible way, so buildargv is not appropriate.  */
669
670   if (args)
671     {
672       while (args[0] != '\0')
673         {
674           /* Make sure leading white space does not break the
675              comparisons.  */
676           args = skip_spaces (args);
677
678           if (args[0] != '-')
679             break;
680
681           if (args[1] == 'v' && isspace (args[2]))
682             {
683               source_verbose = 1;
684
685               /* Skip passed -v.  */
686               args = &args[3];
687             }
688           else if (args[1] == 's' && isspace (args[2]))
689             {
690               search_path = 1;
691
692               /* Skip passed -s.  */
693               args = &args[3];
694             }
695           else
696             break;
697         }
698
699       file = skip_spaces (args);
700     }
701
702   source_script_with_search (file, from_tty, search_path);
703
704   do_cleanups (old_cleanups);
705 }
706
707
708 static void
709 echo_command (char *text, int from_tty)
710 {
711   const char *p = text;
712   int c;
713
714   if (text)
715     while ((c = *p++) != '\0')
716       {
717         if (c == '\\')
718           {
719             /* \ at end of argument is used after spaces
720                so they won't be lost.  */
721             if (*p == 0)
722               return;
723
724             c = parse_escape (get_current_arch (), &p);
725             if (c >= 0)
726               printf_filtered ("%c", c);
727           }
728         else
729           printf_filtered ("%c", c);
730       }
731
732   /* Force this output to appear now.  */
733   wrap_here ("");
734   gdb_flush (gdb_stdout);
735 }
736
737 static void
738 shell_escape (char *arg, int from_tty)
739 {
740 #if defined(CANT_FORK) || \
741       (!defined(HAVE_WORKING_VFORK) && !defined(HAVE_WORKING_FORK))
742   /* If ARG is NULL, they want an inferior shell, but `system' just
743      reports if the shell is available when passed a NULL arg.  */
744   int rc = system (arg ? arg : "");
745
746   if (!arg)
747     arg = "inferior shell";
748
749   if (rc == -1)
750     {
751       fprintf_unfiltered (gdb_stderr, "Cannot execute %s: %s\n", arg,
752                           safe_strerror (errno));
753       gdb_flush (gdb_stderr);
754     }
755   else if (rc)
756     {
757       fprintf_unfiltered (gdb_stderr, "%s exited with status %d\n", arg, rc);
758       gdb_flush (gdb_stderr);
759     }
760 #ifdef GLOBAL_CURDIR
761   /* Make sure to return to the directory GDB thinks it is, in case
762      the shell command we just ran changed it.  */
763   chdir (current_directory);
764 #endif
765 #else /* Can fork.  */
766   int status, pid;
767
768   if ((pid = vfork ()) == 0)
769     {
770       const char *p, *user_shell;
771
772       close_most_fds ();
773
774       if ((user_shell = (char *) getenv ("SHELL")) == NULL)
775         user_shell = "/bin/sh";
776
777       /* Get the name of the shell for arg0.  */
778       p = lbasename (user_shell);
779
780       if (!arg)
781         execl (user_shell, p, (char *) 0);
782       else
783         execl (user_shell, p, "-c", arg, (char *) 0);
784
785       fprintf_unfiltered (gdb_stderr, "Cannot execute %s: %s\n", user_shell,
786                           safe_strerror (errno));
787       gdb_flush (gdb_stderr);
788       _exit (0177);
789     }
790
791   if (pid != -1)
792     waitpid (pid, &status, 0);
793   else
794     error (_("Fork failed"));
795 #endif /* Can fork.  */
796 }
797
798 static void
799 edit_command (char *arg, int from_tty)
800 {
801   struct symtabs_and_lines sals;
802   struct symtab_and_line sal;
803   struct symbol *sym;
804   char *editor;
805   char *p;
806   const char *fn;
807
808   /* Pull in the current default source line if necessary.  */
809   if (arg == 0)
810     {
811       set_default_source_symtab_and_line ();
812       sal = get_current_source_symtab_and_line ();
813     }
814
815   /* Bare "edit" edits file with present line.  */
816
817   if (arg == 0)
818     {
819       if (sal.symtab == 0)
820         error (_("No default source file yet."));
821       sal.line += get_lines_to_list () / 2;
822     }
823   else
824     {
825       struct cleanup *cleanup;
826       struct event_location *location;
827       char *arg1;
828
829       /* Now should only be one argument -- decode it in SAL.  */
830       arg1 = arg;
831       location = string_to_event_location (&arg1, current_language);
832       cleanup = make_cleanup_delete_event_location (location);
833       sals = decode_line_1 (location, DECODE_LINE_LIST_MODE, NULL, NULL, 0);
834
835       filter_sals (&sals);
836       if (! sals.nelts)
837         {
838           /*  C++  */
839           do_cleanups (cleanup);
840           return;
841         }
842       if (sals.nelts > 1)
843         {
844           ambiguous_line_spec (&sals);
845           xfree (sals.sals);
846           do_cleanups (cleanup);
847           return;
848         }
849
850       sal = sals.sals[0];
851       xfree (sals.sals);
852
853       if (*arg1)
854         error (_("Junk at end of line specification."));
855
856       /* If line was specified by address, first print exactly which
857          line, and which file.  In this case, sal.symtab == 0 means
858          address is outside of all known source files, not that user
859          failed to give a filename.  */
860       if (*arg == '*')
861         {
862           struct gdbarch *gdbarch;
863
864           if (sal.symtab == 0)
865             error (_("No source file for address %s."),
866                    paddress (get_current_arch (), sal.pc));
867
868           gdbarch = get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
869           sym = find_pc_function (sal.pc);
870           if (sym)
871             printf_filtered ("%s is in %s (%s:%d).\n",
872                              paddress (gdbarch, sal.pc),
873                              SYMBOL_PRINT_NAME (sym),
874                              symtab_to_filename_for_display (sal.symtab),
875                              sal.line);
876           else
877             printf_filtered ("%s is at %s:%d.\n",
878                              paddress (gdbarch, sal.pc),
879                              symtab_to_filename_for_display (sal.symtab),
880                              sal.line);
881         }
882
883       /* If what was given does not imply a symtab, it must be an
884          undebuggable symbol which means no source code.  */
885
886       if (sal.symtab == 0)
887         error (_("No line number known for %s."), arg);
888       do_cleanups (cleanup);
889     }
890
891   if ((editor = (char *) getenv ("EDITOR")) == NULL)
892       editor = "/bin/ex";
893
894   fn = symtab_to_fullname (sal.symtab);
895
896   /* Quote the file name, in case it has whitespace or other special
897      characters.  */
898   p = xstrprintf ("%s +%d \"%s\"", editor, sal.line, fn);
899   shell_escape (p, from_tty);
900   xfree (p);
901 }
902
903 static void
904 list_command (char *arg, int from_tty)
905 {
906   struct symtabs_and_lines sals, sals_end;
907   struct symtab_and_line sal = { 0 };
908   struct symtab_and_line sal_end = { 0 };
909   struct symtab_and_line cursal = { 0 };
910   struct symbol *sym;
911   char *arg1;
912   int no_end = 1;
913   int dummy_end = 0;
914   int dummy_beg = 0;
915   int linenum_beg = 0;
916   char *p;
917   struct cleanup *cleanup;
918
919   cleanup = make_cleanup (null_cleanup, NULL);
920
921   /* Pull in the current default source line if necessary.  */
922   if (arg == NULL || ((arg[0] == '+' || arg[0] == '-') && arg[1] == '\0'))
923     {
924       set_default_source_symtab_and_line ();
925       cursal = get_current_source_symtab_and_line ();
926
927       /* If this is the first "list" since we've set the current
928          source line, center the listing around that line.  */
929       if (get_first_line_listed () == 0)
930         {
931           int first;
932
933           first = std::max (cursal.line - get_lines_to_list () / 2, 1);
934
935           /* A small special case --- if listing backwards, and we
936              should list only one line, list the preceding line,
937              instead of the exact line we've just shown after e.g.,
938              stopping for a breakpoint.  */
939           if (arg != NULL && arg[0] == '-'
940               && get_lines_to_list () == 1 && first > 1)
941             first -= 1;
942
943           print_source_lines (cursal.symtab, first,
944                               first + get_lines_to_list (), 0);
945         }
946
947       /* "l" or "l +" lists next ten lines.  */
948       else if (arg == NULL || arg[0] == '+')
949         print_source_lines (cursal.symtab, cursal.line,
950                             cursal.line + get_lines_to_list (), 0);
951
952       /* "l -" lists previous ten lines, the ones before the ten just
953          listed.  */
954       else if (arg[0] == '-')
955         {
956           if (get_first_line_listed () == 1)
957             error (_("Already at the start of %s."),
958                    symtab_to_filename_for_display (cursal.symtab));
959           print_source_lines (cursal.symtab,
960                               std::max (get_first_line_listed ()
961                                         - get_lines_to_list (), 1),
962                               get_first_line_listed (), 0);
963         }
964
965       return;
966     }
967
968   /* Now if there is only one argument, decode it in SAL
969      and set NO_END.
970      If there are two arguments, decode them in SAL and SAL_END
971      and clear NO_END; however, if one of the arguments is blank,
972      set DUMMY_BEG or DUMMY_END to record that fact.  */
973
974   if (!have_full_symbols () && !have_partial_symbols ())
975     error (_("No symbol table is loaded.  Use the \"file\" command."));
976
977   arg1 = arg;
978   if (*arg1 == ',')
979     dummy_beg = 1;
980   else
981     {
982       struct event_location *location;
983
984       location = string_to_event_location (&arg1, current_language);
985       make_cleanup_delete_event_location (location);
986       sals = decode_line_1 (location, DECODE_LINE_LIST_MODE, NULL, NULL, 0);
987
988       filter_sals (&sals);
989       if (!sals.nelts)
990         {
991           /*  C++  */
992           do_cleanups (cleanup);
993           return;
994         }
995       if (sals.nelts > 1)
996         {
997           ambiguous_line_spec (&sals);
998           xfree (sals.sals);
999           do_cleanups (cleanup);
1000           return;
1001         }
1002
1003       sal = sals.sals[0];
1004       xfree (sals.sals);
1005     }
1006
1007   /* Record whether the BEG arg is all digits.  */
1008
1009   for (p = arg; p != arg1 && *p >= '0' && *p <= '9'; p++);
1010   linenum_beg = (p == arg1);
1011
1012   while (*arg1 == ' ' || *arg1 == '\t')
1013     arg1++;
1014   if (*arg1 == ',')
1015     {
1016       no_end = 0;
1017       arg1++;
1018       while (*arg1 == ' ' || *arg1 == '\t')
1019         arg1++;
1020       if (*arg1 == 0)
1021         dummy_end = 1;
1022       else
1023         {
1024           struct event_location *location;
1025
1026           location = string_to_event_location (&arg1, current_language);
1027           make_cleanup_delete_event_location (location);
1028           if (dummy_beg)
1029             sals_end = decode_line_1 (location,
1030                                       DECODE_LINE_LIST_MODE, NULL, NULL, 0);
1031           else
1032             sals_end = decode_line_1 (location, DECODE_LINE_LIST_MODE,
1033                                       NULL, sal.symtab, sal.line);
1034
1035           filter_sals (&sals_end);
1036           if (sals_end.nelts == 0)
1037             {
1038               do_cleanups (cleanup);
1039               return;
1040             }
1041           if (sals_end.nelts > 1)
1042             {
1043               ambiguous_line_spec (&sals_end);
1044               xfree (sals_end.sals);
1045               do_cleanups (cleanup);
1046               return;
1047             }
1048           sal_end = sals_end.sals[0];
1049           xfree (sals_end.sals);
1050         }
1051     }
1052
1053   if (*arg1)
1054     error (_("Junk at end of line specification."));
1055
1056   if (!no_end && !dummy_beg && !dummy_end
1057       && sal.symtab != sal_end.symtab)
1058     error (_("Specified start and end are in different files."));
1059   if (dummy_beg && dummy_end)
1060     error (_("Two empty args do not say what lines to list."));
1061
1062   /* If line was specified by address,
1063      first print exactly which line, and which file.
1064
1065      In this case, sal.symtab == 0 means address is outside of all
1066      known source files, not that user failed to give a filename.  */
1067   if (*arg == '*')
1068     {
1069       struct gdbarch *gdbarch;
1070
1071       if (sal.symtab == 0)
1072         error (_("No source file for address %s."),
1073                paddress (get_current_arch (), sal.pc));
1074
1075       gdbarch = get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
1076       sym = find_pc_function (sal.pc);
1077       if (sym)
1078         printf_filtered ("%s is in %s (%s:%d).\n",
1079                          paddress (gdbarch, sal.pc),
1080                          SYMBOL_PRINT_NAME (sym),
1081                          symtab_to_filename_for_display (sal.symtab), sal.line);
1082       else
1083         printf_filtered ("%s is at %s:%d.\n",
1084                          paddress (gdbarch, sal.pc),
1085                          symtab_to_filename_for_display (sal.symtab), sal.line);
1086     }
1087
1088   /* If line was not specified by just a line number, and it does not
1089      imply a symtab, it must be an undebuggable symbol which means no
1090      source code.  */
1091
1092   if (!linenum_beg && sal.symtab == 0)
1093     error (_("No line number known for %s."), arg);
1094
1095   /* If this command is repeated with RET,
1096      turn it into the no-arg variant.  */
1097
1098   if (from_tty)
1099     *arg = 0;
1100
1101   if (dummy_beg && sal_end.symtab == 0)
1102     error (_("No default source file yet.  Do \"help list\"."));
1103   if (dummy_beg)
1104     print_source_lines (sal_end.symtab,
1105                         std::max (sal_end.line - (get_lines_to_list () - 1), 1),
1106                         sal_end.line + 1, 0);
1107   else if (sal.symtab == 0)
1108     error (_("No default source file yet.  Do \"help list\"."));
1109   else if (no_end)
1110     {
1111       int first_line = sal.line - get_lines_to_list () / 2;
1112
1113       if (first_line < 1) first_line = 1;
1114
1115       print_source_lines (sal.symtab,
1116                           first_line,
1117                           first_line + get_lines_to_list (),
1118                           0);
1119     }
1120   else
1121     print_source_lines (sal.symtab, sal.line,
1122                         (dummy_end
1123                          ? sal.line + get_lines_to_list ()
1124                          : sal_end.line + 1),
1125                         0);
1126   do_cleanups (cleanup);
1127 }
1128
1129 /* Subroutine of disassemble_command to simplify it.
1130    Perform the disassembly.
1131    NAME is the name of the function if known, or NULL.
1132    [LOW,HIGH) are the range of addresses to disassemble.
1133    MIXED is non-zero to print source with the assembler.  */
1134
1135 static void
1136 print_disassembly (struct gdbarch *gdbarch, const char *name,
1137                    CORE_ADDR low, CORE_ADDR high, int flags)
1138 {
1139 #if defined(TUI)
1140   if (!tui_is_window_visible (DISASSEM_WIN))
1141 #endif
1142     {
1143       printf_filtered ("Dump of assembler code ");
1144       if (name != NULL)
1145         printf_filtered ("for function %s:\n", name);
1146       else
1147         printf_filtered ("from %s to %s:\n",
1148                          paddress (gdbarch, low), paddress (gdbarch, high));
1149
1150       /* Dump the specified range.  */
1151       gdb_disassembly (gdbarch, current_uiout, 0, flags, -1, low, high);
1152
1153       printf_filtered ("End of assembler dump.\n");
1154       gdb_flush (gdb_stdout);
1155     }
1156 #if defined(TUI)
1157   else
1158     {
1159       tui_show_assembly (gdbarch, low);
1160     }
1161 #endif
1162 }
1163
1164 /* Subroutine of disassemble_command to simplify it.
1165    Print a disassembly of the current function according to FLAGS.  */
1166
1167 static void
1168 disassemble_current_function (int flags)
1169 {
1170   struct frame_info *frame;
1171   struct gdbarch *gdbarch;
1172   CORE_ADDR low, high, pc;
1173   const char *name;
1174
1175   frame = get_selected_frame (_("No frame selected."));
1176   gdbarch = get_frame_arch (frame);
1177   pc = get_frame_address_in_block (frame);
1178   if (find_pc_partial_function (pc, &name, &low, &high) == 0)
1179     error (_("No function contains program counter for selected frame."));
1180 #if defined(TUI)
1181   /* NOTE: cagney/2003-02-13 The `tui_active' was previously
1182      `tui_version'.  */
1183   if (tui_active)
1184     /* FIXME: cagney/2004-02-07: This should be an observer.  */
1185     low = tui_get_low_disassembly_address (gdbarch, low, pc);
1186 #endif
1187   low += gdbarch_deprecated_function_start_offset (gdbarch);
1188
1189   print_disassembly (gdbarch, name, low, high, flags);
1190 }
1191
1192 /* Dump a specified section of assembly code.
1193
1194    Usage:
1195      disassemble [/mrs]
1196        - dump the assembly code for the function of the current pc
1197      disassemble [/mrs] addr
1198        - dump the assembly code for the function at ADDR
1199      disassemble [/mrs] low,high
1200      disassemble [/mrs] low,+length
1201        - dump the assembly code in the range [LOW,HIGH), or [LOW,LOW+length)
1202
1203    A /m modifier will include source code with the assembly in a
1204    "source centric" view.  This view lists only the file of the first insn,
1205    even if other source files are involved (e.g., inlined functions), and
1206    the output is in source order, even with optimized code.  This view is
1207    considered deprecated as it hasn't been useful in practice.
1208
1209    A /r modifier will include raw instructions in hex with the assembly.
1210
1211    A /s modifier will include source code with the assembly, like /m, with
1212    two important differences:
1213    1) The output is still in pc address order.
1214    2) File names and contents for all relevant source files are displayed.  */
1215
1216 static void
1217 disassemble_command (char *arg, int from_tty)
1218 {
1219   struct gdbarch *gdbarch = get_current_arch ();
1220   CORE_ADDR low, high;
1221   const char *name;
1222   CORE_ADDR pc;
1223   int flags;
1224   const char *p;
1225
1226   p = arg;
1227   name = NULL;
1228   flags = 0;
1229
1230   if (p && *p == '/')
1231     {
1232       ++p;
1233
1234       if (*p == '\0')
1235         error (_("Missing modifier."));
1236
1237       while (*p && ! isspace (*p))
1238         {
1239           switch (*p++)
1240             {
1241             case 'm':
1242               flags |= DISASSEMBLY_SOURCE_DEPRECATED;
1243               break;
1244             case 'r':
1245               flags |= DISASSEMBLY_RAW_INSN;
1246               break;
1247             case 's':
1248               flags |= DISASSEMBLY_SOURCE;
1249               break;
1250             default:
1251               error (_("Invalid disassembly modifier."));
1252             }
1253         }
1254
1255       p = skip_spaces_const (p);
1256     }
1257
1258   if ((flags & (DISASSEMBLY_SOURCE_DEPRECATED | DISASSEMBLY_SOURCE))
1259       == (DISASSEMBLY_SOURCE_DEPRECATED | DISASSEMBLY_SOURCE))
1260     error (_("Cannot specify both /m and /s."));
1261
1262   if (! p || ! *p)
1263     {
1264       flags |= DISASSEMBLY_OMIT_FNAME;
1265       disassemble_current_function (flags);
1266       return;
1267     }
1268
1269   pc = value_as_address (parse_to_comma_and_eval (&p));
1270   if (p[0] == ',')
1271     ++p;
1272   if (p[0] == '\0')
1273     {
1274       /* One argument.  */
1275       if (find_pc_partial_function (pc, &name, &low, &high) == 0)
1276         error (_("No function contains specified address."));
1277 #if defined(TUI)
1278       /* NOTE: cagney/2003-02-13 The `tui_active' was previously
1279          `tui_version'.  */
1280       if (tui_active)
1281         /* FIXME: cagney/2004-02-07: This should be an observer.  */
1282         low = tui_get_low_disassembly_address (gdbarch, low, pc);
1283 #endif
1284       low += gdbarch_deprecated_function_start_offset (gdbarch);
1285       flags |= DISASSEMBLY_OMIT_FNAME;
1286     }
1287   else
1288     {
1289       /* Two arguments.  */
1290       int incl_flag = 0;
1291       low = pc;
1292       p = skip_spaces_const (p);
1293       if (p[0] == '+')
1294         {
1295           ++p;
1296           incl_flag = 1;
1297         }
1298       high = parse_and_eval_address (p);
1299       if (incl_flag)
1300         high += low;
1301     }
1302
1303   print_disassembly (gdbarch, name, low, high, flags);
1304 }
1305
1306 static void
1307 make_command (char *arg, int from_tty)
1308 {
1309   char *p;
1310
1311   if (arg == 0)
1312     p = "make";
1313   else
1314     {
1315       p = (char *) xmalloc (sizeof ("make ") + strlen (arg));
1316       strcpy (p, "make ");
1317       strcpy (p + sizeof ("make ") - 1, arg);
1318     }
1319
1320   shell_escape (p, from_tty);
1321 }
1322
1323 static void
1324 show_user (char *args, int from_tty)
1325 {
1326   struct cmd_list_element *c;
1327   extern struct cmd_list_element *cmdlist;
1328
1329   if (args)
1330     {
1331       const char *comname = args;
1332
1333       c = lookup_cmd (&comname, cmdlist, "", 0, 1);
1334       if (!cli_user_command_p (c))
1335         error (_("Not a user command."));
1336       show_user_1 (c, "", args, gdb_stdout);
1337     }
1338   else
1339     {
1340       for (c = cmdlist; c; c = c->next)
1341         {
1342           if (cli_user_command_p (c) || c->prefixlist != NULL)
1343             show_user_1 (c, "", c->name, gdb_stdout);
1344         }
1345     }
1346 }
1347
1348 /* Search through names of commands and documentations for a certain
1349    regular expression.  */
1350
1351 static void 
1352 apropos_command (char *searchstr, int from_tty)
1353 {
1354   regex_t pattern;
1355   int code;
1356
1357   if (searchstr == NULL)
1358     error (_("REGEXP string is empty"));
1359
1360   code = regcomp (&pattern, searchstr, REG_ICASE);
1361   if (code == 0)
1362     {
1363       struct cleanup *cleanups;
1364
1365       cleanups = make_regfree_cleanup (&pattern);
1366       apropos_cmd (gdb_stdout, cmdlist, &pattern, "");
1367       do_cleanups (cleanups);
1368     }
1369   else
1370     {
1371       char *err = get_regcomp_error (code, &pattern);
1372
1373       make_cleanup (xfree, err);
1374       error (_("Error in regular expression: %s"), err);
1375     }
1376 }
1377
1378 /* Subroutine of alias_command to simplify it.
1379    Return the first N elements of ARGV flattened back to a string
1380    with a space separating each element.
1381    ARGV may not be NULL.
1382    This does not take care of quoting elements in case they contain spaces
1383    on purpose.  */
1384
1385 static dyn_string_t
1386 argv_to_dyn_string (char **argv, int n)
1387 {
1388   int i;
1389   dyn_string_t result = dyn_string_new (10);
1390
1391   gdb_assert (argv != NULL);
1392   gdb_assert (n >= 0 && n <= countargv (argv));
1393
1394   for (i = 0; i < n; ++i)
1395     {
1396       if (i > 0)
1397         dyn_string_append_char (result, ' ');
1398       dyn_string_append_cstr (result, argv[i]);
1399     }
1400
1401   return result;
1402 }
1403
1404 /* Subroutine of alias_command to simplify it.
1405    Return TRUE if COMMAND exists, unambiguously.  Otherwise FALSE.  */
1406
1407 static int
1408 valid_command_p (const char *command)
1409 {
1410   struct cmd_list_element *c;
1411
1412   c = lookup_cmd_1 (& command, cmdlist, NULL, 1);
1413
1414   if (c == NULL || c == (struct cmd_list_element *) -1)
1415     return FALSE;
1416
1417   /* This is the slightly tricky part.
1418      lookup_cmd_1 will return a pointer to the last part of COMMAND
1419      to match, leaving COMMAND pointing at the remainder.  */
1420   while (*command == ' ' || *command == '\t')
1421     ++command;
1422   return *command == '\0';
1423 }
1424
1425 /* Called when "alias" was incorrectly used.  */
1426
1427 static void
1428 alias_usage_error (void)
1429 {
1430   error (_("Usage: alias [-a] [--] ALIAS = COMMAND"));
1431 }
1432
1433 /* Make an alias of an existing command.  */
1434
1435 static void
1436 alias_command (char *args, int from_tty)
1437 {
1438   int i, alias_argc, command_argc;
1439   int abbrev_flag = 0;
1440   char *args2, *equals, *alias, *command;
1441   char **alias_argv, **command_argv;
1442   dyn_string_t alias_dyn_string, command_dyn_string;
1443   struct cleanup *cleanup;
1444
1445   if (args == NULL || strchr (args, '=') == NULL)
1446     alias_usage_error ();
1447
1448   args2 = xstrdup (args);
1449   cleanup = make_cleanup (xfree, args2);
1450   equals = strchr (args2, '=');
1451   *equals = '\0';
1452   alias_argv = gdb_buildargv (args2);
1453   make_cleanup_freeargv (alias_argv);
1454   command_argv = gdb_buildargv (equals + 1);
1455   make_cleanup_freeargv (command_argv);
1456
1457   for (i = 0; alias_argv[i] != NULL; )
1458     {
1459       if (strcmp (alias_argv[i], "-a") == 0)
1460         {
1461           ++alias_argv;
1462           abbrev_flag = 1;
1463         }
1464       else if (strcmp (alias_argv[i], "--") == 0)
1465         {
1466           ++alias_argv;
1467           break;
1468         }
1469       else
1470         break;
1471     }
1472
1473   if (alias_argv[0] == NULL || command_argv[0] == NULL
1474       || *alias_argv[0] == '\0' || *command_argv[0] == '\0')
1475     alias_usage_error ();
1476
1477   for (i = 0; alias_argv[i] != NULL; ++i)
1478     {
1479       if (! valid_user_defined_cmd_name_p (alias_argv[i]))
1480         {
1481           if (i == 0)
1482             error (_("Invalid command name: %s"), alias_argv[i]);
1483           else
1484             error (_("Invalid command element name: %s"), alias_argv[i]);
1485         }
1486     }
1487
1488   alias_argc = countargv (alias_argv);
1489   command_argc = countargv (command_argv);
1490
1491   /* COMMAND must exist.
1492      Reconstruct the command to remove any extraneous spaces,
1493      for better error messages.  */
1494   command_dyn_string = argv_to_dyn_string (command_argv, command_argc);
1495   make_cleanup_dyn_string_delete (command_dyn_string);
1496   command = dyn_string_buf (command_dyn_string);
1497   if (! valid_command_p (command))
1498     error (_("Invalid command to alias to: %s"), command);
1499
1500   /* ALIAS must not exist.  */
1501   alias_dyn_string = argv_to_dyn_string (alias_argv, alias_argc);
1502   make_cleanup_dyn_string_delete (alias_dyn_string);
1503   alias = dyn_string_buf (alias_dyn_string);
1504   if (valid_command_p (alias))
1505     error (_("Alias already exists: %s"), alias);
1506
1507   /* If ALIAS is one word, it is an alias for the entire COMMAND.
1508      Example: alias spe = set print elements
1509
1510      Otherwise ALIAS and COMMAND must have the same number of words,
1511      and every word except the last must match; and the last word of
1512      ALIAS is made an alias of the last word of COMMAND.
1513      Example: alias set print elms = set pr elem
1514      Note that unambiguous abbreviations are allowed.  */
1515
1516   if (alias_argc == 1)
1517     {
1518       /* add_cmd requires *we* allocate space for name, hence the xstrdup.  */
1519       add_com_alias (xstrdup (alias_argv[0]), command, class_alias,
1520                      abbrev_flag);
1521     }
1522   else
1523     {
1524       dyn_string_t alias_prefix_dyn_string, command_prefix_dyn_string;
1525       const char *alias_prefix, *command_prefix;
1526       struct cmd_list_element *c_alias, *c_command;
1527
1528       if (alias_argc != command_argc)
1529         error (_("Mismatched command length between ALIAS and COMMAND."));
1530
1531       /* Create copies of ALIAS and COMMAND without the last word,
1532          and use that to verify the leading elements match.  */
1533       alias_prefix_dyn_string =
1534         argv_to_dyn_string (alias_argv, alias_argc - 1);
1535       make_cleanup_dyn_string_delete (alias_prefix_dyn_string);
1536       command_prefix_dyn_string =
1537         argv_to_dyn_string (alias_argv, command_argc - 1);
1538       make_cleanup_dyn_string_delete (command_prefix_dyn_string);
1539       alias_prefix = dyn_string_buf (alias_prefix_dyn_string);
1540       command_prefix = dyn_string_buf (command_prefix_dyn_string);
1541
1542       c_command = lookup_cmd_1 (& command_prefix, cmdlist, NULL, 1);
1543       /* We've already tried to look up COMMAND.  */
1544       gdb_assert (c_command != NULL
1545                   && c_command != (struct cmd_list_element *) -1);
1546       gdb_assert (c_command->prefixlist != NULL);
1547       c_alias = lookup_cmd_1 (& alias_prefix, cmdlist, NULL, 1);
1548       if (c_alias != c_command)
1549         error (_("ALIAS and COMMAND prefixes do not match."));
1550
1551       /* add_cmd requires *we* allocate space for name, hence the xstrdup.  */
1552       add_alias_cmd (xstrdup (alias_argv[alias_argc - 1]),
1553                      command_argv[command_argc - 1],
1554                      class_alias, abbrev_flag, c_command->prefixlist);
1555     }
1556
1557   do_cleanups (cleanup);
1558 }
1559 \f
1560 /* Print a list of files and line numbers which a user may choose from
1561    in order to list a function which was specified ambiguously (as
1562    with `list classname::overloadedfuncname', for example).  The
1563    vector in SALS provides the filenames and line numbers.  */
1564
1565 static void
1566 ambiguous_line_spec (struct symtabs_and_lines *sals)
1567 {
1568   int i;
1569
1570   for (i = 0; i < sals->nelts; ++i)
1571     printf_filtered (_("file: \"%s\", line number: %d\n"),
1572                      symtab_to_filename_for_display (sals->sals[i].symtab),
1573                      sals->sals[i].line);
1574 }
1575
1576 /* Sort function for filter_sals.  */
1577
1578 static int
1579 compare_symtabs (const void *a, const void *b)
1580 {
1581   const struct symtab_and_line *sala = (const struct symtab_and_line *) a;
1582   const struct symtab_and_line *salb = (const struct symtab_and_line *) b;
1583   const char *dira = SYMTAB_DIRNAME (sala->symtab);
1584   const char *dirb = SYMTAB_DIRNAME (salb->symtab);
1585   int r;
1586
1587   if (dira == NULL)
1588     {
1589       if (dirb != NULL)
1590         return -1;
1591     }
1592   else if (dirb == NULL)
1593     {
1594       if (dira != NULL)
1595         return 1;
1596     }
1597   else
1598     {
1599       r = filename_cmp (dira, dirb);
1600       if (r)
1601         return r;
1602     }
1603
1604   r = filename_cmp (sala->symtab->filename, salb->symtab->filename);
1605   if (r)
1606     return r;
1607
1608   if (sala->line < salb->line)
1609     return -1;
1610   return sala->line == salb->line ? 0 : 1;
1611 }
1612
1613 /* Remove any SALs that do not match the current program space, or
1614    which appear to be "file:line" duplicates.  */
1615
1616 static void
1617 filter_sals (struct symtabs_and_lines *sals)
1618 {
1619   int i, out, prev;
1620
1621   out = 0;
1622   for (i = 0; i < sals->nelts; ++i)
1623     {
1624       if (sals->sals[i].pspace == current_program_space
1625           && sals->sals[i].symtab != NULL)
1626         {
1627           sals->sals[out] = sals->sals[i];
1628           ++out;
1629         }
1630     }
1631   sals->nelts = out;
1632
1633   qsort (sals->sals, sals->nelts, sizeof (struct symtab_and_line),
1634          compare_symtabs);
1635
1636   out = 1;
1637   prev = 0;
1638   for (i = 1; i < sals->nelts; ++i)
1639     {
1640       if (compare_symtabs (&sals->sals[prev], &sals->sals[i]))
1641         {
1642           /* Symtabs differ.  */
1643           sals->sals[out] = sals->sals[i];
1644           prev = out;
1645           ++out;
1646         }
1647     }
1648
1649   if (sals->nelts == 0)
1650     {
1651       xfree (sals->sals);
1652       sals->sals = NULL;
1653     }
1654   else
1655     sals->nelts = out;
1656 }
1657
1658 static void
1659 set_debug (char *arg, int from_tty)
1660 {
1661   printf_unfiltered (_("\"set debug\" must be followed by "
1662                        "the name of a debug subcommand.\n"));
1663   help_list (setdebuglist, "set debug ", all_commands, gdb_stdout);
1664 }
1665
1666 static void
1667 show_debug (char *args, int from_tty)
1668 {
1669   cmd_show_list (showdebuglist, from_tty, "");
1670 }
1671
1672 void
1673 init_cmd_lists (void)
1674 {
1675   max_user_call_depth = 1024;
1676 }
1677
1678 static void
1679 show_info_verbose (struct ui_file *file, int from_tty,
1680                    struct cmd_list_element *c,
1681                    const char *value)
1682 {
1683   if (info_verbose)
1684     fprintf_filtered (file,
1685                       _("Verbose printing of informational messages is %s.\n"),
1686                       value);
1687   else
1688     fprintf_filtered (file, _("Verbosity is %s.\n"), value);
1689 }
1690
1691 static void
1692 show_history_expansion_p (struct ui_file *file, int from_tty,
1693                           struct cmd_list_element *c, const char *value)
1694 {
1695   fprintf_filtered (file, _("History expansion on command input is %s.\n"),
1696                     value);
1697 }
1698
1699 static void
1700 show_remote_debug (struct ui_file *file, int from_tty,
1701                    struct cmd_list_element *c, const char *value)
1702 {
1703   fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
1704                     value);
1705 }
1706
1707 static void
1708 show_remote_timeout (struct ui_file *file, int from_tty,
1709                      struct cmd_list_element *c, const char *value)
1710 {
1711   fprintf_filtered (file,
1712                     _("Timeout limit to wait for target to respond is %s.\n"),
1713                     value);
1714 }
1715
1716 static void
1717 show_max_user_call_depth (struct ui_file *file, int from_tty,
1718                           struct cmd_list_element *c, const char *value)
1719 {
1720   fprintf_filtered (file,
1721                     _("The max call depth for user-defined commands is %s.\n"),
1722                     value);
1723 }
1724
1725 \f
1726
1727 initialize_file_ftype _initialize_cli_cmds;
1728
1729 void
1730 _initialize_cli_cmds (void)
1731 {
1732   struct cmd_list_element *c;
1733
1734   /* Define the classes of commands.
1735      They will appear in the help list in alphabetical order.  */
1736
1737   add_cmd ("internals", class_maintenance, NULL, _("\
1738 Maintenance commands.\n\
1739 Some gdb commands are provided just for use by gdb maintainers.\n\
1740 These commands are subject to frequent change, and may not be as\n\
1741 well documented as user commands."),
1742            &cmdlist);
1743   add_cmd ("obscure", class_obscure, NULL, _("Obscure features."), &cmdlist);
1744   add_cmd ("aliases", class_alias, NULL,
1745            _("Aliases of other commands."), &cmdlist);
1746   add_cmd ("user-defined", class_user, NULL, _("\
1747 User-defined commands.\n\
1748 The commands in this class are those defined by the user.\n\
1749 Use the \"define\" command to define a command."), &cmdlist);
1750   add_cmd ("support", class_support, NULL, _("Support facilities."), &cmdlist);
1751   if (!dbx_commands)
1752     add_cmd ("status", class_info, NULL, _("Status inquiries."), &cmdlist);
1753   add_cmd ("files", class_files, NULL, _("Specifying and examining files."),
1754            &cmdlist);
1755   add_cmd ("breakpoints", class_breakpoint, NULL,
1756            _("Making program stop at certain points."), &cmdlist);
1757   add_cmd ("data", class_vars, NULL, _("Examining data."), &cmdlist);
1758   add_cmd ("stack", class_stack, NULL, _("\
1759 Examining the stack.\n\
1760 The stack is made up of stack frames.  Gdb assigns numbers to stack frames\n\
1761 counting from zero for the innermost (currently executing) frame.\n\n\
1762 At any time gdb identifies one frame as the \"selected\" frame.\n\
1763 Variable lookups are done with respect to the selected frame.\n\
1764 When the program being debugged stops, gdb selects the innermost frame.\n\
1765 The commands below can be used to select other frames by number or address."),
1766            &cmdlist);
1767   add_cmd ("running", class_run, NULL, _("Running the program."), &cmdlist);
1768
1769   /* Define general commands.  */
1770
1771   add_com ("pwd", class_files, pwd_command, _("\
1772 Print working directory.  This is used for your program as well."));
1773
1774   c = add_cmd ("cd", class_files, cd_command, _("\
1775 Set working directory to DIR for debugger and program being debugged.\n\
1776 The change does not take effect for the program being debugged\n\
1777 until the next time it is started."), &cmdlist);
1778   set_cmd_completer (c, filename_completer);
1779
1780   add_com ("echo", class_support, echo_command, _("\
1781 Print a constant string.  Give string as argument.\n\
1782 C escape sequences may be used in the argument.\n\
1783 No newline is added at the end of the argument;\n\
1784 use \"\\n\" if you want a newline to be printed.\n\
1785 Since leading and trailing whitespace are ignored in command arguments,\n\
1786 if you want to print some you must use \"\\\" before leading whitespace\n\
1787 to be printed or after trailing whitespace."));
1788
1789   add_setshow_enum_cmd ("script-extension", class_support,
1790                         script_ext_enums, &script_ext_mode, _("\
1791 Set mode for script filename extension recognition."), _("\
1792 Show mode for script filename extension recognition."), _("\
1793 off  == no filename extension recognition (all sourced files are GDB scripts)\n\
1794 soft == evaluate script according to filename extension, fallback to GDB script"
1795   "\n\
1796 strict == evaluate script according to filename extension, error if not supported"
1797   ),
1798                         NULL,
1799                         show_script_ext_mode,
1800                         &setlist, &showlist);
1801
1802   add_com ("quit", class_support, quit_command, _("\
1803 Exit gdb.\n\
1804 Usage: quit [EXPR]\n\
1805 The optional expression EXPR, if present, is evaluated and the result\n\
1806 used as GDB's exit code.  The default is zero."));
1807   c = add_com ("help", class_support, help_command,
1808                _("Print list of commands."));
1809   set_cmd_completer (c, command_completer);
1810   add_com_alias ("q", "quit", class_support, 1);
1811   add_com_alias ("h", "help", class_support, 1);
1812
1813   add_setshow_boolean_cmd ("verbose", class_support, &info_verbose, _("\
1814 Set verbosity."), _("\
1815 Show verbosity."), NULL,
1816                            set_verbose,
1817                            show_info_verbose,
1818                            &setlist, &showlist);
1819
1820   add_prefix_cmd ("history", class_support, set_history,
1821                   _("Generic command for setting command history parameters."),
1822                   &sethistlist, "set history ", 0, &setlist);
1823   add_prefix_cmd ("history", class_support, show_history,
1824                   _("Generic command for showing command history parameters."),
1825                   &showhistlist, "show history ", 0, &showlist);
1826
1827   add_setshow_boolean_cmd ("expansion", no_class, &history_expansion_p, _("\
1828 Set history expansion on command input."), _("\
1829 Show history expansion on command input."), _("\
1830 Without an argument, history expansion is enabled."),
1831                            NULL,
1832                            show_history_expansion_p,
1833                            &sethistlist, &showhistlist);
1834
1835   add_prefix_cmd ("info", class_info, info_command, _("\
1836 Generic command for showing things about the program being debugged."),
1837                   &infolist, "info ", 0, &cmdlist);
1838   add_com_alias ("i", "info", class_info, 1);
1839   add_com_alias ("inf", "info", class_info, 1);
1840
1841   add_com ("complete", class_obscure, complete_command,
1842            _("List the completions for the rest of the line as a command."));
1843
1844   add_prefix_cmd ("show", class_info, show_command, _("\
1845 Generic command for showing things about the debugger."),
1846                   &showlist, "show ", 0, &cmdlist);
1847   /* Another way to get at the same thing.  */
1848   add_info ("set", show_command, _("Show all GDB settings."));
1849
1850   add_cmd ("commands", no_set_class, show_commands, _("\
1851 Show the history of commands you typed.\n\
1852 You can supply a command number to start with, or a `+' to start after\n\
1853 the previous command number shown."),
1854            &showlist);
1855
1856   add_cmd ("version", no_set_class, show_version,
1857            _("Show what version of GDB this is."), &showlist);
1858
1859   add_cmd ("configuration", no_set_class, show_configuration,
1860            _("Show how GDB was configured at build time."), &showlist);
1861
1862   add_setshow_zinteger_cmd ("remote", no_class, &remote_debug, _("\
1863 Set debugging of remote protocol."), _("\
1864 Show debugging of remote protocol."), _("\
1865 When enabled, each packet sent or received with the remote target\n\
1866 is displayed."),
1867                             NULL,
1868                             show_remote_debug,
1869                             &setdebuglist, &showdebuglist);
1870
1871   add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
1872                                        &remote_timeout, _("\
1873 Set timeout limit to wait for target to respond."), _("\
1874 Show timeout limit to wait for target to respond."), _("\
1875 This value is used to set the time limit for gdb to wait for a response\n\
1876 from the target."),
1877                                        NULL,
1878                                        show_remote_timeout,
1879                                        &setlist, &showlist);
1880
1881   add_prefix_cmd ("debug", no_class, set_debug,
1882                   _("Generic command for setting gdb debugging flags"),
1883                   &setdebuglist, "set debug ", 0, &setlist);
1884
1885   add_prefix_cmd ("debug", no_class, show_debug,
1886                   _("Generic command for showing gdb debugging flags"),
1887                   &showdebuglist, "show debug ", 0, &showlist);
1888
1889   c = add_com ("shell", class_support, shell_escape, _("\
1890 Execute the rest of the line as a shell command.\n\
1891 With no arguments, run an inferior shell."));
1892   set_cmd_completer (c, filename_completer);
1893
1894   c = add_com ("edit", class_files, edit_command, _("\
1895 Edit specified file or function.\n\
1896 With no argument, edits file containing most recent line listed.\n\
1897 Editing targets can be specified in these ways:\n\
1898   FILE:LINENUM, to edit at that line in that file,\n\
1899   FUNCTION, to edit at the beginning of that function,\n\
1900   FILE:FUNCTION, to distinguish among like-named static functions.\n\
1901   *ADDRESS, to edit at the line containing that address.\n\
1902 Uses EDITOR environment variable contents as editor (or ex as default)."));
1903
1904   c->completer = location_completer;
1905
1906   add_com ("list", class_files, list_command, _("\
1907 List specified function or line.\n\
1908 With no argument, lists ten more lines after or around previous listing.\n\
1909 \"list -\" lists the ten lines before a previous ten-line listing.\n\
1910 One argument specifies a line, and ten lines are listed around that line.\n\
1911 Two arguments with comma between specify starting and ending lines to list.\n\
1912 Lines can be specified in these ways:\n\
1913   LINENUM, to list around that line in current file,\n\
1914   FILE:LINENUM, to list around that line in that file,\n\
1915   FUNCTION, to list around beginning of that function,\n\
1916   FILE:FUNCTION, to distinguish among like-named static functions.\n\
1917   *ADDRESS, to list around the line containing that address.\n\
1918 With two args, if one is empty, it stands for ten lines away from\n\
1919 the other arg.\n\
1920 \n\
1921 By default, when a single location is given, display ten lines.\n\
1922 This can be changed using \"set listsize\", and the current value\n\
1923 can be shown using \"show listsize\"."));
1924
1925   add_com_alias ("l", "list", class_files, 1);
1926
1927   if (dbx_commands)
1928     add_com_alias ("file", "list", class_files, 1);
1929
1930   c = add_com ("disassemble", class_vars, disassemble_command, _("\
1931 Disassemble a specified section of memory.\n\
1932 Default is the function surrounding the pc of the selected frame.\n\
1933 \n\
1934 With a /m modifier, source lines are included (if available).\n\
1935 This view is \"source centric\": the output is in source line order,\n\
1936 regardless of any optimization that is present.  Only the main source file\n\
1937 is displayed, not those of, e.g., any inlined functions.\n\
1938 This modifier hasn't proved useful in practice and is deprecated\n\
1939 in favor of /s.\n\
1940 \n\
1941 With a /s modifier, source lines are included (if available).\n\
1942 This differs from /m in two important respects:\n\
1943 - the output is still in pc address order, and\n\
1944 - file names and contents for all relevant source files are displayed.\n\
1945 \n\
1946 With a /r modifier, raw instructions in hex are included.\n\
1947 \n\
1948 With a single argument, the function surrounding that address is dumped.\n\
1949 Two arguments (separated by a comma) are taken as a range of memory to dump,\n\
1950   in the form of \"start,end\", or \"start,+length\".\n\
1951 \n\
1952 Note that the address is interpreted as an expression, not as a location\n\
1953 like in the \"break\" command.\n\
1954 So, for example, if you want to disassemble function bar in file foo.c\n\
1955 you must type \"disassemble 'foo.c'::bar\" and not \"disassemble foo.c:bar\"."));
1956   set_cmd_completer (c, location_completer);
1957
1958   add_com_alias ("!", "shell", class_support, 0);
1959
1960   c = add_com ("make", class_support, make_command, _("\
1961 Run the ``make'' program using the rest of the line as arguments."));
1962   set_cmd_completer (c, filename_completer);
1963   add_cmd ("user", no_class, show_user, _("\
1964 Show definitions of non-python/scheme user defined commands.\n\
1965 Argument is the name of the user defined command.\n\
1966 With no argument, show definitions of all user defined commands."), &showlist);
1967   add_com ("apropos", class_support, apropos_command,
1968            _("Search for commands matching a REGEXP"));
1969
1970   add_setshow_uinteger_cmd ("max-user-call-depth", no_class,
1971                            &max_user_call_depth, _("\
1972 Set the max call depth for non-python/scheme user-defined commands."), _("\
1973 Show the max call depth for non-python/scheme user-defined commands."), NULL,
1974                             NULL,
1975                             show_max_user_call_depth,
1976                             &setlist, &showlist);
1977
1978   add_setshow_boolean_cmd ("trace-commands", no_class, &trace_commands, _("\
1979 Set tracing of GDB CLI commands."), _("\
1980 Show state of GDB CLI command tracing."), _("\
1981 When 'on', each command is displayed as it is executed."),
1982                            NULL,
1983                            NULL,
1984                            &setlist, &showlist);
1985
1986   c = add_com ("alias", class_support, alias_command, _("\
1987 Define a new command that is an alias of an existing command.\n\
1988 Usage: alias [-a] [--] ALIAS = COMMAND\n\
1989 ALIAS is the name of the alias command to create.\n\
1990 COMMAND is the command being aliased to.\n\
1991 If \"-a\" is specified, the command is an abbreviation,\n\
1992 and will not appear in help command list output.\n\
1993 \n\
1994 Examples:\n\
1995 Make \"spe\" an alias of \"set print elements\":\n\
1996   alias spe = set print elements\n\
1997 Make \"elms\" an alias of \"elements\" in the \"set print\" command:\n\
1998   alias -a set print elms = set print elements"));
1999 }
2000
2001 void
2002 init_cli_cmds (void)
2003 {
2004   struct cmd_list_element *c;
2005   char *source_help_text;
2006
2007   source_help_text = xstrprintf (_("\
2008 Read commands from a file named FILE.\n\
2009 \n\
2010 Usage: source [-s] [-v] FILE\n\
2011 -s: search for the script in the source search path,\n\
2012     even if FILE contains directories.\n\
2013 -v: each command in FILE is echoed as it is executed.\n\
2014 \n\
2015 Note that the file \"%s\" is read automatically in this way\n\
2016 when GDB is started."), gdbinit);
2017   c = add_cmd ("source", class_support, source_command,
2018                source_help_text, &cmdlist);
2019   set_cmd_completer (c, filename_completer);
2020 }