Constify add_com
[external/binutils.git] / gdb / infcmd.c
1 /* Memory-access and commands for "inferior" process, for GDB.
2
3    Copyright (C) 1986-2017 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 <signal.h>
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "infrun.h"
28 #include "environ.h"
29 #include "value.h"
30 #include "gdbcmd.h"
31 #include "symfile.h"
32 #include "gdbcore.h"
33 #include "target.h"
34 #include "language.h"
35 #include "objfiles.h"
36 #include "completer.h"
37 #include "ui-out.h"
38 #include "event-top.h"
39 #include "parser-defs.h"
40 #include "regcache.h"
41 #include "reggroups.h"
42 #include "block.h"
43 #include "solib.h"
44 #include <ctype.h>
45 #include "observer.h"
46 #include "target-descriptions.h"
47 #include "user-regs.h"
48 #include "cli/cli-decode.h"
49 #include "gdbthread.h"
50 #include "valprint.h"
51 #include "inline-frame.h"
52 #include "tracepoint.h"
53 #include "inf-loop.h"
54 #include "continuations.h"
55 #include "linespec.h"
56 #include "cli/cli-utils.h"
57 #include "infcall.h"
58 #include "thread-fsm.h"
59 #include "top.h"
60 #include "interps.h"
61 #include "common/gdb_optional.h"
62
63 /* Local functions: */
64
65 static void info_registers_command (char *, int);
66
67 static void until_next_command (int);
68
69 static void info_float_command (char *, int);
70
71 static void info_program_command (char *, int);
72
73 static void step_1 (int, int, const char *);
74
75 #define ERROR_NO_INFERIOR \
76    if (!target_has_execution) error (_("The program is not being run."));
77
78 /* Scratch area where string containing arguments to give to the
79    program will be stored by 'set args'.  As soon as anything is
80    stored, notice_args_set will move it into per-inferior storage.
81    Arguments are separated by spaces.  Empty string (pointer to '\0')
82    means no args.  */
83
84 static char *inferior_args_scratch;
85
86 /* Scratch area where the new cwd will be stored by 'set cwd'.  */
87
88 static char *inferior_cwd_scratch;
89
90 /* Scratch area where 'set inferior-tty' will store user-provided value.
91    We'll immediate copy it into per-inferior storage.  */
92
93 static char *inferior_io_terminal_scratch;
94
95 /* Pid of our debugged inferior, or 0 if no inferior now.
96    Since various parts of infrun.c test this to see whether there is a program
97    being debugged it should be nonzero (currently 3 is used) for remote
98    debugging.  */
99
100 ptid_t inferior_ptid;
101
102 /* Address at which inferior stopped.  */
103
104 CORE_ADDR stop_pc;
105
106 /* Nonzero if stopped due to completion of a stack dummy routine.  */
107
108 enum stop_stack_kind stop_stack_dummy;
109
110 /* Nonzero if stopped due to a random (unexpected) signal in inferior
111    process.  */
112
113 int stopped_by_random_signal;
114
115 /* See inferior.h.  */
116
117 int startup_with_shell = 1;
118
119 \f
120 /* Accessor routines.  */
121
122 /* Set the io terminal for the current inferior.  Ownership of
123    TERMINAL_NAME is not transferred.  */
124
125 void 
126 set_inferior_io_terminal (const char *terminal_name)
127 {
128   xfree (current_inferior ()->terminal);
129
130   if (terminal_name != NULL && *terminal_name != '\0')
131     current_inferior ()->terminal = xstrdup (terminal_name);
132   else
133     current_inferior ()->terminal = NULL;
134 }
135
136 const char *
137 get_inferior_io_terminal (void)
138 {
139   return current_inferior ()->terminal;
140 }
141
142 static void
143 set_inferior_tty_command (char *args, int from_tty,
144                           struct cmd_list_element *c)
145 {
146   /* CLI has assigned the user-provided value to inferior_io_terminal_scratch.
147      Now route it to current inferior.  */
148   set_inferior_io_terminal (inferior_io_terminal_scratch);
149 }
150
151 static void
152 show_inferior_tty_command (struct ui_file *file, int from_tty,
153                            struct cmd_list_element *c, const char *value)
154 {
155   /* Note that we ignore the passed-in value in favor of computing it
156      directly.  */
157   const char *inferior_io_terminal = get_inferior_io_terminal ();
158
159   if (inferior_io_terminal == NULL)
160     inferior_io_terminal = "";
161   fprintf_filtered (gdb_stdout,
162                     _("Terminal for future runs of program being debugged "
163                       "is \"%s\".\n"), inferior_io_terminal);
164 }
165
166 char *
167 get_inferior_args (void)
168 {
169   if (current_inferior ()->argc != 0)
170     {
171       char *n;
172
173       n = construct_inferior_arguments (current_inferior ()->argc,
174                                         current_inferior ()->argv);
175       set_inferior_args (n);
176       xfree (n);
177     }
178
179   if (current_inferior ()->args == NULL)
180     current_inferior ()->args = xstrdup ("");
181
182   return current_inferior ()->args;
183 }
184
185 /* Set the arguments for the current inferior.  Ownership of
186    NEWARGS is not transferred.  */
187
188 void
189 set_inferior_args (const char *newargs)
190 {
191   xfree (current_inferior ()->args);
192   current_inferior ()->args = newargs ? xstrdup (newargs) : NULL;
193   current_inferior ()->argc = 0;
194   current_inferior ()->argv = 0;
195 }
196
197 void
198 set_inferior_args_vector (int argc, char **argv)
199 {
200   current_inferior ()->argc = argc;
201   current_inferior ()->argv = argv;
202 }
203
204 /* Notice when `set args' is run.  */
205
206 static void
207 set_args_command (char *args, int from_tty, struct cmd_list_element *c)
208 {
209   /* CLI has assigned the user-provided value to inferior_args_scratch.
210      Now route it to current inferior.  */
211   set_inferior_args (inferior_args_scratch);
212 }
213
214 /* Notice when `show args' is run.  */
215
216 static void
217 show_args_command (struct ui_file *file, int from_tty,
218                    struct cmd_list_element *c, const char *value)
219 {
220   /* Note that we ignore the passed-in value in favor of computing it
221      directly.  */
222   deprecated_show_value_hack (file, from_tty, c, get_inferior_args ());
223 }
224
225 /* See common/common-inferior.h.  */
226
227 void
228 set_inferior_cwd (const char *cwd)
229 {
230   struct inferior *inf = current_inferior ();
231
232   gdb_assert (inf != NULL);
233
234   if (cwd == NULL)
235     inf->cwd.reset ();
236   else
237     inf->cwd.reset (xstrdup (cwd));
238 }
239
240 /* See common/common-inferior.h.  */
241
242 const char *
243 get_inferior_cwd ()
244 {
245   return current_inferior ()->cwd.get ();
246 }
247
248 /* Handle the 'set cwd' command.  */
249
250 static void
251 set_cwd_command (char *args, int from_tty, struct cmd_list_element *c)
252 {
253   if (*inferior_cwd_scratch == '\0')
254     set_inferior_cwd (NULL);
255   else
256     set_inferior_cwd (inferior_cwd_scratch);
257 }
258
259 /* Handle the 'show cwd' command.  */
260
261 static void
262 show_cwd_command (struct ui_file *file, int from_tty,
263                   struct cmd_list_element *c, const char *value)
264 {
265   const char *cwd = get_inferior_cwd ();
266
267   if (cwd == NULL)
268     fprintf_filtered (gdb_stdout,
269                       _("\
270 You have not set the inferior's current working directory.\n\
271 The inferior will inherit GDB's cwd if native debugging, or the remote\n\
272 server's cwd if remote debugging.\n"));
273   else
274     fprintf_filtered (gdb_stdout,
275                       _("Current working directory that will be used "
276                         "when starting the inferior is \"%s\".\n"), cwd);
277 }
278
279 \f
280 /* Compute command-line string given argument vector.  This does the
281    same shell processing as fork_inferior.  */
282
283 char *
284 construct_inferior_arguments (int argc, char **argv)
285 {
286   char *result;
287
288   if (startup_with_shell)
289     {
290 #ifdef __MINGW32__
291       /* This holds all the characters considered special to the
292          Windows shells.  */
293       static const char special[] = "\"!&*|[]{}<>?`~^=;, \t\n";
294       static const char quote = '"';
295 #else
296       /* This holds all the characters considered special to the
297          typical Unix shells.  We include `^' because the SunOS
298          /bin/sh treats it as a synonym for `|'.  */
299       static const char special[] = "\"!#$&*()\\|[]{}<>?'`~^; \t\n";
300       static const char quote = '\'';
301 #endif
302       int i;
303       int length = 0;
304       char *out, *cp;
305
306       /* We over-compute the size.  It shouldn't matter.  */
307       for (i = 0; i < argc; ++i)
308         length += 3 * strlen (argv[i]) + 1 + 2 * (argv[i][0] == '\0');
309
310       result = (char *) xmalloc (length);
311       out = result;
312
313       for (i = 0; i < argc; ++i)
314         {
315           if (i > 0)
316             *out++ = ' ';
317
318           /* Need to handle empty arguments specially.  */
319           if (argv[i][0] == '\0')
320             {
321               *out++ = quote;
322               *out++ = quote;
323             }
324           else
325             {
326 #ifdef __MINGW32__
327               int quoted = 0;
328
329               if (strpbrk (argv[i], special))
330                 {
331                   quoted = 1;
332                   *out++ = quote;
333                 }
334 #endif
335               for (cp = argv[i]; *cp; ++cp)
336                 {
337                   if (*cp == '\n')
338                     {
339                       /* A newline cannot be quoted with a backslash (it
340                          just disappears), only by putting it inside
341                          quotes.  */
342                       *out++ = quote;
343                       *out++ = '\n';
344                       *out++ = quote;
345                     }
346                   else
347                     {
348 #ifdef __MINGW32__
349                       if (*cp == quote)
350 #else
351                       if (strchr (special, *cp) != NULL)
352 #endif
353                         *out++ = '\\';
354                       *out++ = *cp;
355                     }
356                 }
357 #ifdef __MINGW32__
358               if (quoted)
359                 *out++ = quote;
360 #endif
361             }
362         }
363       *out = '\0';
364     }
365   else
366     {
367       /* In this case we can't handle arguments that contain spaces,
368          tabs, or newlines -- see breakup_args().  */
369       int i;
370       int length = 0;
371
372       for (i = 0; i < argc; ++i)
373         {
374           char *cp = strchr (argv[i], ' ');
375           if (cp == NULL)
376             cp = strchr (argv[i], '\t');
377           if (cp == NULL)
378             cp = strchr (argv[i], '\n');
379           if (cp != NULL)
380             error (_("can't handle command-line "
381                      "argument containing whitespace"));
382           length += strlen (argv[i]) + 1;
383         }
384
385       result = (char *) xmalloc (length);
386       result[0] = '\0';
387       for (i = 0; i < argc; ++i)
388         {
389           if (i > 0)
390             strcat (result, " ");
391           strcat (result, argv[i]);
392         }
393     }
394
395   return result;
396 }
397 \f
398
399 /* This function strips the '&' character (indicating background
400    execution) that is added as *the last* of the arguments ARGS of a
401    command.  A copy of the incoming ARGS without the '&' is returned,
402    unless the resulting string after stripping is empty, in which case
403    NULL is returned.  *BG_CHAR_P is an output boolean that indicates
404    whether the '&' character was found.  */
405
406 static gdb::unique_xmalloc_ptr<char>
407 strip_bg_char (const char *args, int *bg_char_p)
408 {
409   const char *p;
410
411   if (args == NULL || *args == '\0')
412     {
413       *bg_char_p = 0;
414       return NULL;
415     }
416
417   p = args + strlen (args);
418   if (p[-1] == '&')
419     {
420       p--;
421       while (p > args && isspace (p[-1]))
422         p--;
423
424       *bg_char_p = 1;
425       if (p != args)
426         return gdb::unique_xmalloc_ptr<char>
427           (savestring (args, p - args));
428       else
429         return gdb::unique_xmalloc_ptr<char> (nullptr);
430     }
431
432   *bg_char_p = 0;
433   return gdb::unique_xmalloc_ptr<char> (xstrdup (args));
434 }
435
436 /* Common actions to take after creating any sort of inferior, by any
437    means (running, attaching, connecting, et cetera).  The target
438    should be stopped.  */
439
440 void
441 post_create_inferior (struct target_ops *target, int from_tty)
442 {
443
444   /* Be sure we own the terminal in case write operations are performed.  */ 
445   target_terminal::ours_for_output ();
446
447   /* If the target hasn't taken care of this already, do it now.
448      Targets which need to access registers during to_open,
449      to_create_inferior, or to_attach should do it earlier; but many
450      don't need to.  */
451   target_find_description ();
452
453   /* Now that we know the register layout, retrieve current PC.  But
454      if the PC is unavailable (e.g., we're opening a core file with
455      missing registers info), ignore it.  */
456   stop_pc = 0;
457   TRY
458     {
459       stop_pc = regcache_read_pc (get_current_regcache ());
460     }
461   CATCH (ex, RETURN_MASK_ERROR)
462     {
463       if (ex.error != NOT_AVAILABLE_ERROR)
464         throw_exception (ex);
465     }
466   END_CATCH
467
468   if (exec_bfd)
469     {
470       const unsigned solib_add_generation
471         = current_program_space->solib_add_generation;
472
473       /* Create the hooks to handle shared library load and unload
474          events.  */
475       solib_create_inferior_hook (from_tty);
476
477       if (current_program_space->solib_add_generation == solib_add_generation)
478         {
479           /* The platform-specific hook should load initial shared libraries,
480              but didn't.  FROM_TTY will be incorrectly 0 but such solib
481              targets should be fixed anyway.  Call it only after the solib
482              target has been initialized by solib_create_inferior_hook.  */
483
484           if (info_verbose)
485             warning (_("platform-specific solib_create_inferior_hook did "
486                        "not load initial shared libraries."));
487
488           /* If the solist is global across processes, there's no need to
489              refetch it here.  */
490           if (!gdbarch_has_global_solist (target_gdbarch ()))
491             solib_add (NULL, 0, auto_solib_add);
492         }
493     }
494
495   /* If the user sets watchpoints before execution having started,
496      then she gets software watchpoints, because GDB can't know which
497      target will end up being pushed, or if it supports hardware
498      watchpoints or not.  breakpoint_re_set takes care of promoting
499      watchpoints to hardware watchpoints if possible, however, if this
500      new inferior doesn't load shared libraries or we don't pull in
501      symbols from any other source on this target/arch,
502      breakpoint_re_set is never called.  Call it now so that software
503      watchpoints get a chance to be promoted to hardware watchpoints
504      if the now pushed target supports hardware watchpoints.  */
505   breakpoint_re_set ();
506
507   observer_notify_inferior_created (target, from_tty);
508 }
509
510 /* Kill the inferior if already running.  This function is designed
511    to be called when we are about to start the execution of the program
512    from the beginning.  Ask the user to confirm that he wants to restart
513    the program being debugged when FROM_TTY is non-null.  */
514
515 static void
516 kill_if_already_running (int from_tty)
517 {
518   if (! ptid_equal (inferior_ptid, null_ptid) && target_has_execution)
519     {
520       /* Bail out before killing the program if we will not be able to
521          restart it.  */
522       target_require_runnable ();
523
524       if (from_tty
525           && !query (_("The program being debugged has been started already.\n\
526 Start it from the beginning? ")))
527         error (_("Program not restarted."));
528       target_kill ();
529     }
530 }
531
532 /* See inferior.h.  */
533
534 void
535 prepare_execution_command (struct target_ops *target, int background)
536 {
537   /* If we get a request for running in the bg but the target
538      doesn't support it, error out.  */
539   if (background && !target->to_can_async_p (target))
540     error (_("Asynchronous execution not supported on this target."));
541
542   if (!background)
543     {
544       /* If we get a request for running in the fg, then we need to
545          simulate synchronous (fg) execution.  Note no cleanup is
546          necessary for this.  stdin is re-enabled whenever an error
547          reaches the top level.  */
548       all_uis_on_sync_execution_starting ();
549     }
550 }
551
552 /* Determine how the new inferior will behave.  */
553
554 enum run_how
555   {
556     /* Run program without any explicit stop during startup.  */
557     RUN_NORMAL,
558
559     /* Stop at the beginning of the program's main function.  */
560     RUN_STOP_AT_MAIN,
561
562     /* Stop at the first instruction of the program.  */
563     RUN_STOP_AT_FIRST_INSN
564   };
565
566 /* Implement the "run" command.  Force a stop during program start if
567    requested by RUN_HOW.  */
568
569 static void
570 run_command_1 (const char *args, int from_tty, enum run_how run_how)
571 {
572   const char *exec_file;
573   struct cleanup *old_chain;
574   ptid_t ptid;
575   struct ui_out *uiout = current_uiout;
576   struct target_ops *run_target;
577   int async_exec;
578   CORE_ADDR pc;
579
580   dont_repeat ();
581
582   kill_if_already_running (from_tty);
583
584   init_wait_for_inferior ();
585   clear_breakpoint_hit_counts ();
586
587   /* Clean up any leftovers from other runs.  Some other things from
588      this function should probably be moved into target_pre_inferior.  */
589   target_pre_inferior (from_tty);
590
591   /* The comment here used to read, "The exec file is re-read every
592      time we do a generic_mourn_inferior, so we just have to worry
593      about the symbol file."  The `generic_mourn_inferior' function
594      gets called whenever the program exits.  However, suppose the
595      program exits, and *then* the executable file changes?  We need
596      to check again here.  Since reopen_exec_file doesn't do anything
597      if the timestamp hasn't changed, I don't see the harm.  */
598   reopen_exec_file ();
599   reread_symbols ();
600
601   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (args, &async_exec);
602   args = stripped.get ();
603
604   /* Do validation and preparation before possibly changing anything
605      in the inferior.  */
606
607   run_target = find_run_target ();
608
609   prepare_execution_command (run_target, async_exec);
610
611   if (non_stop && !run_target->to_supports_non_stop (run_target))
612     error (_("The target does not support running in non-stop mode."));
613
614   /* Done.  Can now set breakpoints, change inferior args, etc.  */
615
616   /* Insert temporary breakpoint in main function if requested.  */
617   if (run_how == RUN_STOP_AT_MAIN)
618     tbreak_command (main_name (), 0);
619
620   exec_file = get_exec_file (0);
621
622   /* We keep symbols from add-symbol-file, on the grounds that the
623      user might want to add some symbols before running the program
624      (right?).  But sometimes (dynamic loading where the user manually
625      introduces the new symbols with add-symbol-file), the code which
626      the symbols describe does not persist between runs.  Currently
627      the user has to manually nuke all symbols between runs if they
628      want them to go away (PR 2207).  This is probably reasonable.  */
629
630   /* If there were other args, beside '&', process them.  */
631   if (args != NULL)
632     set_inferior_args (args);
633
634   if (from_tty)
635     {
636       uiout->field_string (NULL, "Starting program");
637       uiout->text (": ");
638       if (exec_file)
639         uiout->field_string ("execfile", exec_file);
640       uiout->spaces (1);
641       /* We call get_inferior_args() because we might need to compute
642          the value now.  */
643       uiout->field_string ("infargs", get_inferior_args ());
644       uiout->text ("\n");
645       uiout->flush ();
646     }
647
648   /* We call get_inferior_args() because we might need to compute
649      the value now.  */
650   run_target->to_create_inferior (run_target, exec_file,
651                                   std::string (get_inferior_args ()),
652                                   current_inferior ()->environment.envp (),
653                                   from_tty);
654   /* to_create_inferior should push the target, so after this point we
655      shouldn't refer to run_target again.  */
656   run_target = NULL;
657
658   /* We're starting off a new process.  When we get out of here, in
659      non-stop mode, finish the state of all threads of that process,
660      but leave other threads alone, as they may be stopped in internal
661      events --- the frontend shouldn't see them as stopped.  In
662      all-stop, always finish the state of all threads, as we may be
663      resuming more than just the new process.  */
664   if (non_stop)
665     ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
666   else
667     ptid = minus_one_ptid;
668   old_chain = make_cleanup (finish_thread_state_cleanup, &ptid);
669
670   /* Pass zero for FROM_TTY, because at this point the "run" command
671      has done its thing; now we are setting up the running program.  */
672   post_create_inferior (&current_target, 0);
673
674   /* Queue a pending event so that the program stops immediately.  */
675   if (run_how == RUN_STOP_AT_FIRST_INSN)
676     {
677       thread_info *thr = inferior_thread ();
678       thr->suspend.waitstatus_pending_p = 1;
679       thr->suspend.waitstatus.kind = TARGET_WAITKIND_STOPPED;
680       thr->suspend.waitstatus.value.sig = GDB_SIGNAL_0;
681     }
682
683   /* Start the target running.  Do not use -1 continuation as it would skip
684      breakpoint right at the entry point.  */
685   proceed (regcache_read_pc (get_current_regcache ()), GDB_SIGNAL_0);
686
687   /* Since there was no error, there's no need to finish the thread
688      states here.  */
689   discard_cleanups (old_chain);
690 }
691
692 static void
693 run_command (const char *args, int from_tty)
694 {
695   run_command_1 (args, from_tty, RUN_NORMAL);
696 }
697
698 /* Start the execution of the program up until the beginning of the main
699    program.  */
700
701 static void
702 start_command (const char *args, int from_tty)
703 {
704   /* Some languages such as Ada need to search inside the program
705      minimal symbols for the location where to put the temporary
706      breakpoint before starting.  */
707   if (!have_minimal_symbols ())
708     error (_("No symbol table loaded.  Use the \"file\" command."));
709
710   /* Run the program until reaching the main procedure...  */
711   run_command_1 (args, from_tty, RUN_STOP_AT_MAIN);
712 }
713
714 /* Start the execution of the program stopping at the first
715    instruction.  */
716
717 static void
718 starti_command (const char *args, int from_tty)
719 {
720   run_command_1 (args, from_tty, RUN_STOP_AT_FIRST_INSN);
721
722
723 static int
724 proceed_thread_callback (struct thread_info *thread, void *arg)
725 {
726   /* We go through all threads individually instead of compressing
727      into a single target `resume_all' request, because some threads
728      may be stopped in internal breakpoints/events, or stopped waiting
729      for its turn in the displaced stepping queue (that is, they are
730      running && !executing).  The target side has no idea about why
731      the thread is stopped, so a `resume_all' command would resume too
732      much.  If/when GDB gains a way to tell the target `hold this
733      thread stopped until I say otherwise', then we can optimize
734      this.  */
735   if (!is_stopped (thread->ptid))
736     return 0;
737
738   switch_to_thread (thread->ptid);
739   clear_proceed_status (0);
740   proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
741   return 0;
742 }
743
744 static void
745 ensure_valid_thread (void)
746 {
747   if (ptid_equal (inferior_ptid, null_ptid)
748       || is_exited (inferior_ptid))
749     error (_("Cannot execute this command without a live selected thread."));
750 }
751
752 /* If the user is looking at trace frames, any resumption of execution
753    is likely to mix up recorded and live target data.  So simply
754    disallow those commands.  */
755
756 static void
757 ensure_not_tfind_mode (void)
758 {
759   if (get_traceframe_number () >= 0)
760     error (_("Cannot execute this command while looking at trace frames."));
761 }
762
763 /* Throw an error indicating the current thread is running.  */
764
765 static void
766 error_is_running (void)
767 {
768   error (_("Cannot execute this command while "
769            "the selected thread is running."));
770 }
771
772 /* Calls error_is_running if the current thread is running.  */
773
774 static void
775 ensure_not_running (void)
776 {
777   if (is_running (inferior_ptid))
778     error_is_running ();
779 }
780
781 void
782 continue_1 (int all_threads)
783 {
784   ERROR_NO_INFERIOR;
785   ensure_not_tfind_mode ();
786
787   if (non_stop && all_threads)
788     {
789       /* Don't error out if the current thread is running, because
790          there may be other stopped threads.  */
791
792       /* Backup current thread and selected frame and restore on scope
793          exit.  */
794       scoped_restore_current_thread restore_thread;
795
796       iterate_over_threads (proceed_thread_callback, NULL);
797
798       if (current_ui->prompt_state == PROMPT_BLOCKED)
799         {
800           /* If all threads in the target were already running,
801              proceed_thread_callback ends up never calling proceed,
802              and so nothing calls this to put the inferior's terminal
803              settings in effect and remove stdin from the event loop,
804              which we must when running a foreground command.  E.g.:
805
806               (gdb) c -a&
807               Continuing.
808               <all threads are running now>
809               (gdb) c -a
810               Continuing.
811               <no thread was resumed, but the inferior now owns the terminal>
812           */
813           target_terminal::inferior ();
814         }
815     }
816   else
817     {
818       ensure_valid_thread ();
819       ensure_not_running ();
820       clear_proceed_status (0);
821       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
822     }
823 }
824
825 /* continue [-a] [proceed-count] [&]  */
826
827 static void
828 continue_command (const char *args, int from_tty)
829 {
830   int async_exec;
831   int all_threads = 0;
832
833   ERROR_NO_INFERIOR;
834
835   /* Find out whether we must run in the background.  */
836   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (args, &async_exec);
837   args = stripped.get ();
838
839   if (args != NULL)
840     {
841       if (startswith (args, "-a"))
842         {
843           all_threads = 1;
844           args += sizeof ("-a") - 1;
845           if (*args == '\0')
846             args = NULL;
847         }
848     }
849
850   if (!non_stop && all_threads)
851     error (_("`-a' is meaningless in all-stop mode."));
852
853   if (args != NULL && all_threads)
854     error (_("Can't resume all threads and specify "
855              "proceed count simultaneously."));
856
857   /* If we have an argument left, set proceed count of breakpoint we
858      stopped at.  */
859   if (args != NULL)
860     {
861       bpstat bs = NULL;
862       int num, stat;
863       int stopped = 0;
864       struct thread_info *tp;
865
866       if (non_stop)
867         tp = find_thread_ptid (inferior_ptid);
868       else
869         {
870           ptid_t last_ptid;
871           struct target_waitstatus ws;
872
873           get_last_target_status (&last_ptid, &ws);
874           tp = find_thread_ptid (last_ptid);
875         }
876       if (tp != NULL)
877         bs = tp->control.stop_bpstat;
878
879       while ((stat = bpstat_num (&bs, &num)) != 0)
880         if (stat > 0)
881           {
882             set_ignore_count (num,
883                               parse_and_eval_long (args) - 1,
884                               from_tty);
885             /* set_ignore_count prints a message ending with a period.
886                So print two spaces before "Continuing.".  */
887             if (from_tty)
888               printf_filtered ("  ");
889             stopped = 1;
890           }
891
892       if (!stopped && from_tty)
893         {
894           printf_filtered
895             ("Not stopped at any breakpoint; argument ignored.\n");
896         }
897     }
898
899   ERROR_NO_INFERIOR;
900   ensure_not_tfind_mode ();
901
902   if (!non_stop || !all_threads)
903     {
904       ensure_valid_thread ();
905       ensure_not_running ();
906     }
907
908   prepare_execution_command (&current_target, async_exec);
909
910   if (from_tty)
911     printf_filtered (_("Continuing.\n"));
912
913   continue_1 (all_threads);
914 }
915 \f
916 /* Record the starting point of a "step" or "next" command.  */
917
918 static void
919 set_step_frame (void)
920 {
921   frame_info *frame = get_current_frame ();
922
923   symtab_and_line sal = find_frame_sal (frame);
924   set_step_info (frame, sal);
925
926   CORE_ADDR pc = get_frame_pc (frame);
927   thread_info *tp = inferior_thread ();
928   tp->control.step_start_function = find_pc_function (pc);
929 }
930
931 /* Step until outside of current statement.  */
932
933 static void
934 step_command (const char *count_string, int from_tty)
935 {
936   step_1 (0, 0, count_string);
937 }
938
939 /* Likewise, but skip over subroutine calls as if single instructions.  */
940
941 static void
942 next_command (const char *count_string, int from_tty)
943 {
944   step_1 (1, 0, count_string);
945 }
946
947 /* Likewise, but step only one instruction.  */
948
949 static void
950 stepi_command (const char *count_string, int from_tty)
951 {
952   step_1 (0, 1, count_string);
953 }
954
955 static void
956 nexti_command (const char *count_string, int from_tty)
957 {
958   step_1 (1, 1, count_string);
959 }
960
961 void
962 delete_longjmp_breakpoint_cleanup (void *arg)
963 {
964   int thread = * (int *) arg;
965   delete_longjmp_breakpoint (thread);
966 }
967
968 /* Data for the FSM that manages the step/next/stepi/nexti
969    commands.  */
970
971 struct step_command_fsm
972 {
973   /* The base class.  */
974   struct thread_fsm thread_fsm;
975
976   /* How many steps left in a "step N"-like command.  */
977   int count;
978
979   /* If true, this is a next/nexti, otherwise a step/stepi.  */
980   int skip_subroutines;
981
982   /* If true, this is a stepi/nexti, otherwise a step/step.  */
983   int single_inst;
984 };
985
986 static void step_command_fsm_clean_up (struct thread_fsm *self,
987                                        struct thread_info *thread);
988 static int step_command_fsm_should_stop (struct thread_fsm *self,
989                                          struct thread_info *thread);
990 static enum async_reply_reason
991   step_command_fsm_async_reply_reason (struct thread_fsm *self);
992
993 /* step_command_fsm's vtable.  */
994
995 static struct thread_fsm_ops step_command_fsm_ops =
996 {
997   NULL,
998   step_command_fsm_clean_up,
999   step_command_fsm_should_stop,
1000   NULL, /* return_value */
1001   step_command_fsm_async_reply_reason,
1002 };
1003
1004 /* Allocate a new step_command_fsm.  */
1005
1006 static struct step_command_fsm *
1007 new_step_command_fsm (struct interp *cmd_interp)
1008 {
1009   struct step_command_fsm *sm;
1010
1011   sm = XCNEW (struct step_command_fsm);
1012   thread_fsm_ctor (&sm->thread_fsm, &step_command_fsm_ops, cmd_interp);
1013
1014   return sm;
1015 }
1016
1017 /* Prepare for a step/next/etc. command.  Any target resource
1018    allocated here is undone in the FSM's clean_up method.  */
1019
1020 static void
1021 step_command_fsm_prepare (struct step_command_fsm *sm,
1022                           int skip_subroutines, int single_inst,
1023                           int count, struct thread_info *thread)
1024 {
1025   sm->skip_subroutines = skip_subroutines;
1026   sm->single_inst = single_inst;
1027   sm->count = count;
1028
1029   /* Leave the si command alone.  */
1030   if (!sm->single_inst || sm->skip_subroutines)
1031     set_longjmp_breakpoint (thread, get_frame_id (get_current_frame ()));
1032
1033   thread->control.stepping_command = 1;
1034 }
1035
1036 static int prepare_one_step (struct step_command_fsm *sm);
1037
1038 static void
1039 step_1 (int skip_subroutines, int single_inst, const char *count_string)
1040 {
1041   int count;
1042   int async_exec;
1043   struct thread_info *thr;
1044   struct step_command_fsm *step_sm;
1045
1046   ERROR_NO_INFERIOR;
1047   ensure_not_tfind_mode ();
1048   ensure_valid_thread ();
1049   ensure_not_running ();
1050
1051   gdb::unique_xmalloc_ptr<char> stripped
1052     = strip_bg_char (count_string, &async_exec);
1053   count_string = stripped.get ();
1054
1055   prepare_execution_command (&current_target, async_exec);
1056
1057   count = count_string ? parse_and_eval_long (count_string) : 1;
1058
1059   clear_proceed_status (1);
1060
1061   /* Setup the execution command state machine to handle all the COUNT
1062      steps.  */
1063   thr = inferior_thread ();
1064   step_sm = new_step_command_fsm (command_interp ());
1065   thr->thread_fsm = &step_sm->thread_fsm;
1066
1067   step_command_fsm_prepare (step_sm, skip_subroutines,
1068                             single_inst, count, thr);
1069
1070   /* Do only one step for now, before returning control to the event
1071      loop.  Let the continuation figure out how many other steps we
1072      need to do, and handle them one at the time, through
1073      step_once.  */
1074   if (!prepare_one_step (step_sm))
1075     proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
1076   else
1077     {
1078       int proceeded;
1079
1080       /* Stepped into an inline frame.  Pretend that we've
1081          stopped.  */
1082       thread_fsm_clean_up (thr->thread_fsm, thr);
1083       proceeded = normal_stop ();
1084       if (!proceeded)
1085         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
1086       all_uis_check_sync_execution_done ();
1087     }
1088 }
1089
1090 /* Implementation of the 'should_stop' FSM method for stepping
1091    commands.  Called after we are done with one step operation, to
1092    check whether we need to step again, before we print the prompt and
1093    return control to the user.  If count is > 1, returns false, as we
1094    will need to keep going.  */
1095
1096 static int
1097 step_command_fsm_should_stop (struct thread_fsm *self, struct thread_info *tp)
1098 {
1099   struct step_command_fsm *sm = (struct step_command_fsm *) self;
1100
1101   if (tp->control.stop_step)
1102     {
1103       /* There are more steps to make, and we did stop due to
1104          ending a stepping range.  Do another step.  */
1105       if (--sm->count > 0)
1106         return prepare_one_step (sm);
1107
1108       thread_fsm_set_finished (self);
1109     }
1110
1111   return 1;
1112 }
1113
1114 /* Implementation of the 'clean_up' FSM method for stepping commands.  */
1115
1116 static void
1117 step_command_fsm_clean_up (struct thread_fsm *self, struct thread_info *thread)
1118 {
1119   struct step_command_fsm *sm = (struct step_command_fsm *) self;
1120
1121   if (!sm->single_inst || sm->skip_subroutines)
1122     delete_longjmp_breakpoint (thread->global_num);
1123 }
1124
1125 /* Implementation of the 'async_reply_reason' FSM method for stepping
1126    commands.  */
1127
1128 static enum async_reply_reason
1129 step_command_fsm_async_reply_reason (struct thread_fsm *self)
1130 {
1131   return EXEC_ASYNC_END_STEPPING_RANGE;
1132 }
1133
1134 /* Prepare for one step in "step N".  The actual target resumption is
1135    done by the caller.  Return true if we're done and should thus
1136    report a stop to the user.  Returns false if the target needs to be
1137    resumed.  */
1138
1139 static int
1140 prepare_one_step (struct step_command_fsm *sm)
1141 {
1142   if (sm->count > 0)
1143     {
1144       struct frame_info *frame = get_current_frame ();
1145
1146       /* Don't assume THREAD is a valid thread id.  It is set to -1 if
1147          the longjmp breakpoint was not required.  Use the
1148          INFERIOR_PTID thread instead, which is the same thread when
1149          THREAD is set.  */
1150       struct thread_info *tp = inferior_thread ();
1151
1152       set_step_frame ();
1153
1154       if (!sm->single_inst)
1155         {
1156           CORE_ADDR pc;
1157
1158           /* Step at an inlined function behaves like "down".  */
1159           if (!sm->skip_subroutines
1160               && inline_skipped_frames (inferior_ptid))
1161             {
1162               ptid_t resume_ptid;
1163
1164               /* Pretend that we've ran.  */
1165               resume_ptid = user_visible_resume_ptid (1);
1166               set_running (resume_ptid, 1);
1167
1168               step_into_inline_frame (inferior_ptid);
1169               sm->count--;
1170               return prepare_one_step (sm);
1171             }
1172
1173           pc = get_frame_pc (frame);
1174           find_pc_line_pc_range (pc,
1175                                  &tp->control.step_range_start,
1176                                  &tp->control.step_range_end);
1177
1178           tp->control.may_range_step = 1;
1179
1180           /* If we have no line info, switch to stepi mode.  */
1181           if (tp->control.step_range_end == 0 && step_stop_if_no_debug)
1182             {
1183               tp->control.step_range_start = tp->control.step_range_end = 1;
1184               tp->control.may_range_step = 0;
1185             }
1186           else if (tp->control.step_range_end == 0)
1187             {
1188               const char *name;
1189
1190               if (find_pc_partial_function (pc, &name,
1191                                             &tp->control.step_range_start,
1192                                             &tp->control.step_range_end) == 0)
1193                 error (_("Cannot find bounds of current function"));
1194
1195               target_terminal::ours_for_output ();
1196               printf_filtered (_("Single stepping until exit from function %s,"
1197                                  "\nwhich has no line number information.\n"),
1198                                name);
1199             }
1200         }
1201       else
1202         {
1203           /* Say we are stepping, but stop after one insn whatever it does.  */
1204           tp->control.step_range_start = tp->control.step_range_end = 1;
1205           if (!sm->skip_subroutines)
1206             /* It is stepi.
1207                Don't step over function calls, not even to functions lacking
1208                line numbers.  */
1209             tp->control.step_over_calls = STEP_OVER_NONE;
1210         }
1211
1212       if (sm->skip_subroutines)
1213         tp->control.step_over_calls = STEP_OVER_ALL;
1214
1215       return 0;
1216     }
1217
1218   /* Done.  */
1219   thread_fsm_set_finished (&sm->thread_fsm);
1220   return 1;
1221 }
1222
1223 \f
1224 /* Continue program at specified address.  */
1225
1226 static void
1227 jump_command (const char *arg, int from_tty)
1228 {
1229   struct gdbarch *gdbarch = get_current_arch ();
1230   CORE_ADDR addr;
1231   struct symbol *fn;
1232   struct symbol *sfn;
1233   int async_exec;
1234
1235   ERROR_NO_INFERIOR;
1236   ensure_not_tfind_mode ();
1237   ensure_valid_thread ();
1238   ensure_not_running ();
1239
1240   /* Find out whether we must run in the background.  */
1241   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (arg, &async_exec);
1242   arg = stripped.get ();
1243
1244   prepare_execution_command (&current_target, async_exec);
1245
1246   if (!arg)
1247     error_no_arg (_("starting address"));
1248
1249   std::vector<symtab_and_line> sals
1250     = decode_line_with_last_displayed (arg, DECODE_LINE_FUNFIRSTLINE);
1251   if (sals.size () != 1)
1252     error (_("Unreasonable jump request"));
1253
1254   symtab_and_line &sal = sals[0];
1255
1256   if (sal.symtab == 0 && sal.pc == 0)
1257     error (_("No source file has been specified."));
1258
1259   resolve_sal_pc (&sal);        /* May error out.  */
1260
1261   /* See if we are trying to jump to another function.  */
1262   fn = get_frame_function (get_current_frame ());
1263   sfn = find_pc_function (sal.pc);
1264   if (fn != NULL && sfn != fn)
1265     {
1266       if (!query (_("Line %d is not in `%s'.  Jump anyway? "), sal.line,
1267                   SYMBOL_PRINT_NAME (fn)))
1268         {
1269           error (_("Not confirmed."));
1270           /* NOTREACHED */
1271         }
1272     }
1273
1274   if (sfn != NULL)
1275     {
1276       struct obj_section *section;
1277
1278       fixup_symbol_section (sfn, 0);
1279       section = SYMBOL_OBJ_SECTION (symbol_objfile (sfn), sfn);
1280       if (section_is_overlay (section)
1281           && !section_is_mapped (section))
1282         {
1283           if (!query (_("WARNING!!!  Destination is in "
1284                         "unmapped overlay!  Jump anyway? ")))
1285             {
1286               error (_("Not confirmed."));
1287               /* NOTREACHED */
1288             }
1289         }
1290     }
1291
1292   addr = sal.pc;
1293
1294   if (from_tty)
1295     {
1296       printf_filtered (_("Continuing at "));
1297       fputs_filtered (paddress (gdbarch, addr), gdb_stdout);
1298       printf_filtered (".\n");
1299     }
1300
1301   clear_proceed_status (0);
1302   proceed (addr, GDB_SIGNAL_0);
1303 }
1304 \f
1305 /* Continue program giving it specified signal.  */
1306
1307 static void
1308 signal_command (const char *signum_exp, int from_tty)
1309 {
1310   enum gdb_signal oursig;
1311   int async_exec;
1312
1313   dont_repeat ();               /* Too dangerous.  */
1314   ERROR_NO_INFERIOR;
1315   ensure_not_tfind_mode ();
1316   ensure_valid_thread ();
1317   ensure_not_running ();
1318
1319   /* Find out whether we must run in the background.  */
1320   gdb::unique_xmalloc_ptr<char> stripped
1321     = strip_bg_char (signum_exp, &async_exec);
1322   signum_exp = stripped.get ();
1323
1324   prepare_execution_command (&current_target, async_exec);
1325
1326   if (!signum_exp)
1327     error_no_arg (_("signal number"));
1328
1329   /* It would be even slicker to make signal names be valid expressions,
1330      (the type could be "enum $signal" or some such), then the user could
1331      assign them to convenience variables.  */
1332   oursig = gdb_signal_from_name (signum_exp);
1333
1334   if (oursig == GDB_SIGNAL_UNKNOWN)
1335     {
1336       /* No, try numeric.  */
1337       int num = parse_and_eval_long (signum_exp);
1338
1339       if (num == 0)
1340         oursig = GDB_SIGNAL_0;
1341       else
1342         oursig = gdb_signal_from_command (num);
1343     }
1344
1345   /* Look for threads other than the current that this command ends up
1346      resuming too (due to schedlock off), and warn if they'll get a
1347      signal delivered.  "signal 0" is used to suppress a previous
1348      signal, but if the current thread is no longer the one that got
1349      the signal, then the user is potentially suppressing the signal
1350      of the wrong thread.  */
1351   if (!non_stop)
1352     {
1353       struct thread_info *tp;
1354       ptid_t resume_ptid;
1355       int must_confirm = 0;
1356
1357       /* This indicates what will be resumed.  Either a single thread,
1358          a whole process, or all threads of all processes.  */
1359       resume_ptid = user_visible_resume_ptid (0);
1360
1361       ALL_NON_EXITED_THREADS (tp)
1362         {
1363           if (ptid_equal (tp->ptid, inferior_ptid))
1364             continue;
1365           if (!ptid_match (tp->ptid, resume_ptid))
1366             continue;
1367
1368           if (tp->suspend.stop_signal != GDB_SIGNAL_0
1369               && signal_pass_state (tp->suspend.stop_signal))
1370             {
1371               if (!must_confirm)
1372                 printf_unfiltered (_("Note:\n"));
1373               printf_unfiltered (_("  Thread %s previously stopped with signal %s, %s.\n"),
1374                                  print_thread_id (tp),
1375                                  gdb_signal_to_name (tp->suspend.stop_signal),
1376                                  gdb_signal_to_string (tp->suspend.stop_signal));
1377               must_confirm = 1;
1378             }
1379         }
1380
1381       if (must_confirm
1382           && !query (_("Continuing thread %s (the current thread) with specified signal will\n"
1383                        "still deliver the signals noted above to their respective threads.\n"
1384                        "Continue anyway? "),
1385                      print_thread_id (inferior_thread ())))
1386         error (_("Not confirmed."));
1387     }
1388
1389   if (from_tty)
1390     {
1391       if (oursig == GDB_SIGNAL_0)
1392         printf_filtered (_("Continuing with no signal.\n"));
1393       else
1394         printf_filtered (_("Continuing with signal %s.\n"),
1395                          gdb_signal_to_name (oursig));
1396     }
1397
1398   clear_proceed_status (0);
1399   proceed ((CORE_ADDR) -1, oursig);
1400 }
1401
1402 /* Queue a signal to be delivered to the current thread.  */
1403
1404 static void
1405 queue_signal_command (const char *signum_exp, int from_tty)
1406 {
1407   enum gdb_signal oursig;
1408   struct thread_info *tp;
1409
1410   ERROR_NO_INFERIOR;
1411   ensure_not_tfind_mode ();
1412   ensure_valid_thread ();
1413   ensure_not_running ();
1414
1415   if (signum_exp == NULL)
1416     error_no_arg (_("signal number"));
1417
1418   /* It would be even slicker to make signal names be valid expressions,
1419      (the type could be "enum $signal" or some such), then the user could
1420      assign them to convenience variables.  */
1421   oursig = gdb_signal_from_name (signum_exp);
1422
1423   if (oursig == GDB_SIGNAL_UNKNOWN)
1424     {
1425       /* No, try numeric.  */
1426       int num = parse_and_eval_long (signum_exp);
1427
1428       if (num == 0)
1429         oursig = GDB_SIGNAL_0;
1430       else
1431         oursig = gdb_signal_from_command (num);
1432     }
1433
1434   if (oursig != GDB_SIGNAL_0
1435       && !signal_pass_state (oursig))
1436     error (_("Signal handling set to not pass this signal to the program."));
1437
1438   tp = inferior_thread ();
1439   tp->suspend.stop_signal = oursig;
1440 }
1441
1442 /* Data for the FSM that manages the until (with no argument)
1443    command.  */
1444
1445 struct until_next_fsm
1446 {
1447   /* The base class.  */
1448   struct thread_fsm thread_fsm;
1449
1450   /* The thread that as current when the command was executed.  */
1451   int thread;
1452 };
1453
1454 static int until_next_fsm_should_stop (struct thread_fsm *self,
1455                                        struct thread_info *thread);
1456 static void until_next_fsm_clean_up (struct thread_fsm *self,
1457                                      struct thread_info *thread);
1458 static enum async_reply_reason
1459   until_next_fsm_async_reply_reason (struct thread_fsm *self);
1460
1461 /* until_next_fsm's vtable.  */
1462
1463 static struct thread_fsm_ops until_next_fsm_ops =
1464 {
1465   NULL, /* dtor */
1466   until_next_fsm_clean_up,
1467   until_next_fsm_should_stop,
1468   NULL, /* return_value */
1469   until_next_fsm_async_reply_reason,
1470 };
1471
1472 /* Allocate a new until_next_fsm.  */
1473
1474 static struct until_next_fsm *
1475 new_until_next_fsm (struct interp *cmd_interp, int thread)
1476 {
1477   struct until_next_fsm *sm;
1478
1479   sm = XCNEW (struct until_next_fsm);
1480   thread_fsm_ctor (&sm->thread_fsm, &until_next_fsm_ops, cmd_interp);
1481
1482   sm->thread = thread;
1483
1484   return sm;
1485 }
1486
1487 /* Implementation of the 'should_stop' FSM method for the until (with
1488    no arg) command.  */
1489
1490 static int
1491 until_next_fsm_should_stop (struct thread_fsm *self,
1492                             struct thread_info *tp)
1493 {
1494   if (tp->control.stop_step)
1495     thread_fsm_set_finished (self);
1496
1497   return 1;
1498 }
1499
1500 /* Implementation of the 'clean_up' FSM method for the until (with no
1501    arg) command.  */
1502
1503 static void
1504 until_next_fsm_clean_up (struct thread_fsm *self, struct thread_info *thread)
1505 {
1506   struct until_next_fsm *sm = (struct until_next_fsm *) self;
1507
1508   delete_longjmp_breakpoint (thread->global_num);
1509 }
1510
1511 /* Implementation of the 'async_reply_reason' FSM method for the until
1512    (with no arg) command.  */
1513
1514 static enum async_reply_reason
1515 until_next_fsm_async_reply_reason (struct thread_fsm *self)
1516 {
1517   return EXEC_ASYNC_END_STEPPING_RANGE;
1518 }
1519
1520 /* Proceed until we reach a different source line with pc greater than
1521    our current one or exit the function.  We skip calls in both cases.
1522
1523    Note that eventually this command should probably be changed so
1524    that only source lines are printed out when we hit the breakpoint
1525    we set.  This may involve changes to wait_for_inferior and the
1526    proceed status code.  */
1527
1528 static void
1529 until_next_command (int from_tty)
1530 {
1531   struct frame_info *frame;
1532   CORE_ADDR pc;
1533   struct symbol *func;
1534   struct symtab_and_line sal;
1535   struct thread_info *tp = inferior_thread ();
1536   int thread = tp->global_num;
1537   struct cleanup *old_chain;
1538   struct until_next_fsm *sm;
1539
1540   clear_proceed_status (0);
1541   set_step_frame ();
1542
1543   frame = get_current_frame ();
1544
1545   /* Step until either exited from this function or greater
1546      than the current line (if in symbolic section) or pc (if
1547      not).  */
1548
1549   pc = get_frame_pc (frame);
1550   func = find_pc_function (pc);
1551
1552   if (!func)
1553     {
1554       struct bound_minimal_symbol msymbol = lookup_minimal_symbol_by_pc (pc);
1555
1556       if (msymbol.minsym == NULL)
1557         error (_("Execution is not within a known function."));
1558
1559       tp->control.step_range_start = BMSYMBOL_VALUE_ADDRESS (msymbol);
1560       /* The upper-bound of step_range is exclusive.  In order to make PC
1561          within the range, set the step_range_end with PC + 1.  */
1562       tp->control.step_range_end = pc + 1;
1563     }
1564   else
1565     {
1566       sal = find_pc_line (pc, 0);
1567
1568       tp->control.step_range_start = BLOCK_START (SYMBOL_BLOCK_VALUE (func));
1569       tp->control.step_range_end = sal.end;
1570     }
1571   tp->control.may_range_step = 1;
1572
1573   tp->control.step_over_calls = STEP_OVER_ALL;
1574
1575   set_longjmp_breakpoint (tp, get_frame_id (frame));
1576   old_chain = make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
1577
1578   sm = new_until_next_fsm (command_interp (), tp->global_num);
1579   tp->thread_fsm = &sm->thread_fsm;
1580   discard_cleanups (old_chain);
1581
1582   proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
1583 }
1584
1585 static void
1586 until_command (const char *arg, int from_tty)
1587 {
1588   int async_exec;
1589
1590   ERROR_NO_INFERIOR;
1591   ensure_not_tfind_mode ();
1592   ensure_valid_thread ();
1593   ensure_not_running ();
1594
1595   /* Find out whether we must run in the background.  */
1596   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (arg, &async_exec);
1597   arg = stripped.get ();
1598
1599   prepare_execution_command (&current_target, async_exec);
1600
1601   if (arg)
1602     until_break_command (arg, from_tty, 0);
1603   else
1604     until_next_command (from_tty);
1605 }
1606
1607 static void
1608 advance_command (const char *arg, int from_tty)
1609 {
1610   int async_exec;
1611
1612   ERROR_NO_INFERIOR;
1613   ensure_not_tfind_mode ();
1614   ensure_valid_thread ();
1615   ensure_not_running ();
1616
1617   if (arg == NULL)
1618     error_no_arg (_("a location"));
1619
1620   /* Find out whether we must run in the background.  */
1621   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (arg, &async_exec);
1622   arg = stripped.get ();
1623
1624   prepare_execution_command (&current_target, async_exec);
1625
1626   until_break_command (arg, from_tty, 1);
1627 }
1628 \f
1629 /* Return the value of the result of a function at the end of a 'finish'
1630    command/BP.  DTOR_DATA (if not NULL) can represent inferior registers
1631    right after an inferior call has finished.  */
1632
1633 struct value *
1634 get_return_value (struct value *function, struct type *value_type)
1635 {
1636   regcache stop_regs (regcache::readonly, *get_current_regcache ());
1637   struct gdbarch *gdbarch = stop_regs.arch ();
1638   struct value *value;
1639
1640   value_type = check_typedef (value_type);
1641   gdb_assert (TYPE_CODE (value_type) != TYPE_CODE_VOID);
1642
1643   /* FIXME: 2003-09-27: When returning from a nested inferior function
1644      call, it's possible (with no help from the architecture vector)
1645      to locate and return/print a "struct return" value.  This is just
1646      a more complicated case of what is already being done in the
1647      inferior function call code.  In fact, when inferior function
1648      calls are made async, this will likely be made the norm.  */
1649
1650   switch (gdbarch_return_value (gdbarch, function, value_type,
1651                                 NULL, NULL, NULL))
1652     {
1653     case RETURN_VALUE_REGISTER_CONVENTION:
1654     case RETURN_VALUE_ABI_RETURNS_ADDRESS:
1655     case RETURN_VALUE_ABI_PRESERVES_ADDRESS:
1656       value = allocate_value (value_type);
1657       gdbarch_return_value (gdbarch, function, value_type, &stop_regs,
1658                             value_contents_raw (value), NULL);
1659       break;
1660     case RETURN_VALUE_STRUCT_CONVENTION:
1661       value = NULL;
1662       break;
1663     default:
1664       internal_error (__FILE__, __LINE__, _("bad switch"));
1665     }
1666
1667   return value;
1668 }
1669
1670 /* The captured function return value/type and its position in the
1671    value history.  */
1672
1673 struct return_value_info
1674 {
1675   /* The captured return value.  May be NULL if we weren't able to
1676      retrieve it.  See get_return_value.  */
1677   struct value *value;
1678
1679   /* The return type.  In some cases, we'll not be able extract the
1680      return value, but we always know the type.  */
1681   struct type *type;
1682
1683   /* If we captured a value, this is the value history index.  */
1684   int value_history_index;
1685 };
1686
1687 /* Helper for print_return_value.  */
1688
1689 static void
1690 print_return_value_1 (struct ui_out *uiout, struct return_value_info *rv)
1691 {
1692   if (rv->value != NULL)
1693     {
1694       struct value_print_options opts;
1695
1696       /* Print it.  */
1697       uiout->text ("Value returned is ");
1698       uiout->field_fmt ("gdb-result-var", "$%d",
1699                          rv->value_history_index);
1700       uiout->text (" = ");
1701       get_no_prettyformat_print_options (&opts);
1702
1703       string_file stb;
1704
1705       value_print (rv->value, &stb, &opts);
1706       uiout->field_stream ("return-value", stb);
1707       uiout->text ("\n");
1708     }
1709   else
1710     {
1711       std::string type_name = type_to_string (rv->type);
1712       uiout->text ("Value returned has type: ");
1713       uiout->field_string ("return-type", type_name.c_str ());
1714       uiout->text (".");
1715       uiout->text (" Cannot determine contents\n");
1716     }
1717 }
1718
1719 /* Print the result of a function at the end of a 'finish' command.
1720    RV points at an object representing the captured return value/type
1721    and its position in the value history.  */
1722
1723 void
1724 print_return_value (struct ui_out *uiout, struct return_value_info *rv)
1725 {
1726   if (rv->type == NULL || TYPE_CODE (rv->type) == TYPE_CODE_VOID)
1727     return;
1728
1729   TRY
1730     {
1731       /* print_return_value_1 can throw an exception in some
1732          circumstances.  We need to catch this so that we still
1733          delete the breakpoint.  */
1734       print_return_value_1 (uiout, rv);
1735     }
1736   CATCH (ex, RETURN_MASK_ALL)
1737     {
1738       exception_print (gdb_stdout, ex);
1739     }
1740   END_CATCH
1741 }
1742
1743 /* Data for the FSM that manages the finish command.  */
1744
1745 struct finish_command_fsm
1746 {
1747   /* The base class.  */
1748   struct thread_fsm thread_fsm;
1749
1750   /* The momentary breakpoint set at the function's return address in
1751      the caller.  */
1752   struct breakpoint *breakpoint;
1753
1754   /* The function that we're stepping out of.  */
1755   struct symbol *function;
1756
1757   /* If the FSM finishes successfully, this stores the function's
1758      return value.  */
1759   struct return_value_info return_value;
1760 };
1761
1762 static int finish_command_fsm_should_stop (struct thread_fsm *self,
1763                                            struct thread_info *thread);
1764 static void finish_command_fsm_clean_up (struct thread_fsm *self,
1765                                          struct thread_info *thread);
1766 static struct return_value_info *
1767   finish_command_fsm_return_value (struct thread_fsm *self);
1768 static enum async_reply_reason
1769   finish_command_fsm_async_reply_reason (struct thread_fsm *self);
1770
1771 /* finish_command_fsm's vtable.  */
1772
1773 static struct thread_fsm_ops finish_command_fsm_ops =
1774 {
1775   NULL, /* dtor */
1776   finish_command_fsm_clean_up,
1777   finish_command_fsm_should_stop,
1778   finish_command_fsm_return_value,
1779   finish_command_fsm_async_reply_reason,
1780   NULL, /* should_notify_stop */
1781 };
1782
1783 /* Allocate a new finish_command_fsm.  */
1784
1785 static struct finish_command_fsm *
1786 new_finish_command_fsm (struct interp *cmd_interp)
1787 {
1788   struct finish_command_fsm *sm;
1789
1790   sm = XCNEW (struct finish_command_fsm);
1791   thread_fsm_ctor (&sm->thread_fsm, &finish_command_fsm_ops, cmd_interp);
1792
1793   return sm;
1794 }
1795
1796 /* Implementation of the 'should_stop' FSM method for the finish
1797    commands.  Detects whether the thread stepped out of the function
1798    successfully, and if so, captures the function's return value and
1799    marks the FSM finished.  */
1800
1801 static int
1802 finish_command_fsm_should_stop (struct thread_fsm *self,
1803                                 struct thread_info *tp)
1804 {
1805   struct finish_command_fsm *f = (struct finish_command_fsm *) self;
1806   struct return_value_info *rv = &f->return_value;
1807
1808   if (f->function != NULL
1809       && bpstat_find_breakpoint (tp->control.stop_bpstat,
1810                                  f->breakpoint) != NULL)
1811     {
1812       /* We're done.  */
1813       thread_fsm_set_finished (self);
1814
1815       rv->type = TYPE_TARGET_TYPE (SYMBOL_TYPE (f->function));
1816       if (rv->type == NULL)
1817         internal_error (__FILE__, __LINE__,
1818                         _("finish_command: function has no target type"));
1819
1820       if (TYPE_CODE (rv->type) != TYPE_CODE_VOID)
1821         {
1822           struct value *func;
1823
1824           func = read_var_value (f->function, NULL, get_current_frame ());
1825           rv->value = get_return_value (func, rv->type);
1826           if (rv->value != NULL)
1827             rv->value_history_index = record_latest_value (rv->value);
1828         }
1829     }
1830   else if (tp->control.stop_step)
1831     {
1832       /* Finishing from an inline frame, or reverse finishing.  In
1833          either case, there's no way to retrieve the return value.  */
1834       thread_fsm_set_finished (self);
1835     }
1836
1837   return 1;
1838 }
1839
1840 /* Implementation of the 'clean_up' FSM method for the finish
1841    commands.  */
1842
1843 static void
1844 finish_command_fsm_clean_up (struct thread_fsm *self,
1845                              struct thread_info *thread)
1846 {
1847   struct finish_command_fsm *f = (struct finish_command_fsm *) self;
1848
1849   if (f->breakpoint != NULL)
1850     {
1851       delete_breakpoint (f->breakpoint);
1852       f->breakpoint = NULL;
1853     }
1854   delete_longjmp_breakpoint (thread->global_num);
1855 }
1856
1857 /* Implementation of the 'return_value' FSM method for the finish
1858    commands.  */
1859
1860 static struct return_value_info *
1861 finish_command_fsm_return_value (struct thread_fsm *self)
1862 {
1863   struct finish_command_fsm *f = (struct finish_command_fsm *) self;
1864
1865   return &f->return_value;
1866 }
1867
1868 /* Implementation of the 'async_reply_reason' FSM method for the
1869    finish commands.  */
1870
1871 static enum async_reply_reason
1872 finish_command_fsm_async_reply_reason (struct thread_fsm *self)
1873 {
1874   if (execution_direction == EXEC_REVERSE)
1875     return EXEC_ASYNC_END_STEPPING_RANGE;
1876   else
1877     return EXEC_ASYNC_FUNCTION_FINISHED;
1878 }
1879
1880 /* finish_backward -- helper function for finish_command.  */
1881
1882 static void
1883 finish_backward (struct finish_command_fsm *sm)
1884 {
1885   struct symtab_and_line sal;
1886   struct thread_info *tp = inferior_thread ();
1887   CORE_ADDR pc;
1888   CORE_ADDR func_addr;
1889
1890   pc = get_frame_pc (get_current_frame ());
1891
1892   if (find_pc_partial_function (pc, NULL, &func_addr, NULL) == 0)
1893     error (_("Cannot find bounds of current function"));
1894
1895   sal = find_pc_line (func_addr, 0);
1896
1897   tp->control.proceed_to_finish = 1;
1898   /* Special case: if we're sitting at the function entry point,
1899      then all we need to do is take a reverse singlestep.  We
1900      don't need to set a breakpoint, and indeed it would do us
1901      no good to do so.
1902
1903      Note that this can only happen at frame #0, since there's
1904      no way that a function up the stack can have a return address
1905      that's equal to its entry point.  */
1906
1907   if (sal.pc != pc)
1908     {
1909       struct frame_info *frame = get_selected_frame (NULL);
1910       struct gdbarch *gdbarch = get_frame_arch (frame);
1911
1912       /* Set a step-resume at the function's entry point.  Once that's
1913          hit, we'll do one more step backwards.  */
1914       symtab_and_line sr_sal;
1915       sr_sal.pc = sal.pc;
1916       sr_sal.pspace = get_frame_program_space (frame);
1917       insert_step_resume_breakpoint_at_sal (gdbarch,
1918                                             sr_sal, null_frame_id);
1919
1920       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
1921     }
1922   else
1923     {
1924       /* We're almost there -- we just need to back up by one more
1925          single-step.  */
1926       tp->control.step_range_start = tp->control.step_range_end = 1;
1927       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
1928     }
1929 }
1930
1931 /* finish_forward -- helper function for finish_command.  FRAME is the
1932    frame that called the function we're about to step out of.  */
1933
1934 static void
1935 finish_forward (struct finish_command_fsm *sm, struct frame_info *frame)
1936 {
1937   struct frame_id frame_id = get_frame_id (frame);
1938   struct gdbarch *gdbarch = get_frame_arch (frame);
1939   struct symtab_and_line sal;
1940   struct thread_info *tp = inferior_thread ();
1941
1942   sal = find_pc_line (get_frame_pc (frame), 0);
1943   sal.pc = get_frame_pc (frame);
1944
1945   sm->breakpoint = set_momentary_breakpoint (gdbarch, sal,
1946                                              get_stack_frame_id (frame),
1947                                              bp_finish).release ();
1948
1949   /* set_momentary_breakpoint invalidates FRAME.  */
1950   frame = NULL;
1951
1952   set_longjmp_breakpoint (tp, frame_id);
1953
1954   /* We want to print return value, please...  */
1955   tp->control.proceed_to_finish = 1;
1956
1957   proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
1958 }
1959
1960 /* Skip frames for "finish".  */
1961
1962 static struct frame_info *
1963 skip_finish_frames (struct frame_info *frame)
1964 {
1965   struct frame_info *start;
1966
1967   do
1968     {
1969       start = frame;
1970
1971       frame = skip_tailcall_frames (frame);
1972       if (frame == NULL)
1973         break;
1974
1975       frame = skip_unwritable_frames (frame);
1976       if (frame == NULL)
1977         break;
1978     }
1979   while (start != frame);
1980
1981   return frame;
1982 }
1983
1984 /* "finish": Set a temporary breakpoint at the place the selected
1985    frame will return to, then continue.  */
1986
1987 static void
1988 finish_command (const char *arg, int from_tty)
1989 {
1990   struct frame_info *frame;
1991   int async_exec;
1992   struct finish_command_fsm *sm;
1993   struct thread_info *tp;
1994
1995   ERROR_NO_INFERIOR;
1996   ensure_not_tfind_mode ();
1997   ensure_valid_thread ();
1998   ensure_not_running ();
1999
2000   /* Find out whether we must run in the background.  */
2001   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (arg, &async_exec);
2002   arg = stripped.get ();
2003
2004   prepare_execution_command (&current_target, async_exec);
2005
2006   if (arg)
2007     error (_("The \"finish\" command does not take any arguments."));
2008
2009   frame = get_prev_frame (get_selected_frame (_("No selected frame.")));
2010   if (frame == 0)
2011     error (_("\"finish\" not meaningful in the outermost frame."));
2012
2013   clear_proceed_status (0);
2014
2015   tp = inferior_thread ();
2016
2017   sm = new_finish_command_fsm (command_interp ());
2018
2019   tp->thread_fsm = &sm->thread_fsm;
2020
2021   /* Finishing from an inline frame is completely different.  We don't
2022      try to show the "return value" - no way to locate it.  */
2023   if (get_frame_type (get_selected_frame (_("No selected frame.")))
2024       == INLINE_FRAME)
2025     {
2026       /* Claim we are stepping in the calling frame.  An empty step
2027          range means that we will stop once we aren't in a function
2028          called by that frame.  We don't use the magic "1" value for
2029          step_range_end, because then infrun will think this is nexti,
2030          and not step over the rest of this inlined function call.  */
2031       set_step_info (frame, {});
2032       tp->control.step_range_start = get_frame_pc (frame);
2033       tp->control.step_range_end = tp->control.step_range_start;
2034       tp->control.step_over_calls = STEP_OVER_ALL;
2035
2036       /* Print info on the selected frame, including level number but not
2037          source.  */
2038       if (from_tty)
2039         {
2040           printf_filtered (_("Run till exit from "));
2041           print_stack_frame (get_selected_frame (NULL), 1, LOCATION, 0);
2042         }
2043
2044       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
2045       return;
2046     }
2047
2048   /* Find the function we will return from.  */
2049
2050   sm->function = find_pc_function (get_frame_pc (get_selected_frame (NULL)));
2051
2052   /* Print info on the selected frame, including level number but not
2053      source.  */
2054   if (from_tty)
2055     {
2056       if (execution_direction == EXEC_REVERSE)
2057         printf_filtered (_("Run back to call of "));
2058       else
2059         {
2060           if (sm->function != NULL && TYPE_NO_RETURN (sm->function->type)
2061               && !query (_("warning: Function %s does not return normally.\n"
2062                            "Try to finish anyway? "),
2063                          SYMBOL_PRINT_NAME (sm->function)))
2064             error (_("Not confirmed."));
2065           printf_filtered (_("Run till exit from "));
2066         }
2067
2068       print_stack_frame (get_selected_frame (NULL), 1, LOCATION, 0);
2069     }
2070
2071   if (execution_direction == EXEC_REVERSE)
2072     finish_backward (sm);
2073   else
2074     {
2075       frame = skip_finish_frames (frame);
2076
2077       if (frame == NULL)
2078         error (_("Cannot find the caller frame."));
2079
2080       finish_forward (sm, frame);
2081     }
2082 }
2083 \f
2084
2085 static void
2086 info_program_command (char *args, int from_tty)
2087 {
2088   bpstat bs;
2089   int num, stat;
2090   struct thread_info *tp;
2091   ptid_t ptid;
2092
2093   if (!target_has_execution)
2094     {
2095       printf_filtered (_("The program being debugged is not being run.\n"));
2096       return;
2097     }
2098
2099   if (non_stop)
2100     ptid = inferior_ptid;
2101   else
2102     {
2103       struct target_waitstatus ws;
2104
2105       get_last_target_status (&ptid, &ws);
2106     }
2107
2108   if (ptid_equal (ptid, null_ptid) || is_exited (ptid))
2109     error (_("Invalid selected thread."));
2110   else if (is_running (ptid))
2111     error (_("Selected thread is running."));
2112
2113   tp = find_thread_ptid (ptid);
2114   bs = tp->control.stop_bpstat;
2115   stat = bpstat_num (&bs, &num);
2116
2117   target_files_info ();
2118   printf_filtered (_("Program stopped at %s.\n"),
2119                    paddress (target_gdbarch (), stop_pc));
2120   if (tp->control.stop_step)
2121     printf_filtered (_("It stopped after being stepped.\n"));
2122   else if (stat != 0)
2123     {
2124       /* There may be several breakpoints in the same place, so this
2125          isn't as strange as it seems.  */
2126       while (stat != 0)
2127         {
2128           if (stat < 0)
2129             {
2130               printf_filtered (_("It stopped at a breakpoint "
2131                                  "that has since been deleted.\n"));
2132             }
2133           else
2134             printf_filtered (_("It stopped at breakpoint %d.\n"), num);
2135           stat = bpstat_num (&bs, &num);
2136         }
2137     }
2138   else if (tp->suspend.stop_signal != GDB_SIGNAL_0)
2139     {
2140       printf_filtered (_("It stopped with signal %s, %s.\n"),
2141                        gdb_signal_to_name (tp->suspend.stop_signal),
2142                        gdb_signal_to_string (tp->suspend.stop_signal));
2143     }
2144
2145   if (from_tty)
2146     {
2147       printf_filtered (_("Type \"info stack\" or \"info "
2148                          "registers\" for more information.\n"));
2149     }
2150 }
2151 \f
2152 static void
2153 environment_info (const char *var, int from_tty)
2154 {
2155   if (var)
2156     {
2157       const char *val = current_inferior ()->environment.get (var);
2158
2159       if (val)
2160         {
2161           puts_filtered (var);
2162           puts_filtered (" = ");
2163           puts_filtered (val);
2164           puts_filtered ("\n");
2165         }
2166       else
2167         {
2168           puts_filtered ("Environment variable \"");
2169           puts_filtered (var);
2170           puts_filtered ("\" not defined.\n");
2171         }
2172     }
2173   else
2174     {
2175       char **envp = current_inferior ()->environment.envp ();
2176
2177       for (int idx = 0; envp[idx] != NULL; ++idx)
2178         {
2179           puts_filtered (envp[idx]);
2180           puts_filtered ("\n");
2181         }
2182     }
2183 }
2184
2185 static void
2186 set_environment_command (const char *arg, int from_tty)
2187 {
2188   const char *p, *val;
2189   int nullset = 0;
2190
2191   if (arg == 0)
2192     error_no_arg (_("environment variable and value"));
2193
2194   /* Find seperation between variable name and value.  */
2195   p = (char *) strchr (arg, '=');
2196   val = (char *) strchr (arg, ' ');
2197
2198   if (p != 0 && val != 0)
2199     {
2200       /* We have both a space and an equals.  If the space is before the
2201          equals, walk forward over the spaces til we see a nonspace 
2202          (possibly the equals).  */
2203       if (p > val)
2204         while (*val == ' ')
2205           val++;
2206
2207       /* Now if the = is after the char following the spaces,
2208          take the char following the spaces.  */
2209       if (p > val)
2210         p = val - 1;
2211     }
2212   else if (val != 0 && p == 0)
2213     p = val;
2214
2215   if (p == arg)
2216     error_no_arg (_("environment variable to set"));
2217
2218   if (p == 0 || p[1] == 0)
2219     {
2220       nullset = 1;
2221       if (p == 0)
2222         p = arg + strlen (arg); /* So that savestring below will work.  */
2223     }
2224   else
2225     {
2226       /* Not setting variable value to null.  */
2227       val = p + 1;
2228       while (*val == ' ' || *val == '\t')
2229         val++;
2230     }
2231
2232   while (p != arg && (p[-1] == ' ' || p[-1] == '\t'))
2233     p--;
2234
2235   std::string var (arg, p - arg);
2236   if (nullset)
2237     {
2238       printf_filtered (_("Setting environment variable "
2239                          "\"%s\" to null value.\n"),
2240                        var.c_str ());
2241       current_inferior ()->environment.set (var.c_str (), "");
2242     }
2243   else
2244     current_inferior ()->environment.set (var.c_str (), val);
2245 }
2246
2247 static void
2248 unset_environment_command (const char *var, int from_tty)
2249 {
2250   if (var == 0)
2251     {
2252       /* If there is no argument, delete all environment variables.
2253          Ask for confirmation if reading from the terminal.  */
2254       if (!from_tty || query (_("Delete all environment variables? ")))
2255         current_inferior ()->environment.clear ();
2256     }
2257   else
2258     current_inferior ()->environment.unset (var);
2259 }
2260
2261 /* Handle the execution path (PATH variable).  */
2262
2263 static const char path_var_name[] = "PATH";
2264
2265 static void
2266 path_info (const char *args, int from_tty)
2267 {
2268   puts_filtered ("Executable and object file path: ");
2269   puts_filtered (current_inferior ()->environment.get (path_var_name));
2270   puts_filtered ("\n");
2271 }
2272
2273 /* Add zero or more directories to the front of the execution path.  */
2274
2275 static void
2276 path_command (const char *dirname, int from_tty)
2277 {
2278   char *exec_path;
2279   const char *env;
2280
2281   dont_repeat ();
2282   env = current_inferior ()->environment.get (path_var_name);
2283   /* Can be null if path is not set.  */
2284   if (!env)
2285     env = "";
2286   exec_path = xstrdup (env);
2287   mod_path (dirname, &exec_path);
2288   current_inferior ()->environment.set (path_var_name, exec_path);
2289   xfree (exec_path);
2290   if (from_tty)
2291     path_info ((char *) NULL, from_tty);
2292 }
2293 \f
2294
2295 /* Print out the register NAME with value VAL, to FILE, in the default
2296    fashion.  */
2297
2298 static void
2299 default_print_one_register_info (struct ui_file *file,
2300                                  const char *name,
2301                                  struct value *val)
2302 {
2303   struct type *regtype = value_type (val);
2304   int print_raw_format;
2305
2306   fputs_filtered (name, file);
2307   print_spaces_filtered (15 - strlen (name), file);
2308
2309   print_raw_format = (value_entirely_available (val)
2310                       && !value_optimized_out (val));
2311
2312   /* If virtual format is floating, print it that way, and in raw
2313      hex.  */
2314   if (TYPE_CODE (regtype) == TYPE_CODE_FLT
2315       || TYPE_CODE (regtype) == TYPE_CODE_DECFLOAT)
2316     {
2317       struct value_print_options opts;
2318       const gdb_byte *valaddr = value_contents_for_printing (val);
2319       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (regtype));
2320
2321       get_user_print_options (&opts);
2322       opts.deref_ref = 1;
2323
2324       val_print (regtype,
2325                  value_embedded_offset (val), 0,
2326                  file, 0, val, &opts, current_language);
2327
2328       if (print_raw_format)
2329         {
2330           fprintf_filtered (file, "\t(raw ");
2331           print_hex_chars (file, valaddr, TYPE_LENGTH (regtype), byte_order,
2332                            true);
2333           fprintf_filtered (file, ")");
2334         }
2335     }
2336   else
2337     {
2338       struct value_print_options opts;
2339
2340       /* Print the register in hex.  */
2341       get_formatted_print_options (&opts, 'x');
2342       opts.deref_ref = 1;
2343       val_print (regtype,
2344                  value_embedded_offset (val), 0,
2345                  file, 0, val, &opts, current_language);
2346       /* If not a vector register, print it also according to its
2347          natural format.  */
2348       if (print_raw_format && TYPE_VECTOR (regtype) == 0)
2349         {
2350           get_user_print_options (&opts);
2351           opts.deref_ref = 1;
2352           fprintf_filtered (file, "\t");
2353           val_print (regtype,
2354                      value_embedded_offset (val), 0,
2355                      file, 0, val, &opts, current_language);
2356         }
2357     }
2358
2359   fprintf_filtered (file, "\n");
2360 }
2361
2362 /* Print out the machine register regnum.  If regnum is -1, print all
2363    registers (print_all == 1) or all non-float and non-vector
2364    registers (print_all == 0).
2365
2366    For most machines, having all_registers_info() print the
2367    register(s) one per line is good enough.  If a different format is
2368    required, (eg, for MIPS or Pyramid 90x, which both have lots of
2369    regs), or there is an existing convention for showing all the
2370    registers, define the architecture method PRINT_REGISTERS_INFO to
2371    provide that format.  */
2372
2373 void
2374 default_print_registers_info (struct gdbarch *gdbarch,
2375                               struct ui_file *file,
2376                               struct frame_info *frame,
2377                               int regnum, int print_all)
2378 {
2379   int i;
2380   const int numregs = gdbarch_num_regs (gdbarch)
2381                       + gdbarch_num_pseudo_regs (gdbarch);
2382
2383   for (i = 0; i < numregs; i++)
2384     {
2385       /* Decide between printing all regs, non-float / vector regs, or
2386          specific reg.  */
2387       if (regnum == -1)
2388         {
2389           if (print_all)
2390             {
2391               if (!gdbarch_register_reggroup_p (gdbarch, i, all_reggroup))
2392                 continue;
2393             }
2394           else
2395             {
2396               if (!gdbarch_register_reggroup_p (gdbarch, i, general_reggroup))
2397                 continue;
2398             }
2399         }
2400       else
2401         {
2402           if (i != regnum)
2403             continue;
2404         }
2405
2406       /* If the register name is empty, it is undefined for this
2407          processor, so don't display anything.  */
2408       if (gdbarch_register_name (gdbarch, i) == NULL
2409           || *(gdbarch_register_name (gdbarch, i)) == '\0')
2410         continue;
2411
2412       default_print_one_register_info (file,
2413                                        gdbarch_register_name (gdbarch, i),
2414                                        value_of_register (i, frame));
2415     }
2416 }
2417
2418 void
2419 registers_info (char *addr_exp, int fpregs)
2420 {
2421   struct frame_info *frame;
2422   struct gdbarch *gdbarch;
2423
2424   if (!target_has_registers)
2425     error (_("The program has no registers now."));
2426   frame = get_selected_frame (NULL);
2427   gdbarch = get_frame_arch (frame);
2428
2429   if (!addr_exp)
2430     {
2431       gdbarch_print_registers_info (gdbarch, gdb_stdout,
2432                                     frame, -1, fpregs);
2433       return;
2434     }
2435
2436   while (*addr_exp != '\0')
2437     {
2438       char *start;
2439       const char *end;
2440
2441       /* Skip leading white space.  */
2442       addr_exp = skip_spaces (addr_exp);
2443
2444       /* Discard any leading ``$''.  Check that there is something
2445          resembling a register following it.  */
2446       if (addr_exp[0] == '$')
2447         addr_exp++;
2448       if (isspace ((*addr_exp)) || (*addr_exp) == '\0')
2449         error (_("Missing register name"));
2450
2451       /* Find the start/end of this register name/num/group.  */
2452       start = addr_exp;
2453       while ((*addr_exp) != '\0' && !isspace ((*addr_exp)))
2454         addr_exp++;
2455       end = addr_exp;
2456
2457       /* Figure out what we've found and display it.  */
2458
2459       /* A register name?  */
2460       {
2461         int regnum = user_reg_map_name_to_regnum (gdbarch, start, end - start);
2462
2463         if (regnum >= 0)
2464           {
2465             /* User registers lie completely outside of the range of
2466                normal registers.  Catch them early so that the target
2467                never sees them.  */
2468             if (regnum >= gdbarch_num_regs (gdbarch)
2469                           + gdbarch_num_pseudo_regs (gdbarch))
2470               {
2471                 struct value *regval = value_of_user_reg (regnum, frame);
2472                 const char *regname = user_reg_map_regnum_to_name (gdbarch,
2473                                                                    regnum);
2474
2475                 /* Print in the same fashion
2476                    gdbarch_print_registers_info's default
2477                    implementation prints.  */
2478                 default_print_one_register_info (gdb_stdout,
2479                                                  regname,
2480                                                  regval);
2481               }
2482             else
2483               gdbarch_print_registers_info (gdbarch, gdb_stdout,
2484                                             frame, regnum, fpregs);
2485             continue;
2486           }
2487       }
2488
2489       /* A register group?  */
2490       {
2491         struct reggroup *group;
2492
2493         for (group = reggroup_next (gdbarch, NULL);
2494              group != NULL;
2495              group = reggroup_next (gdbarch, group))
2496           {
2497             /* Don't bother with a length check.  Should the user
2498                enter a short register group name, go with the first
2499                group that matches.  */
2500             if (strncmp (start, reggroup_name (group), end - start) == 0)
2501               break;
2502           }
2503         if (group != NULL)
2504           {
2505             int regnum;
2506
2507             for (regnum = 0;
2508                  regnum < gdbarch_num_regs (gdbarch)
2509                           + gdbarch_num_pseudo_regs (gdbarch);
2510                  regnum++)
2511               {
2512                 if (gdbarch_register_reggroup_p (gdbarch, regnum, group))
2513                   gdbarch_print_registers_info (gdbarch,
2514                                                 gdb_stdout, frame,
2515                                                 regnum, fpregs);
2516               }
2517             continue;
2518           }
2519       }
2520
2521       /* Nothing matched.  */
2522       error (_("Invalid register `%.*s'"), (int) (end - start), start);
2523     }
2524 }
2525
2526 static void
2527 info_all_registers_command (char *addr_exp, int from_tty)
2528 {
2529   registers_info (addr_exp, 1);
2530 }
2531
2532 static void
2533 info_registers_command (char *addr_exp, int from_tty)
2534 {
2535   registers_info (addr_exp, 0);
2536 }
2537
2538 static void
2539 print_vector_info (struct ui_file *file,
2540                    struct frame_info *frame, const char *args)
2541 {
2542   struct gdbarch *gdbarch = get_frame_arch (frame);
2543
2544   if (gdbarch_print_vector_info_p (gdbarch))
2545     gdbarch_print_vector_info (gdbarch, file, frame, args);
2546   else
2547     {
2548       int regnum;
2549       int printed_something = 0;
2550
2551       for (regnum = 0;
2552            regnum < gdbarch_num_regs (gdbarch)
2553                     + gdbarch_num_pseudo_regs (gdbarch);
2554            regnum++)
2555         {
2556           if (gdbarch_register_reggroup_p (gdbarch, regnum, vector_reggroup))
2557             {
2558               printed_something = 1;
2559               gdbarch_print_registers_info (gdbarch, file, frame, regnum, 1);
2560             }
2561         }
2562       if (!printed_something)
2563         fprintf_filtered (file, "No vector information\n");
2564     }
2565 }
2566
2567 static void
2568 info_vector_command (char *args, int from_tty)
2569 {
2570   if (!target_has_registers)
2571     error (_("The program has no registers now."));
2572
2573   print_vector_info (gdb_stdout, get_selected_frame (NULL), args);
2574 }
2575 \f
2576 /* Kill the inferior process.  Make us have no inferior.  */
2577
2578 static void
2579 kill_command (const char *arg, int from_tty)
2580 {
2581   /* FIXME:  This should not really be inferior_ptid (or target_has_execution).
2582      It should be a distinct flag that indicates that a target is active, cuz
2583      some targets don't have processes!  */
2584
2585   if (ptid_equal (inferior_ptid, null_ptid))
2586     error (_("The program is not being run."));
2587   if (!query (_("Kill the program being debugged? ")))
2588     error (_("Not confirmed."));
2589   target_kill ();
2590
2591   /* If we still have other inferiors to debug, then don't mess with
2592      with their threads.  */
2593   if (!have_inferiors ())
2594     {
2595       init_thread_list ();              /* Destroy thread info.  */
2596
2597       /* Killing off the inferior can leave us with a core file.  If
2598          so, print the state we are left in.  */
2599       if (target_has_stack)
2600         {
2601           printf_filtered (_("In %s,\n"), target_longname);
2602           print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
2603         }
2604     }
2605   bfd_cache_close_all ();
2606 }
2607
2608 /* Used in `attach&' command.  ARG is a point to an integer
2609    representing a process id.  Proceed threads of this process iff
2610    they stopped due to debugger request, and when they did, they
2611    reported a clean stop (GDB_SIGNAL_0).  Do not proceed threads
2612    that have been explicitly been told to stop.  */
2613
2614 static int
2615 proceed_after_attach_callback (struct thread_info *thread,
2616                                void *arg)
2617 {
2618   int pid = * (int *) arg;
2619
2620   if (ptid_get_pid (thread->ptid) == pid
2621       && !is_exited (thread->ptid)
2622       && !is_executing (thread->ptid)
2623       && !thread->stop_requested
2624       && thread->suspend.stop_signal == GDB_SIGNAL_0)
2625     {
2626       switch_to_thread (thread->ptid);
2627       clear_proceed_status (0);
2628       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
2629     }
2630
2631   return 0;
2632 }
2633
2634 static void
2635 proceed_after_attach (int pid)
2636 {
2637   /* Don't error out if the current thread is running, because
2638      there may be other stopped threads.  */
2639
2640   /* Backup current thread and selected frame.  */
2641   scoped_restore_current_thread restore_thread;
2642
2643   iterate_over_threads (proceed_after_attach_callback, &pid);
2644 }
2645
2646 /* See inferior.h.  */
2647
2648 void
2649 setup_inferior (int from_tty)
2650 {
2651   struct inferior *inferior;
2652
2653   inferior = current_inferior ();
2654   inferior->needs_setup = 0;
2655
2656   /* If no exec file is yet known, try to determine it from the
2657      process itself.  */
2658   if (get_exec_file (0) == NULL)
2659     exec_file_locate_attach (ptid_get_pid (inferior_ptid), 1, from_tty);
2660   else
2661     {
2662       reopen_exec_file ();
2663       reread_symbols ();
2664     }
2665
2666   /* Take any necessary post-attaching actions for this platform.  */
2667   target_post_attach (ptid_get_pid (inferior_ptid));
2668
2669   post_create_inferior (&current_target, from_tty);
2670 }
2671
2672 /* What to do after the first program stops after attaching.  */
2673 enum attach_post_wait_mode
2674 {
2675   /* Do nothing.  Leaves threads as they are.  */
2676   ATTACH_POST_WAIT_NOTHING,
2677
2678   /* Re-resume threads that are marked running.  */
2679   ATTACH_POST_WAIT_RESUME,
2680
2681   /* Stop all threads.  */
2682   ATTACH_POST_WAIT_STOP,
2683 };
2684
2685 /* Called after we've attached to a process and we've seen it stop for
2686    the first time.  If ASYNC_EXEC is true, re-resume threads that
2687    should be running.  Else if ATTACH, */
2688
2689 static void
2690 attach_post_wait (const char *args, int from_tty, enum attach_post_wait_mode mode)
2691 {
2692   struct inferior *inferior;
2693
2694   inferior = current_inferior ();
2695   inferior->control.stop_soon = NO_STOP_QUIETLY;
2696
2697   if (inferior->needs_setup)
2698     setup_inferior (from_tty);
2699
2700   if (mode == ATTACH_POST_WAIT_RESUME)
2701     {
2702       /* The user requested an `attach&', so be sure to leave threads
2703          that didn't get a signal running.  */
2704
2705       /* Immediatelly resume all suspended threads of this inferior,
2706          and this inferior only.  This should have no effect on
2707          already running threads.  If a thread has been stopped with a
2708          signal, leave it be.  */
2709       if (non_stop)
2710         proceed_after_attach (inferior->pid);
2711       else
2712         {
2713           if (inferior_thread ()->suspend.stop_signal == GDB_SIGNAL_0)
2714             {
2715               clear_proceed_status (0);
2716               proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
2717             }
2718         }
2719     }
2720   else if (mode == ATTACH_POST_WAIT_STOP)
2721     {
2722       /* The user requested a plain `attach', so be sure to leave
2723          the inferior stopped.  */
2724
2725       /* At least the current thread is already stopped.  */
2726
2727       /* In all-stop, by definition, all threads have to be already
2728          stopped at this point.  In non-stop, however, although the
2729          selected thread is stopped, others may still be executing.
2730          Be sure to explicitly stop all threads of the process.  This
2731          should have no effect on already stopped threads.  */
2732       if (non_stop)
2733         target_stop (pid_to_ptid (inferior->pid));
2734       else if (target_is_non_stop_p ())
2735         {
2736           struct thread_info *thread;
2737           struct thread_info *lowest = inferior_thread ();
2738           int pid = current_inferior ()->pid;
2739
2740           stop_all_threads ();
2741
2742           /* It's not defined which thread will report the attach
2743              stop.  For consistency, always select the thread with
2744              lowest GDB number, which should be the main thread, if it
2745              still exists.  */
2746           ALL_NON_EXITED_THREADS (thread)
2747             {
2748               if (ptid_get_pid (thread->ptid) == pid)
2749                 {
2750                   if (thread->inf->num < lowest->inf->num
2751                       || thread->per_inf_num < lowest->per_inf_num)
2752                     lowest = thread;
2753                 }
2754             }
2755
2756           switch_to_thread (lowest->ptid);
2757         }
2758
2759       /* Tell the user/frontend where we're stopped.  */
2760       normal_stop ();
2761       if (deprecated_attach_hook)
2762         deprecated_attach_hook ();
2763     }
2764 }
2765
2766 struct attach_command_continuation_args
2767 {
2768   char *args;
2769   int from_tty;
2770   enum attach_post_wait_mode mode;
2771 };
2772
2773 static void
2774 attach_command_continuation (void *args, int err)
2775 {
2776   struct attach_command_continuation_args *a
2777     = (struct attach_command_continuation_args *) args;
2778
2779   if (err)
2780     return;
2781
2782   attach_post_wait (a->args, a->from_tty, a->mode);
2783 }
2784
2785 static void
2786 attach_command_continuation_free_args (void *args)
2787 {
2788   struct attach_command_continuation_args *a
2789     = (struct attach_command_continuation_args *) args;
2790
2791   xfree (a->args);
2792   xfree (a);
2793 }
2794
2795 /* "attach" command entry point.  Takes a program started up outside
2796    of gdb and ``attaches'' to it.  This stops it cold in its tracks
2797    and allows us to start debugging it.  */
2798
2799 void
2800 attach_command (const char *args, int from_tty)
2801 {
2802   int async_exec;
2803   struct target_ops *attach_target;
2804   struct inferior *inferior = current_inferior ();
2805   enum attach_post_wait_mode mode;
2806
2807   dont_repeat ();               /* Not for the faint of heart */
2808
2809   if (gdbarch_has_global_solist (target_gdbarch ()))
2810     /* Don't complain if all processes share the same symbol
2811        space.  */
2812     ;
2813   else if (target_has_execution)
2814     {
2815       if (query (_("A program is being debugged already.  Kill it? ")))
2816         target_kill ();
2817       else
2818         error (_("Not killed."));
2819     }
2820
2821   /* Clean up any leftovers from other runs.  Some other things from
2822      this function should probably be moved into target_pre_inferior.  */
2823   target_pre_inferior (from_tty);
2824
2825   gdb::unique_xmalloc_ptr<char> stripped = strip_bg_char (args, &async_exec);
2826   args = stripped.get ();
2827
2828   attach_target = find_attach_target ();
2829
2830   prepare_execution_command (attach_target, async_exec);
2831
2832   if (non_stop && !attach_target->to_supports_non_stop (attach_target))
2833     error (_("Cannot attach to this target in non-stop mode"));
2834
2835   attach_target->to_attach (attach_target, args, from_tty);
2836   /* to_attach should push the target, so after this point we
2837      shouldn't refer to attach_target again.  */
2838   attach_target = NULL;
2839
2840   /* Set up the "saved terminal modes" of the inferior
2841      based on what modes we are starting it with.  */
2842   target_terminal::init ();
2843
2844   /* Install inferior's terminal modes.  This may look like a no-op,
2845      as we've just saved them above, however, this does more than
2846      restore terminal settings:
2847
2848      - installs a SIGINT handler that forwards SIGINT to the inferior.
2849        Otherwise a Ctrl-C pressed just while waiting for the initial
2850        stop would end up as a spurious Quit.
2851
2852      - removes stdin from the event loop, which we need if attaching
2853        in the foreground, otherwise on targets that report an initial
2854        stop on attach (which are most) we'd process input/commands
2855        while we're in the event loop waiting for that stop.  That is,
2856        before the attach continuation runs and the command is really
2857        finished.  */
2858   target_terminal::inferior ();
2859
2860   /* Set up execution context to know that we should return from
2861      wait_for_inferior as soon as the target reports a stop.  */
2862   init_wait_for_inferior ();
2863   clear_proceed_status (0);
2864
2865   inferior->needs_setup = 1;
2866
2867   if (target_is_non_stop_p ())
2868     {
2869       /* If we find that the current thread isn't stopped, explicitly
2870          do so now, because we're going to install breakpoints and
2871          poke at memory.  */
2872
2873       if (async_exec)
2874         /* The user requested an `attach&'; stop just one thread.  */
2875         target_stop (inferior_ptid);
2876       else
2877         /* The user requested an `attach', so stop all threads of this
2878            inferior.  */
2879         target_stop (pid_to_ptid (ptid_get_pid (inferior_ptid)));
2880     }
2881
2882   mode = async_exec ? ATTACH_POST_WAIT_RESUME : ATTACH_POST_WAIT_STOP;
2883
2884   /* Some system don't generate traps when attaching to inferior.
2885      E.g. Mach 3 or GNU hurd.  */
2886   if (!target_attach_no_wait)
2887     {
2888       struct attach_command_continuation_args *a;
2889
2890       /* Careful here.  See comments in inferior.h.  Basically some
2891          OSes don't ignore SIGSTOPs on continue requests anymore.  We
2892          need a way for handle_inferior_event to reset the stop_signal
2893          variable after an attach, and this is what
2894          STOP_QUIETLY_NO_SIGSTOP is for.  */
2895       inferior->control.stop_soon = STOP_QUIETLY_NO_SIGSTOP;
2896
2897       /* Wait for stop.  */
2898       a = XNEW (struct attach_command_continuation_args);
2899       a->args = xstrdup (args);
2900       a->from_tty = from_tty;
2901       a->mode = mode;
2902       add_inferior_continuation (attach_command_continuation, a,
2903                                  attach_command_continuation_free_args);
2904
2905       if (!target_is_async_p ())
2906         mark_infrun_async_event_handler ();
2907       return;
2908     }
2909
2910   attach_post_wait (args, from_tty, mode);
2911 }
2912
2913 /* We had just found out that the target was already attached to an
2914    inferior.  PTID points at a thread of this new inferior, that is
2915    the most likely to be stopped right now, but not necessarily so.
2916    The new inferior is assumed to be already added to the inferior
2917    list at this point.  If LEAVE_RUNNING, then leave the threads of
2918    this inferior running, except those we've explicitly seen reported
2919    as stopped.  */
2920
2921 void
2922 notice_new_inferior (ptid_t ptid, int leave_running, int from_tty)
2923 {
2924   enum attach_post_wait_mode mode
2925     = leave_running ? ATTACH_POST_WAIT_RESUME : ATTACH_POST_WAIT_NOTHING;
2926
2927   gdb::optional<scoped_restore_current_thread> restore_thread;
2928
2929   if (inferior_ptid != null_ptid)
2930     restore_thread.emplace ();
2931
2932   /* Avoid reading registers -- we haven't fetched the target
2933      description yet.  */
2934   switch_to_thread_no_regs (find_thread_ptid (ptid));
2935
2936   /* When we "notice" a new inferior we need to do all the things we
2937      would normally do if we had just attached to it.  */
2938
2939   if (is_executing (inferior_ptid))
2940     {
2941       struct attach_command_continuation_args *a;
2942       struct inferior *inferior = current_inferior ();
2943
2944       /* We're going to install breakpoints, and poke at memory,
2945          ensure that the inferior is stopped for a moment while we do
2946          that.  */
2947       target_stop (inferior_ptid);
2948
2949       inferior->control.stop_soon = STOP_QUIETLY_REMOTE;
2950
2951       /* Wait for stop before proceeding.  */
2952       a = XNEW (struct attach_command_continuation_args);
2953       a->args = xstrdup ("");
2954       a->from_tty = from_tty;
2955       a->mode = mode;
2956       add_inferior_continuation (attach_command_continuation, a,
2957                                  attach_command_continuation_free_args);
2958
2959       return;
2960     }
2961
2962   attach_post_wait ("" /* args */, from_tty, mode);
2963 }
2964
2965 /*
2966  * detach_command --
2967  * takes a program previously attached to and detaches it.
2968  * The program resumes execution and will no longer stop
2969  * on signals, etc.  We better not have left any breakpoints
2970  * in the program or it'll die when it hits one.  For this
2971  * to work, it may be necessary for the process to have been
2972  * previously attached.  It *might* work if the program was
2973  * started via the normal ptrace (PTRACE_TRACEME).
2974  */
2975
2976 void
2977 detach_command (const char *args, int from_tty)
2978 {
2979   dont_repeat ();               /* Not for the faint of heart.  */
2980
2981   if (ptid_equal (inferior_ptid, null_ptid))
2982     error (_("The program is not being run."));
2983
2984   query_if_trace_running (from_tty);
2985
2986   disconnect_tracing ();
2987
2988   target_detach (args, from_tty);
2989
2990   /* The current inferior process was just detached successfully.  Get
2991      rid of breakpoints that no longer make sense.  Note we don't do
2992      this within target_detach because that is also used when
2993      following child forks, and in that case we will want to transfer
2994      breakpoints to the child, not delete them.  */
2995   breakpoint_init_inferior (inf_exited);
2996
2997   /* If the solist is global across inferiors, don't clear it when we
2998      detach from a single inferior.  */
2999   if (!gdbarch_has_global_solist (target_gdbarch ()))
3000     no_shared_libraries (NULL, from_tty);
3001
3002   /* If we still have inferiors to debug, then don't mess with their
3003      threads.  */
3004   if (!have_inferiors ())
3005     init_thread_list ();
3006
3007   if (deprecated_detach_hook)
3008     deprecated_detach_hook ();
3009 }
3010
3011 /* Disconnect from the current target without resuming it (leaving it
3012    waiting for a debugger).
3013
3014    We'd better not have left any breakpoints in the program or the
3015    next debugger will get confused.  Currently only supported for some
3016    remote targets, since the normal attach mechanisms don't work on
3017    stopped processes on some native platforms (e.g. GNU/Linux).  */
3018
3019 static void
3020 disconnect_command (const char *args, int from_tty)
3021 {
3022   dont_repeat ();               /* Not for the faint of heart.  */
3023   query_if_trace_running (from_tty);
3024   disconnect_tracing ();
3025   target_disconnect (args, from_tty);
3026   no_shared_libraries (NULL, from_tty);
3027   init_thread_list ();
3028   if (deprecated_detach_hook)
3029     deprecated_detach_hook ();
3030 }
3031
3032 void 
3033 interrupt_target_1 (int all_threads)
3034 {
3035   ptid_t ptid;
3036
3037   if (all_threads)
3038     ptid = minus_one_ptid;
3039   else
3040     ptid = inferior_ptid;
3041
3042   if (non_stop)
3043     target_stop (ptid);
3044   else
3045     target_interrupt (ptid);
3046
3047   /* Tag the thread as having been explicitly requested to stop, so
3048      other parts of gdb know not to resume this thread automatically,
3049      if it was stopped due to an internal event.  Limit this to
3050      non-stop mode, as when debugging a multi-threaded application in
3051      all-stop mode, we will only get one stop event --- it's undefined
3052      which thread will report the event.  */
3053   if (non_stop)
3054     set_stop_requested (ptid, 1);
3055 }
3056
3057 /* interrupt [-a]
3058    Stop the execution of the target while running in async mode, in
3059    the background.  In all-stop, stop the whole process.  In non-stop
3060    mode, stop the current thread only by default, or stop all threads
3061    if the `-a' switch is used.  */
3062
3063 static void
3064 interrupt_command (const char *args, int from_tty)
3065 {
3066   if (target_can_async_p ())
3067     {
3068       int all_threads = 0;
3069
3070       dont_repeat ();           /* Not for the faint of heart.  */
3071
3072       if (args != NULL
3073           && startswith (args, "-a"))
3074         all_threads = 1;
3075
3076       if (!non_stop && all_threads)
3077         error (_("-a is meaningless in all-stop mode."));
3078
3079       interrupt_target_1 (all_threads);
3080     }
3081 }
3082
3083 /* See inferior.h.  */
3084
3085 void
3086 default_print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
3087                           struct frame_info *frame, const char *args)
3088 {
3089   int regnum;
3090   int printed_something = 0;
3091
3092   for (regnum = 0;
3093        regnum < gdbarch_num_regs (gdbarch)
3094          + gdbarch_num_pseudo_regs (gdbarch);
3095        regnum++)
3096     {
3097       if (gdbarch_register_reggroup_p (gdbarch, regnum, float_reggroup))
3098         {
3099           printed_something = 1;
3100           gdbarch_print_registers_info (gdbarch, file, frame, regnum, 1);
3101         }
3102     }
3103   if (!printed_something)
3104     fprintf_filtered (file, "No floating-point info "
3105                       "available for this processor.\n");
3106 }
3107
3108 static void
3109 info_float_command (char *args, int from_tty)
3110 {
3111   struct frame_info *frame;
3112
3113   if (!target_has_registers)
3114     error (_("The program has no registers now."));
3115
3116   frame = get_selected_frame (NULL);
3117   gdbarch_print_float_info (get_frame_arch (frame), gdb_stdout, frame, args);
3118 }
3119 \f
3120 static void
3121 unset_command (const char *args, int from_tty)
3122 {
3123   printf_filtered (_("\"unset\" must be followed by the "
3124                      "name of an unset subcommand.\n"));
3125   help_list (unsetlist, "unset ", all_commands, gdb_stdout);
3126 }
3127
3128 /* Implement `info proc' family of commands.  */
3129
3130 static void
3131 info_proc_cmd_1 (const char *args, enum info_proc_what what, int from_tty)
3132 {
3133   struct gdbarch *gdbarch = get_current_arch ();
3134
3135   if (!target_info_proc (args, what))
3136     {
3137       if (gdbarch_info_proc_p (gdbarch))
3138         gdbarch_info_proc (gdbarch, args, what);
3139       else
3140         error (_("Not supported on this target."));
3141     }
3142 }
3143
3144 /* Implement `info proc' when given without any futher parameters.  */
3145
3146 static void
3147 info_proc_cmd (const char *args, int from_tty)
3148 {
3149   info_proc_cmd_1 (args, IP_MINIMAL, from_tty);
3150 }
3151
3152 /* Implement `info proc mappings'.  */
3153
3154 static void
3155 info_proc_cmd_mappings (const char *args, int from_tty)
3156 {
3157   info_proc_cmd_1 (args, IP_MAPPINGS, from_tty);
3158 }
3159
3160 /* Implement `info proc stat'.  */
3161
3162 static void
3163 info_proc_cmd_stat (const char *args, int from_tty)
3164 {
3165   info_proc_cmd_1 (args, IP_STAT, from_tty);
3166 }
3167
3168 /* Implement `info proc status'.  */
3169
3170 static void
3171 info_proc_cmd_status (const char *args, int from_tty)
3172 {
3173   info_proc_cmd_1 (args, IP_STATUS, from_tty);
3174 }
3175
3176 /* Implement `info proc cwd'.  */
3177
3178 static void
3179 info_proc_cmd_cwd (const char *args, int from_tty)
3180 {
3181   info_proc_cmd_1 (args, IP_CWD, from_tty);
3182 }
3183
3184 /* Implement `info proc cmdline'.  */
3185
3186 static void
3187 info_proc_cmd_cmdline (const char *args, int from_tty)
3188 {
3189   info_proc_cmd_1 (args, IP_CMDLINE, from_tty);
3190 }
3191
3192 /* Implement `info proc exe'.  */
3193
3194 static void
3195 info_proc_cmd_exe (const char *args, int from_tty)
3196 {
3197   info_proc_cmd_1 (args, IP_EXE, from_tty);
3198 }
3199
3200 /* Implement `info proc all'.  */
3201
3202 static void
3203 info_proc_cmd_all (const char *args, int from_tty)
3204 {
3205   info_proc_cmd_1 (args, IP_ALL, from_tty);
3206 }
3207
3208 /* This help string is used for the run, start, and starti commands.
3209    It is defined as a macro to prevent duplication.  */
3210
3211 #define RUN_ARGS_HELP \
3212 "You may specify arguments to give it.\n\
3213 Args may include \"*\", or \"[...]\"; they are expanded using the\n\
3214 shell that will start the program (specified by the \"$SHELL\" environment\n\
3215 variable).  Input and output redirection with \">\", \"<\", or \">>\"\n\
3216 are also allowed.\n\
3217 \n\
3218 With no arguments, uses arguments last specified (with \"run\" or \n\
3219 \"set args\").  To cancel previous arguments and run with no arguments,\n\
3220 use \"set args\" without arguments.\n\
3221 \n\
3222 To start the inferior without using a shell, use \"set startup-with-shell off\"."
3223
3224 void
3225 _initialize_infcmd (void)
3226 {
3227   static struct cmd_list_element *info_proc_cmdlist;
3228   struct cmd_list_element *c = NULL;
3229   const char *cmd_name;
3230
3231   /* Add the filename of the terminal connected to inferior I/O.  */
3232   add_setshow_optional_filename_cmd ("inferior-tty", class_run,
3233                                      &inferior_io_terminal_scratch, _("\
3234 Set terminal for future runs of program being debugged."), _("\
3235 Show terminal for future runs of program being debugged."), _("\
3236 Usage: set inferior-tty [TTY]\n\n\
3237 If TTY is omitted, the default behavior of using the same terminal as GDB\n\
3238 is restored."),
3239                                      set_inferior_tty_command,
3240                                      show_inferior_tty_command,
3241                                      &setlist, &showlist);
3242   cmd_name = "inferior-tty";
3243   c = lookup_cmd (&cmd_name, setlist, "", -1, 1);
3244   gdb_assert (c != NULL);
3245   add_alias_cmd ("tty", c, class_alias, 0, &cmdlist);
3246
3247   cmd_name = "args";
3248   add_setshow_string_noescape_cmd (cmd_name, class_run,
3249                                    &inferior_args_scratch, _("\
3250 Set argument list to give program being debugged when it is started."), _("\
3251 Show argument list to give program being debugged when it is started."), _("\
3252 Follow this command with any number of args, to be passed to the program."),
3253                                    set_args_command,
3254                                    show_args_command,
3255                                    &setlist, &showlist);
3256   c = lookup_cmd (&cmd_name, setlist, "", -1, 1);
3257   gdb_assert (c != NULL);
3258   set_cmd_completer (c, filename_completer);
3259
3260   cmd_name = "cwd";
3261   add_setshow_string_noescape_cmd (cmd_name, class_run,
3262                                    &inferior_cwd_scratch, _("\
3263 Set the current working directory to be used when the inferior is started.\n\
3264 Changing this setting does not have any effect on inferiors that are\n\
3265 already running."),
3266                                    _("\
3267 Show the current working directory that is used when the inferior is started."),
3268                                    _("\
3269 Use this command to change the current working directory that will be used\n\
3270 when the inferior is started.  This setting does not affect GDB's current\n\
3271 working directory."),
3272                                    set_cwd_command,
3273                                    show_cwd_command,
3274                                    &setlist, &showlist);
3275   c = lookup_cmd (&cmd_name, setlist, "", -1, 1);
3276   gdb_assert (c != NULL);
3277   set_cmd_completer (c, filename_completer);
3278
3279   c = add_cmd ("environment", no_class, environment_info, _("\
3280 The environment to give the program, or one variable's value.\n\
3281 With an argument VAR, prints the value of environment variable VAR to\n\
3282 give the program being debugged.  With no arguments, prints the entire\n\
3283 environment to be given to the program."), &showlist);
3284   set_cmd_completer (c, noop_completer);
3285
3286   add_prefix_cmd ("unset", no_class, unset_command,
3287                   _("Complement to certain \"set\" commands."),
3288                   &unsetlist, "unset ", 0, &cmdlist);
3289
3290   c = add_cmd ("environment", class_run, unset_environment_command, _("\
3291 Cancel environment variable VAR for the program.\n\
3292 This does not affect the program until the next \"run\" command."),
3293                &unsetlist);
3294   set_cmd_completer (c, noop_completer);
3295
3296   c = add_cmd ("environment", class_run, set_environment_command, _("\
3297 Set environment variable value to give the program.\n\
3298 Arguments are VAR VALUE where VAR is variable name and VALUE is value.\n\
3299 VALUES of environment variables are uninterpreted strings.\n\
3300 This does not affect the program until the next \"run\" command."),
3301                &setlist);
3302   set_cmd_completer (c, noop_completer);
3303
3304   c = add_com ("path", class_files, path_command, _("\
3305 Add directory DIR(s) to beginning of search path for object files.\n\
3306 $cwd in the path means the current working directory.\n\
3307 This path is equivalent to the $PATH shell variable.  It is a list of\n\
3308 directories, separated by colons.  These directories are searched to find\n\
3309 fully linked executable files and separately compiled object files as \
3310 needed."));
3311   set_cmd_completer (c, filename_completer);
3312
3313   c = add_cmd ("paths", no_class, path_info, _("\
3314 Current search path for finding object files.\n\
3315 $cwd in the path means the current working directory.\n\
3316 This path is equivalent to the $PATH shell variable.  It is a list of\n\
3317 directories, separated by colons.  These directories are searched to find\n\
3318 fully linked executable files and separately compiled object files as \
3319 needed."),
3320                &showlist);
3321   set_cmd_completer (c, noop_completer);
3322
3323   add_prefix_cmd ("kill", class_run, kill_command,
3324                   _("Kill execution of program being debugged."),
3325                   &killlist, "kill ", 0, &cmdlist);
3326
3327   add_com ("attach", class_run, attach_command, _("\
3328 Attach to a process or file outside of GDB.\n\
3329 This command attaches to another target, of the same type as your last\n\
3330 \"target\" command (\"info files\" will show your target stack).\n\
3331 The command may take as argument a process id or a device file.\n\
3332 For a process id, you must have permission to send the process a signal,\n\
3333 and it must have the same effective uid as the debugger.\n\
3334 When using \"attach\" with a process id, the debugger finds the\n\
3335 program running in the process, looking first in the current working\n\
3336 directory, or (if not found there) using the source file search path\n\
3337 (see the \"directory\" command).  You can also use the \"file\" command\n\
3338 to specify the program, and to load its symbol table."));
3339
3340   add_prefix_cmd ("detach", class_run, detach_command, _("\
3341 Detach a process or file previously attached.\n\
3342 If a process, it is no longer traced, and it continues its execution.  If\n\
3343 you were debugging a file, the file is closed and gdb no longer accesses it."),
3344                   &detachlist, "detach ", 0, &cmdlist);
3345
3346   add_com ("disconnect", class_run, disconnect_command, _("\
3347 Disconnect from a target.\n\
3348 The target will wait for another debugger to connect.  Not available for\n\
3349 all targets."));
3350
3351   c = add_com ("signal", class_run, signal_command, _("\
3352 Continue program with the specified signal.\n\
3353 Usage: signal SIGNAL\n\
3354 The SIGNAL argument is processed the same as the handle command.\n\
3355 \n\
3356 An argument of \"0\" means continue the program without sending it a signal.\n\
3357 This is useful in cases where the program stopped because of a signal,\n\
3358 and you want to resume the program while discarding the signal.\n\
3359 \n\
3360 In a multi-threaded program the signal is delivered to, or discarded from,\n\
3361 the current thread only."));
3362   set_cmd_completer (c, signal_completer);
3363
3364   c = add_com ("queue-signal", class_run, queue_signal_command, _("\
3365 Queue a signal to be delivered to the current thread when it is resumed.\n\
3366 Usage: queue-signal SIGNAL\n\
3367 The SIGNAL argument is processed the same as the handle command.\n\
3368 It is an error if the handling state of SIGNAL is \"nopass\".\n\
3369 \n\
3370 An argument of \"0\" means remove any currently queued signal from\n\
3371 the current thread.  This is useful in cases where the program stopped\n\
3372 because of a signal, and you want to resume it while discarding the signal.\n\
3373 \n\
3374 In a multi-threaded program the signal is queued with, or discarded from,\n\
3375 the current thread only."));
3376   set_cmd_completer (c, signal_completer);
3377
3378   add_com ("stepi", class_run, stepi_command, _("\
3379 Step one instruction exactly.\n\
3380 Usage: stepi [N]\n\
3381 Argument N means step N times (or till program stops for another \
3382 reason)."));
3383   add_com_alias ("si", "stepi", class_alias, 0);
3384
3385   add_com ("nexti", class_run, nexti_command, _("\
3386 Step one instruction, but proceed through subroutine calls.\n\
3387 Usage: nexti [N]\n\
3388 Argument N means step N times (or till program stops for another \
3389 reason)."));
3390   add_com_alias ("ni", "nexti", class_alias, 0);
3391
3392   add_com ("finish", class_run, finish_command, _("\
3393 Execute until selected stack frame returns.\n\
3394 Usage: finish\n\
3395 Upon return, the value returned is printed and put in the value history."));
3396   add_com_alias ("fin", "finish", class_run, 1);
3397
3398   add_com ("next", class_run, next_command, _("\
3399 Step program, proceeding through subroutine calls.\n\
3400 Usage: next [N]\n\
3401 Unlike \"step\", if the current source line calls a subroutine,\n\
3402 this command does not enter the subroutine, but instead steps over\n\
3403 the call, in effect treating it as a single source line."));
3404   add_com_alias ("n", "next", class_run, 1);
3405
3406   add_com ("step", class_run, step_command, _("\
3407 Step program until it reaches a different source line.\n\
3408 Usage: step [N]\n\
3409 Argument N means step N times (or till program stops for another \
3410 reason)."));
3411   add_com_alias ("s", "step", class_run, 1);
3412
3413   c = add_com ("until", class_run, until_command, _("\
3414 Execute until the program reaches a source line greater than the current\n\
3415 or a specified location (same args as break command) within the current \
3416 frame."));
3417   set_cmd_completer (c, location_completer);
3418   add_com_alias ("u", "until", class_run, 1);
3419
3420   c = add_com ("advance", class_run, advance_command, _("\
3421 Continue the program up to the given location (same form as args for break \
3422 command).\n\
3423 Execution will also stop upon exit from the current stack frame."));
3424   set_cmd_completer (c, location_completer);
3425
3426   c = add_com ("jump", class_run, jump_command, _("\
3427 Continue program being debugged at specified line or address.\n\
3428 Usage: jump <location>\n\
3429 Give as argument either LINENUM or *ADDR, where ADDR is an expression\n\
3430 for an address to start at."));
3431   set_cmd_completer (c, location_completer);
3432   add_com_alias ("j", "jump", class_run, 1);
3433
3434   add_com ("continue", class_run, continue_command, _("\
3435 Continue program being debugged, after signal or breakpoint.\n\
3436 Usage: continue [N]\n\
3437 If proceeding from breakpoint, a number N may be used as an argument,\n\
3438 which means to set the ignore count of that breakpoint to N - 1 (so that\n\
3439 the breakpoint won't break until the Nth time it is reached).\n\
3440 \n\
3441 If non-stop mode is enabled, continue only the current thread,\n\
3442 otherwise all the threads in the program are continued.  To \n\
3443 continue all stopped threads in non-stop mode, use the -a option.\n\
3444 Specifying -a and an ignore count simultaneously is an error."));
3445   add_com_alias ("c", "cont", class_run, 1);
3446   add_com_alias ("fg", "cont", class_run, 1);
3447
3448   c = add_com ("run", class_run, run_command, _("\
3449 Start debugged program.\n"
3450 RUN_ARGS_HELP));
3451   set_cmd_completer (c, filename_completer);
3452   add_com_alias ("r", "run", class_run, 1);
3453
3454   c = add_com ("start", class_run, start_command, _("\
3455 Start the debugged program stopping at the beginning of the main procedure.\n"
3456 RUN_ARGS_HELP));
3457   set_cmd_completer (c, filename_completer);
3458
3459   c = add_com ("starti", class_run, starti_command, _("\
3460 Start the debugged program stopping at the first instruction.\n"
3461 RUN_ARGS_HELP));
3462   set_cmd_completer (c, filename_completer);
3463
3464   add_com ("interrupt", class_run, interrupt_command,
3465            _("Interrupt the execution of the debugged program.\n\
3466 If non-stop mode is enabled, interrupt only the current thread,\n\
3467 otherwise all the threads in the program are stopped.  To \n\
3468 interrupt all running threads in non-stop mode, use the -a option."));
3469
3470   c = add_info ("registers", info_registers_command, _("\
3471 List of integer registers and their contents, for selected stack frame.\n\
3472 Register name as argument means describe only that register."));
3473   add_info_alias ("r", "registers", 1);
3474   set_cmd_completer (c, reg_or_group_completer);
3475
3476   c = add_info ("all-registers", info_all_registers_command, _("\
3477 List of all registers and their contents, for selected stack frame.\n\
3478 Register name as argument means describe only that register."));
3479   set_cmd_completer (c, reg_or_group_completer);
3480
3481   add_info ("program", info_program_command,
3482             _("Execution status of the program."));
3483
3484   add_info ("float", info_float_command,
3485             _("Print the status of the floating point unit\n"));
3486
3487   add_info ("vector", info_vector_command,
3488             _("Print the status of the vector unit\n"));
3489
3490   add_prefix_cmd ("proc", class_info, info_proc_cmd,
3491                   _("\
3492 Show /proc process information about any running process.\n\
3493 Specify any process id, or use the program being debugged by default."),
3494                   &info_proc_cmdlist, "info proc ",
3495                   1/*allow-unknown*/, &infolist);
3496
3497   add_cmd ("mappings", class_info, info_proc_cmd_mappings, _("\
3498 List of mapped memory regions."),
3499            &info_proc_cmdlist);
3500
3501   add_cmd ("stat", class_info, info_proc_cmd_stat, _("\
3502 List process info from /proc/PID/stat."),
3503            &info_proc_cmdlist);
3504
3505   add_cmd ("status", class_info, info_proc_cmd_status, _("\
3506 List process info from /proc/PID/status."),
3507            &info_proc_cmdlist);
3508
3509   add_cmd ("cwd", class_info, info_proc_cmd_cwd, _("\
3510 List current working directory of the process."),
3511            &info_proc_cmdlist);
3512
3513   add_cmd ("cmdline", class_info, info_proc_cmd_cmdline, _("\
3514 List command line arguments of the process."),
3515            &info_proc_cmdlist);
3516
3517   add_cmd ("exe", class_info, info_proc_cmd_exe, _("\
3518 List absolute filename for executable of the process."),
3519            &info_proc_cmdlist);
3520
3521   add_cmd ("all", class_info, info_proc_cmd_all, _("\
3522 List all available /proc info."),
3523            &info_proc_cmdlist);
3524 }