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