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