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