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