gas/testsuite/
[external/binutils.git] / gdb / infcmd.c
1 /* Memory-access and commands for "inferior" process, for GDB.
2
3    Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
4    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
5    2008, 2009 Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include <signal.h>
24 #include "gdb_string.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "frame.h"
28 #include "inferior.h"
29 #include "environ.h"
30 #include "value.h"
31 #include "gdbcmd.h"
32 #include "symfile.h"
33 #include "gdbcore.h"
34 #include "target.h"
35 #include "language.h"
36 #include "symfile.h"
37 #include "objfiles.h"
38 #include "completer.h"
39 #include "ui-out.h"
40 #include "event-top.h"
41 #include "parser-defs.h"
42 #include "regcache.h"
43 #include "reggroups.h"
44 #include "block.h"
45 #include "solib.h"
46 #include <ctype.h>
47 #include "gdb_assert.h"
48 #include "observer.h"
49 #include "target-descriptions.h"
50 #include "user-regs.h"
51 #include "exceptions.h"
52 #include "cli/cli-decode.h"
53 #include "gdbthread.h"
54 #include "valprint.h"
55
56 /* Functions exported for general use, in inferior.h: */
57
58 void all_registers_info (char *, int);
59
60 void registers_info (char *, int);
61
62 void nexti_command (char *, int);
63
64 void stepi_command (char *, int);
65
66 void continue_command (char *, int);
67
68 void interrupt_target_command (char *args, int from_tty);
69
70 /* Local functions: */
71
72 static void nofp_registers_info (char *, int);
73
74 static void print_return_value (struct type *func_type,
75                                 struct type *value_type);
76
77 static void until_next_command (int);
78
79 static void until_command (char *, int);
80
81 static void path_info (char *, int);
82
83 static void path_command (char *, int);
84
85 static void unset_command (char *, int);
86
87 static void float_info (char *, int);
88
89 static void disconnect_command (char *, int);
90
91 static void unset_environment_command (char *, int);
92
93 static void set_environment_command (char *, int);
94
95 static void environment_info (char *, int);
96
97 static void program_info (char *, int);
98
99 static void finish_command (char *, int);
100
101 static void signal_command (char *, int);
102
103 static void jump_command (char *, int);
104
105 static void step_1 (int, int, char *);
106 static void step_once (int skip_subroutines, int single_inst, int count, int thread);
107
108 static void next_command (char *, int);
109
110 static void step_command (char *, int);
111
112 static void run_command (char *, int);
113
114 static void run_no_args_command (char *args, int from_tty);
115
116 static void go_command (char *line_no, int from_tty);
117
118 static int strip_bg_char (char **);
119
120 void _initialize_infcmd (void);
121
122 #define ERROR_NO_INFERIOR \
123    if (!target_has_execution) error (_("The program is not being run."));
124
125 /* String containing arguments to give to the program, separated by spaces.
126    Empty string (pointer to '\0') means no args.  */
127
128 static char *inferior_args;
129
130 /* The inferior arguments as a vector.  If INFERIOR_ARGC is nonzero,
131    then we must compute INFERIOR_ARGS from this (via the target).  */
132
133 static int inferior_argc;
134 static char **inferior_argv;
135
136 /* File name for default use for standard in/out in the inferior.  */
137
138 static char *inferior_io_terminal;
139
140 /* Pid of our debugged inferior, or 0 if no inferior now.
141    Since various parts of infrun.c test this to see whether there is a program
142    being debugged it should be nonzero (currently 3 is used) for remote
143    debugging.  */
144
145 ptid_t inferior_ptid;
146
147 /* Address at which inferior stopped.  */
148
149 CORE_ADDR stop_pc;
150
151 /* Flag indicating that a command has proceeded the inferior past the
152    current breakpoint.  */
153
154 int breakpoint_proceeded;
155
156 /* Nonzero if stopped due to completion of a stack dummy routine.  */
157
158 int stop_stack_dummy;
159
160 /* Nonzero if stopped due to a random (unexpected) signal in inferior
161    process.  */
162
163 int stopped_by_random_signal;
164
165 /* Environment to use for running inferior,
166    in format described in environ.h.  */
167
168 struct gdb_environ *inferior_environ;
169 \f
170 /* Accessor routines. */
171
172 void 
173 set_inferior_io_terminal (const char *terminal_name)
174 {
175   if (inferior_io_terminal)
176     xfree (inferior_io_terminal);
177
178   if (!terminal_name)
179     inferior_io_terminal = NULL;
180   else
181     inferior_io_terminal = savestring (terminal_name, strlen (terminal_name));
182 }
183
184 const char *
185 get_inferior_io_terminal (void)
186 {
187   return inferior_io_terminal;
188 }
189
190 char *
191 get_inferior_args (void)
192 {
193   if (inferior_argc != 0)
194     {
195       char *n, *old;
196
197       n = gdbarch_construct_inferior_arguments (current_gdbarch,
198                                                 inferior_argc, inferior_argv);
199       old = set_inferior_args (n);
200       xfree (old);
201     }
202
203   if (inferior_args == NULL)
204     inferior_args = xstrdup ("");
205
206   return inferior_args;
207 }
208
209 char *
210 set_inferior_args (char *newargs)
211 {
212   char *saved_args = inferior_args;
213
214   inferior_args = newargs;
215   inferior_argc = 0;
216   inferior_argv = 0;
217
218   return saved_args;
219 }
220
221 void
222 set_inferior_args_vector (int argc, char **argv)
223 {
224   inferior_argc = argc;
225   inferior_argv = argv;
226 }
227
228 /* Notice when `set args' is run.  */
229 static void
230 notice_args_set (char *args, int from_tty, struct cmd_list_element *c)
231 {
232   inferior_argc = 0;
233   inferior_argv = 0;
234 }
235
236 /* Notice when `show args' is run.  */
237 static void
238 notice_args_read (struct ui_file *file, int from_tty,
239                   struct cmd_list_element *c, const char *value)
240 {
241   /* Note that we ignore the passed-in value in favor of computing it
242      directly.  */
243   deprecated_show_value_hack (file, from_tty, c, get_inferior_args ());
244 }
245
246 \f
247 /* Compute command-line string given argument vector.  This does the
248    same shell processing as fork_inferior.  */
249 char *
250 construct_inferior_arguments (struct gdbarch *gdbarch, int argc, char **argv)
251 {
252   char *result;
253
254   if (STARTUP_WITH_SHELL)
255     {
256       /* This holds all the characters considered special to the
257          typical Unix shells.  We include `^' because the SunOS
258          /bin/sh treats it as a synonym for `|'.  */
259       char *special = "\"!#$&*()\\|[]{}<>?'\"`~^; \t\n";
260       int i;
261       int length = 0;
262       char *out, *cp;
263
264       /* We over-compute the size.  It shouldn't matter.  */
265       for (i = 0; i < argc; ++i)
266         length += 3 * strlen (argv[i]) + 1 + 2 * (argv[i][0] == '\0');
267
268       result = (char *) xmalloc (length);
269       out = result;
270
271       for (i = 0; i < argc; ++i)
272         {
273           if (i > 0)
274             *out++ = ' ';
275
276           /* Need to handle empty arguments specially.  */
277           if (argv[i][0] == '\0')
278             {
279               *out++ = '\'';
280               *out++ = '\'';
281             }
282           else
283             {
284               for (cp = argv[i]; *cp; ++cp)
285                 {
286                   if (*cp == '\n')
287                     {
288                       /* A newline cannot be quoted with a backslash (it
289                          just disappears), only by putting it inside
290                          quotes.  */
291                       *out++ = '\'';
292                       *out++ = '\n';
293                       *out++ = '\'';
294                     }
295                   else
296                     {
297                       if (strchr (special, *cp) != NULL)
298                         *out++ = '\\';
299                       *out++ = *cp;
300                     }
301                 }
302             }
303         }
304       *out = '\0';
305     }
306   else
307     {
308       /* In this case we can't handle arguments that contain spaces,
309          tabs, or newlines -- see breakup_args().  */
310       int i;
311       int length = 0;
312
313       for (i = 0; i < argc; ++i)
314         {
315           char *cp = strchr (argv[i], ' ');
316           if (cp == NULL)
317             cp = strchr (argv[i], '\t');
318           if (cp == NULL)
319             cp = strchr (argv[i], '\n');
320           if (cp != NULL)
321             error (_("can't handle command-line argument containing whitespace"));
322           length += strlen (argv[i]) + 1;
323         }
324
325       result = (char *) xmalloc (length);
326       result[0] = '\0';
327       for (i = 0; i < argc; ++i)
328         {
329           if (i > 0)
330             strcat (result, " ");
331           strcat (result, argv[i]);
332         }
333     }
334
335   return result;
336 }
337 \f
338
339 /* This function detects whether or not a '&' character (indicating
340    background execution) has been added as *the last* of the arguments ARGS
341    of a command. If it has, it removes it and returns 1. Otherwise it
342    does nothing and returns 0. */
343 static int
344 strip_bg_char (char **args)
345 {
346   char *p = NULL;
347
348   p = strchr (*args, '&');
349
350   if (p)
351     {
352       if (p == (*args + strlen (*args) - 1))
353         {
354           if (strlen (*args) > 1)
355             {
356               do
357                 p--;
358               while (*p == ' ' || *p == '\t');
359               *(p + 1) = '\0';
360             }
361           else
362             *args = 0;
363           return 1;
364         }
365     }
366   return 0;
367 }
368
369 void
370 tty_command (char *file, int from_tty)
371 {
372   if (file == 0)
373     error_no_arg (_("terminal name for running target process"));
374
375   set_inferior_io_terminal (file);
376 }
377
378 /* Common actions to take after creating any sort of inferior, by any
379    means (running, attaching, connecting, et cetera).  The target
380    should be stopped.  */
381
382 void
383 post_create_inferior (struct target_ops *target, int from_tty)
384 {
385   /* Be sure we own the terminal in case write operations are performed.  */ 
386   target_terminal_ours ();
387
388   /* If the target hasn't taken care of this already, do it now.
389      Targets which need to access registers during to_open,
390      to_create_inferior, or to_attach should do it earlier; but many
391      don't need to.  */
392   target_find_description ();
393
394   /* If the solist is global across processes, there's no need to
395      refetch it here.  */
396   if (exec_bfd && !gdbarch_has_global_solist (target_gdbarch))
397     {
398       /* Sometimes the platform-specific hook loads initial shared
399          libraries, and sometimes it doesn't.  Try to do so first, so
400          that we can add them with the correct value for FROM_TTY.
401          If we made all the inferior hook methods consistent,
402          this call could be removed.  */
403 #ifdef SOLIB_ADD
404       SOLIB_ADD (NULL, from_tty, target, auto_solib_add);
405 #else
406       solib_add (NULL, from_tty, target, auto_solib_add);
407 #endif
408     }
409
410   if (exec_bfd)
411     {
412       /* Create the hooks to handle shared library load and unload
413          events.  */
414 #ifdef SOLIB_CREATE_INFERIOR_HOOK
415       SOLIB_CREATE_INFERIOR_HOOK (PIDGET (inferior_ptid));
416 #else
417       solib_create_inferior_hook ();
418 #endif
419     }
420
421   observer_notify_inferior_created (target, from_tty);
422 }
423
424 /* Kill the inferior if already running.  This function is designed
425    to be called when we are about to start the execution of the program
426    from the beginning.  Ask the user to confirm that he wants to restart
427    the program being debugged when FROM_TTY is non-null.  */
428
429 static void
430 kill_if_already_running (int from_tty)
431 {
432   if (! ptid_equal (inferior_ptid, null_ptid) && target_has_execution)
433     {
434       /* Bail out before killing the program if we will not be able to
435          restart it.  */
436       target_require_runnable ();
437
438       if (from_tty
439           && !query (_("The program being debugged has been started already.\n\
440 Start it from the beginning? ")))
441         error (_("Program not restarted."));
442       target_kill ();
443     }
444 }
445
446 /* Implement the "run" command. If TBREAK_AT_MAIN is set, then insert
447    a temporary breakpoint at the begining of the main program before
448    running the program.  */
449
450 static void
451 run_command_1 (char *args, int from_tty, int tbreak_at_main)
452 {
453   char *exec_file;
454   struct cleanup *old_chain;
455   ptid_t ptid;
456
457   dont_repeat ();
458
459   kill_if_already_running (from_tty);
460
461   init_wait_for_inferior ();
462   clear_breakpoint_hit_counts ();
463
464   /* Clean up any leftovers from other runs.  Some other things from
465      this function should probably be moved into target_pre_inferior.  */
466   target_pre_inferior (from_tty);
467
468   /* The comment here used to read, "The exec file is re-read every
469      time we do a generic_mourn_inferior, so we just have to worry
470      about the symbol file."  The `generic_mourn_inferior' function
471      gets called whenever the program exits.  However, suppose the
472      program exits, and *then* the executable file changes?  We need
473      to check again here.  Since reopen_exec_file doesn't do anything
474      if the timestamp hasn't changed, I don't see the harm.  */
475   reopen_exec_file ();
476   reread_symbols ();
477
478   /* Insert the temporary breakpoint if a location was specified.  */
479   if (tbreak_at_main)
480     tbreak_command (main_name (), 0);
481
482   exec_file = (char *) get_exec_file (0);
483
484   if (non_stop && !target_supports_non_stop ())
485     error (_("The target does not support running in non-stop mode."));
486
487   /* We keep symbols from add-symbol-file, on the grounds that the
488      user might want to add some symbols before running the program
489      (right?).  But sometimes (dynamic loading where the user manually
490      introduces the new symbols with add-symbol-file), the code which
491      the symbols describe does not persist between runs.  Currently
492      the user has to manually nuke all symbols between runs if they
493      want them to go away (PR 2207).  This is probably reasonable.  */
494
495   if (!args)
496     {
497       if (target_can_async_p ())
498         async_disable_stdin ();
499     }
500   else
501     {
502       int async_exec = strip_bg_char (&args);
503
504       /* If we get a request for running in the bg but the target
505          doesn't support it, error out. */
506       if (async_exec && !target_can_async_p ())
507         error (_("Asynchronous execution not supported on this target."));
508
509       /* If we don't get a request of running in the bg, then we need
510          to simulate synchronous (fg) execution. */
511       if (!async_exec && target_can_async_p ())
512         {
513           /* Simulate synchronous execution */
514           async_disable_stdin ();
515         }
516
517       /* If there were other args, beside '&', process them. */
518       if (args)
519         {
520           char *old_args = set_inferior_args (xstrdup (args));
521           xfree (old_args);
522         }
523     }
524
525   if (from_tty)
526     {
527       ui_out_field_string (uiout, NULL, "Starting program");
528       ui_out_text (uiout, ": ");
529       if (exec_file)
530         ui_out_field_string (uiout, "execfile", exec_file);
531       ui_out_spaces (uiout, 1);
532       /* We call get_inferior_args() because we might need to compute
533          the value now.  */
534       ui_out_field_string (uiout, "infargs", get_inferior_args ());
535       ui_out_text (uiout, "\n");
536       ui_out_flush (uiout);
537     }
538
539   /* We call get_inferior_args() because we might need to compute
540      the value now.  */
541   target_create_inferior (exec_file, get_inferior_args (),
542                           environ_vector (inferior_environ), from_tty);
543
544   /* We're starting off a new process.  When we get out of here, in
545      non-stop mode, finish the state of all threads of that process,
546      but leave other threads alone, as they may be stopped in internal
547      events --- the frontend shouldn't see them as stopped.  In
548      all-stop, always finish the state of all threads, as we may be
549      resuming more than just the new process.  */
550   if (non_stop)
551     ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
552   else
553     ptid = minus_one_ptid;
554   old_chain = make_cleanup (finish_thread_state_cleanup, &ptid);
555
556   /* Pass zero for FROM_TTY, because at this point the "run" command
557      has done its thing; now we are setting up the running program.  */
558   post_create_inferior (&current_target, 0);
559
560   /* Start the target running.  */
561   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_0, 0);
562
563   /* Since there was no error, there's no need to finish the thread
564      states here.  */
565   discard_cleanups (old_chain);
566 }
567
568 static void
569 run_command (char *args, int from_tty)
570 {
571   run_command_1 (args, from_tty, 0);
572 }
573
574 static void
575 run_no_args_command (char *args, int from_tty)
576 {
577   char *old_args = set_inferior_args (xstrdup (""));
578   xfree (old_args);
579 }
580 \f
581
582 /* Start the execution of the program up until the beginning of the main
583    program.  */
584
585 static void
586 start_command (char *args, int from_tty)
587 {
588   /* Some languages such as Ada need to search inside the program
589      minimal symbols for the location where to put the temporary
590      breakpoint before starting.  */
591   if (!have_minimal_symbols ())
592     error (_("No symbol table loaded.  Use the \"file\" command."));
593
594   /* Run the program until reaching the main procedure...  */
595   run_command_1 (args, from_tty, 1);
596
597
598 static int
599 proceed_thread_callback (struct thread_info *thread, void *arg)
600 {
601   /* We go through all threads individually instead of compressing
602      into a single target `resume_all' request, because some threads
603      may be stopped in internal breakpoints/events, or stopped waiting
604      for its turn in the displaced stepping queue (that is, they are
605      running && !executing).  The target side has no idea about why
606      the thread is stopped, so a `resume_all' command would resume too
607      much.  If/when GDB gains a way to tell the target `hold this
608      thread stopped until I say otherwise', then we can optimize
609      this.  */
610   if (!is_stopped (thread->ptid))
611     return 0;
612
613   switch_to_thread (thread->ptid);
614   clear_proceed_status ();
615   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
616   return 0;
617 }
618
619 void
620 ensure_valid_thread (void)
621 {
622   if (ptid_equal (inferior_ptid, null_ptid)
623       || is_exited (inferior_ptid))
624     error (_("\
625 Cannot execute this command without a live selected thread."));
626 }
627
628 void
629 continue_1 (int all_threads)
630 {
631   ERROR_NO_INFERIOR;
632
633   if (non_stop && all_threads)
634     {
635       /* Don't error out if the current thread is running, because
636         there may be other stopped threads.  */
637       struct cleanup *old_chain;
638
639       /* Backup current thread and selected frame.  */
640       old_chain = make_cleanup_restore_current_thread ();
641
642       iterate_over_threads (proceed_thread_callback, NULL);
643
644       /* Restore selected ptid.  */
645       do_cleanups (old_chain);
646     }
647   else
648     {
649       ensure_valid_thread ();
650       ensure_not_running ();
651       clear_proceed_status ();
652       proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
653     }
654 }
655
656 /* continue [-a] [proceed-count] [&]  */
657 void
658 continue_command (char *args, int from_tty)
659 {
660   int async_exec = 0;
661   int all_threads = 0;
662   ERROR_NO_INFERIOR;
663
664   /* Find out whether we must run in the background. */
665   if (args != NULL)
666     async_exec = strip_bg_char (&args);
667
668   /* If we must run in the background, but the target can't do it,
669      error out. */
670   if (async_exec && !target_can_async_p ())
671     error (_("Asynchronous execution not supported on this target."));
672
673   /* If we are not asked to run in the bg, then prepare to run in the
674      foreground, synchronously. */
675   if (!async_exec && target_can_async_p ())
676     {
677       /* Simulate synchronous execution */
678       async_disable_stdin ();
679     }
680
681   if (args != NULL)
682     {
683       if (strncmp (args, "-a", sizeof ("-a") - 1) == 0)
684         {
685           all_threads = 1;
686           args += sizeof ("-a") - 1;
687           if (*args == '\0')
688             args = NULL;
689         }
690     }
691
692   if (!non_stop && all_threads)
693     error (_("`-a' is meaningless in all-stop mode."));
694
695   if (args != NULL && all_threads)
696     error (_("\
697 Can't resume all threads and specify proceed count simultaneously."));
698
699   /* If we have an argument left, set proceed count of breakpoint we
700      stopped at.  */
701   if (args != NULL)
702     {
703       bpstat bs = NULL;
704       int num, stat;
705       int stopped = 0;
706       struct thread_info *tp;
707
708       if (non_stop)
709         tp = find_thread_pid (inferior_ptid);
710       else
711         {
712           ptid_t last_ptid;
713           struct target_waitstatus ws;
714
715           get_last_target_status (&last_ptid, &ws);
716           tp = find_thread_pid (last_ptid);
717         }
718       if (tp != NULL)
719         bs = tp->stop_bpstat;
720
721       while ((stat = bpstat_num (&bs, &num)) != 0)
722         if (stat > 0)
723           {
724             set_ignore_count (num,
725                               parse_and_eval_long (args) - 1,
726                               from_tty);
727             /* set_ignore_count prints a message ending with a period.
728                So print two spaces before "Continuing.".  */
729             if (from_tty)
730               printf_filtered ("  ");
731             stopped = 1;
732           }
733
734       if (!stopped && from_tty)
735         {
736           printf_filtered
737             ("Not stopped at any breakpoint; argument ignored.\n");
738         }
739     }
740
741   if (from_tty)
742     printf_filtered (_("Continuing.\n"));
743
744   continue_1 (all_threads);
745 }
746 \f
747 /* Step until outside of current statement.  */
748
749 static void
750 step_command (char *count_string, int from_tty)
751 {
752   step_1 (0, 0, count_string);
753 }
754
755 /* Likewise, but skip over subroutine calls as if single instructions.  */
756
757 static void
758 next_command (char *count_string, int from_tty)
759 {
760   step_1 (1, 0, count_string);
761 }
762
763 /* Likewise, but step only one instruction.  */
764
765 void
766 stepi_command (char *count_string, int from_tty)
767 {
768   step_1 (0, 1, count_string);
769 }
770
771 void
772 nexti_command (char *count_string, int from_tty)
773 {
774   step_1 (1, 1, count_string);
775 }
776
777 static void
778 delete_longjmp_breakpoint_cleanup (void *arg)
779 {
780   int thread = * (int *) arg;
781   delete_longjmp_breakpoint (thread);
782 }
783
784 static void
785 step_1 (int skip_subroutines, int single_inst, char *count_string)
786 {
787   int count = 1;
788   struct frame_info *frame;
789   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
790   int async_exec = 0;
791   int thread = -1;
792
793   ERROR_NO_INFERIOR;
794   ensure_valid_thread ();
795   ensure_not_running ();
796
797   if (count_string)
798     async_exec = strip_bg_char (&count_string);
799
800   /* If we get a request for running in the bg but the target
801      doesn't support it, error out. */
802   if (async_exec && !target_can_async_p ())
803     error (_("Asynchronous execution not supported on this target."));
804
805   /* If we don't get a request of running in the bg, then we need
806      to simulate synchronous (fg) execution. */
807   if (!async_exec && target_can_async_p ())
808     {
809       /* Simulate synchronous execution */
810       async_disable_stdin ();
811     }
812
813   count = count_string ? parse_and_eval_long (count_string) : 1;
814
815   if (!single_inst || skip_subroutines)         /* leave si command alone */
816     {
817       if (in_thread_list (inferior_ptid))
818         thread = pid_to_thread_id (inferior_ptid);
819
820       set_longjmp_breakpoint ();
821
822       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
823     }
824
825   /* In synchronous case, all is well; each step_once call will step once.  */
826   if (!target_can_async_p ())
827     {
828       for (; count > 0; count--)
829         {
830           struct thread_info *tp;
831           step_once (skip_subroutines, single_inst, count, thread);
832
833           if (target_has_execution
834               && !ptid_equal (inferior_ptid, null_ptid))
835             tp = inferior_thread ();
836           else
837             tp = NULL;
838
839           if (!tp || !tp->stop_step || !tp->step_multi)
840             {
841               /* If we stopped for some reason that is not stepping
842                  there are no further steps to make.  */
843               if (tp)
844                 tp->step_multi = 0;
845               break;
846             }
847         }
848
849       do_cleanups (cleanups);
850     }
851   else
852     {
853       /* In the case of an asynchronous target things get complicated;
854          do only one step for now, before returning control to the
855          event loop.  Let the continuation figure out how many other
856          steps we need to do, and handle them one at the time, through
857          step_once.  */
858       step_once (skip_subroutines, single_inst, count, thread);
859
860       /* We are running, and the continuation is installed.  It will
861          disable the longjmp breakpoint as appropriate.  */
862       discard_cleanups (cleanups);
863     }
864 }
865
866 struct step_1_continuation_args
867 {
868   int count;
869   int skip_subroutines;
870   int single_inst;
871   int thread;
872 };
873
874 /* Called after we are done with one step operation, to check whether
875    we need to step again, before we print the prompt and return control
876    to the user. If count is > 1, we will need to do one more call to
877    proceed(), via step_once(). Basically it is like step_once and
878    step_1_continuation are co-recursive. */
879 static void
880 step_1_continuation (void *args)
881 {
882   struct step_1_continuation_args *a = args;
883
884   if (target_has_execution)
885     {
886       struct thread_info *tp;
887
888       tp = inferior_thread ();
889       if (tp->step_multi && tp->stop_step)
890         {
891           /* There are more steps to make, and we did stop due to
892              ending a stepping range.  Do another step.  */
893           step_once (a->skip_subroutines, a->single_inst,
894                      a->count - 1, a->thread);
895           return;
896         }
897       tp->step_multi = 0;
898     }
899
900   /* We either stopped for some reason that is not stepping, or there
901      are no further steps to make.  Cleanup.  */
902   if (!a->single_inst || a->skip_subroutines)
903     delete_longjmp_breakpoint (a->thread);
904 }
905
906 /* Do just one step operation.  This is useful to implement the 'step
907    n' kind of commands.  In case of asynchronous targets, we will have
908    to set up a continuation to be done after the target stops (after
909    this one step).  For synch targets, the caller handles further
910    stepping.  */
911
912 static void
913 step_once (int skip_subroutines, int single_inst, int count, int thread)
914 {
915   struct frame_info *frame;
916
917   if (count > 0)
918     {
919       /* Don't assume THREAD is a valid thread id.  It is set to -1 if
920          the longjmp breakpoint was not required.  Use the
921          INFERIOR_PTID thread instead, which is the same thread when
922          THREAD is set.  */
923       struct thread_info *tp = inferior_thread ();
924       clear_proceed_status ();
925
926       frame = get_current_frame ();
927       tp->step_frame_id = get_frame_id (frame);
928
929       if (!single_inst)
930         {
931           CORE_ADDR pc;
932
933           pc = get_frame_pc (frame);
934           find_pc_line_pc_range (pc,
935                                  &tp->step_range_start, &tp->step_range_end);
936
937           /* If we have no line info, switch to stepi mode.  */
938           if (tp->step_range_end == 0 && step_stop_if_no_debug)
939             {
940               tp->step_range_start = tp->step_range_end = 1;
941             }
942           else if (tp->step_range_end == 0)
943             {
944               char *name;
945               if (find_pc_partial_function (pc, &name,
946                                             &tp->step_range_start,
947                                             &tp->step_range_end) == 0)
948                 error (_("Cannot find bounds of current function"));
949
950               target_terminal_ours ();
951               printf_filtered (_("\
952 Single stepping until exit from function %s, \n\
953 which has no line number information.\n"), name);
954             }
955         }
956       else
957         {
958           /* Say we are stepping, but stop after one insn whatever it does.  */
959           tp->step_range_start = tp->step_range_end = 1;
960           if (!skip_subroutines)
961             /* It is stepi.
962                Don't step over function calls, not even to functions lacking
963                line numbers.  */
964             tp->step_over_calls = STEP_OVER_NONE;
965         }
966
967       if (skip_subroutines)
968         tp->step_over_calls = STEP_OVER_ALL;
969
970       tp->step_multi = (count > 1);
971       proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 1);
972
973       /* For async targets, register a continuation to do any
974          additional steps.  For sync targets, the caller will handle
975          further stepping.  */
976       if (target_can_async_p ())
977         {
978           struct step_1_continuation_args *args;
979
980           args = xmalloc (sizeof (*args));
981           args->skip_subroutines = skip_subroutines;
982           args->single_inst = single_inst;
983           args->count = count;
984           args->thread = thread;
985
986           add_intermediate_continuation (tp, step_1_continuation, args, xfree);
987         }
988     }
989 }
990
991 \f
992 /* Continue program at specified address.  */
993
994 static void
995 jump_command (char *arg, int from_tty)
996 {
997   CORE_ADDR addr;
998   struct symtabs_and_lines sals;
999   struct symtab_and_line sal;
1000   struct symbol *fn;
1001   struct symbol *sfn;
1002   int async_exec = 0;
1003
1004   ERROR_NO_INFERIOR;
1005   ensure_valid_thread ();
1006   ensure_not_running ();
1007
1008   /* Find out whether we must run in the background. */
1009   if (arg != NULL)
1010     async_exec = strip_bg_char (&arg);
1011
1012   /* If we must run in the background, but the target can't do it,
1013      error out. */
1014   if (async_exec && !target_can_async_p ())
1015     error (_("Asynchronous execution not supported on this target."));
1016
1017   if (!arg)
1018     error_no_arg (_("starting address"));
1019
1020   sals = decode_line_spec_1 (arg, 1);
1021   if (sals.nelts != 1)
1022     {
1023       error (_("Unreasonable jump request"));
1024     }
1025
1026   sal = sals.sals[0];
1027   xfree (sals.sals);
1028
1029   if (sal.symtab == 0 && sal.pc == 0)
1030     error (_("No source file has been specified."));
1031
1032   resolve_sal_pc (&sal);        /* May error out */
1033
1034   /* See if we are trying to jump to another function. */
1035   fn = get_frame_function (get_current_frame ());
1036   sfn = find_pc_function (sal.pc);
1037   if (fn != NULL && sfn != fn)
1038     {
1039       if (!query (_("Line %d is not in `%s'.  Jump anyway? "), sal.line,
1040                   SYMBOL_PRINT_NAME (fn)))
1041         {
1042           error (_("Not confirmed."));
1043           /* NOTREACHED */
1044         }
1045     }
1046
1047   if (sfn != NULL)
1048     {
1049       fixup_symbol_section (sfn, 0);
1050       if (section_is_overlay (SYMBOL_OBJ_SECTION (sfn)) &&
1051           !section_is_mapped (SYMBOL_OBJ_SECTION (sfn)))
1052         {
1053           if (!query (_("WARNING!!!  Destination is in unmapped overlay!  Jump anyway? ")))
1054             {
1055               error (_("Not confirmed."));
1056               /* NOTREACHED */
1057             }
1058         }
1059     }
1060
1061   addr = sal.pc;
1062
1063   if (from_tty)
1064     {
1065       printf_filtered (_("Continuing at "));
1066       fputs_filtered (paddress (addr), gdb_stdout);
1067       printf_filtered (".\n");
1068     }
1069
1070   /* If we are not asked to run in the bg, then prepare to run in the
1071      foreground, synchronously. */
1072   if (!async_exec && target_can_async_p ())
1073     {
1074       /* Simulate synchronous execution */
1075       async_disable_stdin ();
1076     }
1077
1078   clear_proceed_status ();
1079   proceed (addr, TARGET_SIGNAL_0, 0);
1080 }
1081 \f
1082
1083 /* Go to line or address in current procedure */
1084 static void
1085 go_command (char *line_no, int from_tty)
1086 {
1087   if (line_no == (char *) NULL || !*line_no)
1088     printf_filtered (_("Usage: go <location>\n"));
1089   else
1090     {
1091       tbreak_command (line_no, from_tty);
1092       jump_command (line_no, from_tty);
1093     }
1094 }
1095 \f
1096
1097 /* Continue program giving it specified signal.  */
1098
1099 static void
1100 signal_command (char *signum_exp, int from_tty)
1101 {
1102   enum target_signal oursig;
1103   int async_exec = 0;
1104
1105   dont_repeat ();               /* Too dangerous.  */
1106   ERROR_NO_INFERIOR;
1107   ensure_valid_thread ();
1108   ensure_not_running ();
1109
1110   /* Find out whether we must run in the background.  */
1111   if (signum_exp != NULL)
1112     async_exec = strip_bg_char (&signum_exp);
1113
1114   /* If we must run in the background, but the target can't do it,
1115      error out.  */
1116   if (async_exec && !target_can_async_p ())
1117     error (_("Asynchronous execution not supported on this target."));
1118
1119   /* If we are not asked to run in the bg, then prepare to run in the
1120      foreground, synchronously.  */
1121   if (!async_exec && target_can_async_p ())
1122     {
1123       /* Simulate synchronous execution.  */
1124       async_disable_stdin ();
1125     }
1126
1127   if (!signum_exp)
1128     error_no_arg (_("signal number"));
1129
1130   /* It would be even slicker to make signal names be valid expressions,
1131      (the type could be "enum $signal" or some such), then the user could
1132      assign them to convenience variables.  */
1133   oursig = target_signal_from_name (signum_exp);
1134
1135   if (oursig == TARGET_SIGNAL_UNKNOWN)
1136     {
1137       /* No, try numeric.  */
1138       int num = parse_and_eval_long (signum_exp);
1139
1140       if (num == 0)
1141         oursig = TARGET_SIGNAL_0;
1142       else
1143         oursig = target_signal_from_command (num);
1144     }
1145
1146   if (from_tty)
1147     {
1148       if (oursig == TARGET_SIGNAL_0)
1149         printf_filtered (_("Continuing with no signal.\n"));
1150       else
1151         printf_filtered (_("Continuing with signal %s.\n"),
1152                          target_signal_to_name (oursig));
1153     }
1154
1155   clear_proceed_status ();
1156   proceed ((CORE_ADDR) -1, oursig, 0);
1157 }
1158
1159 /* Proceed until we reach a different source line with pc greater than
1160    our current one or exit the function.  We skip calls in both cases.
1161
1162    Note that eventually this command should probably be changed so
1163    that only source lines are printed out when we hit the breakpoint
1164    we set.  This may involve changes to wait_for_inferior and the
1165    proceed status code.  */
1166
1167 static void
1168 until_next_command (int from_tty)
1169 {
1170   struct frame_info *frame;
1171   CORE_ADDR pc;
1172   struct symbol *func;
1173   struct symtab_and_line sal;
1174   struct thread_info *tp = inferior_thread ();
1175
1176   clear_proceed_status ();
1177
1178   frame = get_current_frame ();
1179
1180   /* Step until either exited from this function or greater
1181      than the current line (if in symbolic section) or pc (if
1182      not). */
1183
1184   pc = get_frame_pc (frame);
1185   func = find_pc_function (pc);
1186
1187   if (!func)
1188     {
1189       struct minimal_symbol *msymbol = lookup_minimal_symbol_by_pc (pc);
1190
1191       if (msymbol == NULL)
1192         error (_("Execution is not within a known function."));
1193
1194       tp->step_range_start = SYMBOL_VALUE_ADDRESS (msymbol);
1195       tp->step_range_end = pc;
1196     }
1197   else
1198     {
1199       sal = find_pc_line (pc, 0);
1200
1201       tp->step_range_start = BLOCK_START (SYMBOL_BLOCK_VALUE (func));
1202       tp->step_range_end = sal.end;
1203     }
1204
1205   tp->step_over_calls = STEP_OVER_ALL;
1206   tp->step_frame_id = get_frame_id (frame);
1207
1208   tp->step_multi = 0;           /* Only one call to proceed */
1209
1210   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 1);
1211 }
1212
1213 static void
1214 until_command (char *arg, int from_tty)
1215 {
1216   int async_exec = 0;
1217
1218   if (!target_has_execution)
1219     error (_("The program is not running."));
1220
1221   /* Find out whether we must run in the background. */
1222   if (arg != NULL)
1223     async_exec = strip_bg_char (&arg);
1224
1225   /* If we must run in the background, but the target can't do it,
1226      error out. */
1227   if (async_exec && !target_can_async_p ())
1228     error (_("Asynchronous execution not supported on this target."));
1229
1230   /* If we are not asked to run in the bg, then prepare to run in the
1231      foreground, synchronously. */
1232   if (!async_exec && target_can_async_p ())
1233     {
1234       /* Simulate synchronous execution */
1235       async_disable_stdin ();
1236     }
1237
1238   if (arg)
1239     until_break_command (arg, from_tty, 0);
1240   else
1241     until_next_command (from_tty);
1242 }
1243
1244 static void
1245 advance_command (char *arg, int from_tty)
1246 {
1247   int async_exec = 0;
1248
1249   if (!target_has_execution)
1250     error (_("The program is not running."));
1251
1252   if (arg == NULL)
1253     error_no_arg (_("a location"));
1254
1255   /* Find out whether we must run in the background.  */
1256   if (arg != NULL)
1257     async_exec = strip_bg_char (&arg);
1258
1259   /* If we must run in the background, but the target can't do it,
1260      error out.  */
1261   if (async_exec && !target_can_async_p ())
1262     error (_("Asynchronous execution not supported on this target."));
1263
1264   /* If we are not asked to run in the bg, then prepare to run in the
1265      foreground, synchronously.  */
1266   if (!async_exec && target_can_async_p ())
1267     {
1268       /* Simulate synchronous execution.  */
1269       async_disable_stdin ();
1270     }
1271
1272   until_break_command (arg, from_tty, 1);
1273 }
1274 \f
1275 /* Print the result of a function at the end of a 'finish' command.  */
1276
1277 static void
1278 print_return_value (struct type *func_type, struct type *value_type)
1279 {
1280   struct gdbarch *gdbarch = current_gdbarch;
1281   struct cleanup *old_chain;
1282   struct ui_stream *stb;
1283   struct value *value;
1284
1285   CHECK_TYPEDEF (value_type);
1286   gdb_assert (TYPE_CODE (value_type) != TYPE_CODE_VOID);
1287
1288   /* FIXME: 2003-09-27: When returning from a nested inferior function
1289      call, it's possible (with no help from the architecture vector)
1290      to locate and return/print a "struct return" value.  This is just
1291      a more complicated case of what is already being done in in the
1292      inferior function call code.  In fact, when inferior function
1293      calls are made async, this will likely be made the norm.  */
1294
1295   switch (gdbarch_return_value (gdbarch, func_type, value_type,
1296                                 NULL, NULL, NULL))
1297     {
1298     case RETURN_VALUE_REGISTER_CONVENTION:
1299     case RETURN_VALUE_ABI_RETURNS_ADDRESS:
1300     case RETURN_VALUE_ABI_PRESERVES_ADDRESS:
1301       value = allocate_value (value_type);
1302       gdbarch_return_value (gdbarch, func_type, value_type, stop_registers,
1303                             value_contents_raw (value), NULL);
1304       break;
1305     case RETURN_VALUE_STRUCT_CONVENTION:
1306       value = NULL;
1307       break;
1308     default:
1309       internal_error (__FILE__, __LINE__, _("bad switch"));
1310     }
1311
1312   if (value)
1313     {
1314       struct value_print_options opts;
1315
1316       /* Print it.  */
1317       stb = ui_out_stream_new (uiout);
1318       old_chain = make_cleanup_ui_out_stream_delete (stb);
1319       ui_out_text (uiout, "Value returned is ");
1320       ui_out_field_fmt (uiout, "gdb-result-var", "$%d",
1321                         record_latest_value (value));
1322       ui_out_text (uiout, " = ");
1323       get_raw_print_options (&opts);
1324       value_print (value, stb->stream, &opts);
1325       ui_out_field_stream (uiout, "return-value", stb);
1326       ui_out_text (uiout, "\n");
1327       do_cleanups (old_chain);
1328     }
1329   else
1330     {
1331       ui_out_text (uiout, "Value returned has type: ");
1332       ui_out_field_string (uiout, "return-type", TYPE_NAME (value_type));
1333       ui_out_text (uiout, ".");
1334       ui_out_text (uiout, " Cannot determine contents\n");
1335     }
1336 }
1337
1338 /* Stuff that needs to be done by the finish command after the target
1339    has stopped.  In asynchronous mode, we wait for the target to stop
1340    in the call to poll or select in the event loop, so it is
1341    impossible to do all the stuff as part of the finish_command
1342    function itself.  The only chance we have to complete this command
1343    is in fetch_inferior_event, which is called by the event loop as
1344    soon as it detects that the target has stopped. This function is
1345    called via the cmd_continuation pointer.  */
1346
1347 struct finish_command_continuation_args
1348 {
1349   struct breakpoint *breakpoint;
1350   struct symbol *function;
1351 };
1352
1353 static void
1354 finish_command_continuation (void *arg)
1355 {
1356   struct finish_command_continuation_args *a = arg;
1357   struct thread_info *tp = NULL;
1358   bpstat bs = NULL;
1359
1360   if (!ptid_equal (inferior_ptid, null_ptid)
1361       && target_has_execution
1362       && is_stopped (inferior_ptid))
1363     {
1364       tp = inferior_thread ();
1365       bs = tp->stop_bpstat;
1366     }
1367
1368   if (bpstat_find_breakpoint (bs, a->breakpoint) != NULL
1369       && a->function != NULL)
1370     {
1371       struct type *value_type;
1372
1373       value_type = TYPE_TARGET_TYPE (SYMBOL_TYPE (a->function));
1374       if (!value_type)
1375         internal_error (__FILE__, __LINE__,
1376                         _("finish_command: function has no target type"));
1377
1378       if (TYPE_CODE (value_type) != TYPE_CODE_VOID)
1379         print_return_value (SYMBOL_TYPE (a->function), value_type);
1380     }
1381
1382   /* We suppress normal call of normal_stop observer and do it here so
1383      that the *stopped notification includes the return value.  */
1384   if (bs != NULL && tp->proceed_to_finish)
1385     observer_notify_normal_stop (bs, 1 /* print frame */);
1386   delete_breakpoint (a->breakpoint);
1387 }
1388
1389 static void
1390 finish_command_continuation_free_arg (void *arg)
1391 {
1392   xfree (arg);
1393 }
1394
1395 /* finish_backward -- helper function for finish_command.  */
1396
1397 static void
1398 finish_backward (struct symbol *function)
1399 {
1400   struct symtab_and_line sal;
1401   struct thread_info *tp = inferior_thread ();
1402   struct breakpoint *breakpoint;
1403   struct cleanup *old_chain;
1404   CORE_ADDR pc;
1405   CORE_ADDR func_addr;
1406   int back_up;
1407
1408   pc = get_frame_pc (get_current_frame ());
1409
1410   if (find_pc_partial_function (pc, NULL, &func_addr, NULL) == 0)
1411     internal_error (__FILE__, __LINE__,
1412                     _("Finish: couldn't find function."));
1413
1414   sal = find_pc_line (func_addr, 0);
1415
1416   /* We don't need a return value.  */
1417   tp->proceed_to_finish = 0;
1418   /* Special case: if we're sitting at the function entry point,
1419      then all we need to do is take a reverse singlestep.  We
1420      don't need to set a breakpoint, and indeed it would do us
1421      no good to do so.
1422
1423      Note that this can only happen at frame #0, since there's
1424      no way that a function up the stack can have a return address
1425      that's equal to its entry point.  */
1426
1427   if (sal.pc != pc)
1428     {
1429       /* Set breakpoint and continue.  */
1430       breakpoint =
1431         set_momentary_breakpoint (sal,
1432                                   get_frame_id (get_selected_frame (NULL)),
1433                                   bp_breakpoint);
1434       /* Tell the breakpoint to keep quiet.  We won't be done
1435          until we've done another reverse single-step.  */
1436       make_breakpoint_silent (breakpoint);
1437       old_chain = make_cleanup_delete_breakpoint (breakpoint);
1438       proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
1439       /* We will be stopped when proceed returns.  */
1440       back_up = bpstat_find_breakpoint (tp->stop_bpstat, breakpoint) != NULL;
1441       do_cleanups (old_chain);
1442     }
1443   else
1444     back_up = 1;
1445   if (back_up)
1446     {
1447       /* If in fact we hit the step-resume breakpoint (and not
1448          some other breakpoint), then we're almost there --
1449          we just need to back up by one more single-step.  */
1450       tp->step_range_start = tp->step_range_end = 1;
1451       proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 1);
1452     }
1453   return;
1454 }
1455
1456 /* finish_forward -- helper function for finish_command.  */
1457
1458 static void
1459 finish_forward (struct symbol *function, struct frame_info *frame)
1460 {
1461   struct symtab_and_line sal;
1462   struct thread_info *tp = inferior_thread ();
1463   struct breakpoint *breakpoint;
1464   struct cleanup *old_chain;
1465   struct finish_command_continuation_args *cargs;
1466
1467   sal = find_pc_line (get_frame_pc (frame), 0);
1468   sal.pc = get_frame_pc (frame);
1469
1470   breakpoint = set_momentary_breakpoint (sal, get_frame_id (frame),
1471                                          bp_finish);
1472
1473   old_chain = make_cleanup_delete_breakpoint (breakpoint);
1474
1475   tp->proceed_to_finish = 1;    /* We want stop_registers, please...  */
1476   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
1477
1478   cargs = xmalloc (sizeof (*cargs));
1479
1480   cargs->breakpoint = breakpoint;
1481   cargs->function = function;
1482   add_continuation (tp, finish_command_continuation, cargs,
1483                     finish_command_continuation_free_arg);
1484
1485   discard_cleanups (old_chain);
1486   if (!target_can_async_p ())
1487     do_all_continuations ();
1488 }
1489
1490 /* "finish": Set a temporary breakpoint at the place the selected
1491    frame will return to, then continue.  */
1492
1493 static void
1494 finish_command (char *arg, int from_tty)
1495 {
1496   struct frame_info *frame;
1497   struct symbol *function;
1498
1499   int async_exec = 0;
1500
1501   /* Find out whether we must run in the background.  */
1502   if (arg != NULL)
1503     async_exec = strip_bg_char (&arg);
1504
1505   /* If we must run in the background, but the target can't do it,
1506      error out.  */
1507   if (async_exec && !target_can_async_p ())
1508     error (_("Asynchronous execution not supported on this target."));
1509
1510   /* Don't try to async in reverse.  */
1511   if (async_exec && execution_direction == EXEC_REVERSE)
1512     error (_("Asynchronous 'finish' not supported in reverse."));
1513
1514   /* If we are not asked to run in the bg, then prepare to run in the
1515      foreground, synchronously.  */
1516   if (!async_exec && target_can_async_p ())
1517     {
1518       /* Simulate synchronous execution.  */
1519       async_disable_stdin ();
1520     }
1521
1522   if (arg)
1523     error (_("The \"finish\" command does not take any arguments."));
1524   if (!target_has_execution)
1525     error (_("The program is not running."));
1526
1527   frame = get_prev_frame (get_selected_frame (_("No selected frame.")));
1528   if (frame == 0)
1529     error (_("\"finish\" not meaningful in the outermost frame."));
1530
1531   clear_proceed_status ();
1532
1533   /* Find the function we will return from.  */
1534
1535   function = find_pc_function (get_frame_pc (get_selected_frame (NULL)));
1536
1537   /* Print info on the selected frame, including level number but not
1538      source.  */
1539   if (from_tty)
1540     {
1541       if (execution_direction == EXEC_REVERSE)
1542         printf_filtered (_("Run back to call of "));
1543       else
1544         printf_filtered (_("Run till exit from "));
1545
1546       print_stack_frame (get_selected_frame (NULL), 1, LOCATION);
1547     }
1548
1549   if (execution_direction == EXEC_REVERSE)
1550     finish_backward (function);
1551   else
1552     finish_forward (function, frame);
1553 }
1554 \f
1555
1556 static void
1557 program_info (char *args, int from_tty)
1558 {
1559   bpstat bs;
1560   int num, stat;
1561   struct thread_info *tp;
1562   ptid_t ptid;
1563
1564   if (!target_has_execution)
1565     {
1566       printf_filtered (_("The program being debugged is not being run.\n"));
1567       return;
1568     }
1569
1570   if (non_stop)
1571     ptid = inferior_ptid;
1572   else
1573     {
1574       struct target_waitstatus ws;
1575       get_last_target_status (&ptid, &ws);
1576     }
1577
1578   if (ptid_equal (ptid, null_ptid) || is_exited (ptid))
1579     error (_("Invalid selected thread."));
1580   else if (is_running (ptid))
1581     error (_("Selected thread is running."));
1582
1583   tp = find_thread_pid (ptid);
1584   bs = tp->stop_bpstat;
1585   stat = bpstat_num (&bs, &num);
1586
1587   target_files_info ();
1588   printf_filtered (_("Program stopped at %s.\n"), paddress (stop_pc));
1589   if (tp->stop_step)
1590     printf_filtered (_("It stopped after being stepped.\n"));
1591   else if (stat != 0)
1592     {
1593       /* There may be several breakpoints in the same place, so this
1594          isn't as strange as it seems.  */
1595       while (stat != 0)
1596         {
1597           if (stat < 0)
1598             {
1599               printf_filtered (_("\
1600 It stopped at a breakpoint that has since been deleted.\n"));
1601             }
1602           else
1603             printf_filtered (_("It stopped at breakpoint %d.\n"), num);
1604           stat = bpstat_num (&bs, &num);
1605         }
1606     }
1607   else if (tp->stop_signal != TARGET_SIGNAL_0)
1608     {
1609       printf_filtered (_("It stopped with signal %s, %s.\n"),
1610                        target_signal_to_name (tp->stop_signal),
1611                        target_signal_to_string (tp->stop_signal));
1612     }
1613
1614   if (!from_tty)
1615     {
1616       printf_filtered (_("\
1617 Type \"info stack\" or \"info registers\" for more information.\n"));
1618     }
1619 }
1620 \f
1621 static void
1622 environment_info (char *var, int from_tty)
1623 {
1624   if (var)
1625     {
1626       char *val = get_in_environ (inferior_environ, var);
1627       if (val)
1628         {
1629           puts_filtered (var);
1630           puts_filtered (" = ");
1631           puts_filtered (val);
1632           puts_filtered ("\n");
1633         }
1634       else
1635         {
1636           puts_filtered ("Environment variable \"");
1637           puts_filtered (var);
1638           puts_filtered ("\" not defined.\n");
1639         }
1640     }
1641   else
1642     {
1643       char **vector = environ_vector (inferior_environ);
1644       while (*vector)
1645         {
1646           puts_filtered (*vector++);
1647           puts_filtered ("\n");
1648         }
1649     }
1650 }
1651
1652 static void
1653 set_environment_command (char *arg, int from_tty)
1654 {
1655   char *p, *val, *var;
1656   int nullset = 0;
1657
1658   if (arg == 0)
1659     error_no_arg (_("environment variable and value"));
1660
1661   /* Find seperation between variable name and value */
1662   p = (char *) strchr (arg, '=');
1663   val = (char *) strchr (arg, ' ');
1664
1665   if (p != 0 && val != 0)
1666     {
1667       /* We have both a space and an equals.  If the space is before the
1668          equals, walk forward over the spaces til we see a nonspace 
1669          (possibly the equals). */
1670       if (p > val)
1671         while (*val == ' ')
1672           val++;
1673
1674       /* Now if the = is after the char following the spaces,
1675          take the char following the spaces.  */
1676       if (p > val)
1677         p = val - 1;
1678     }
1679   else if (val != 0 && p == 0)
1680     p = val;
1681
1682   if (p == arg)
1683     error_no_arg (_("environment variable to set"));
1684
1685   if (p == 0 || p[1] == 0)
1686     {
1687       nullset = 1;
1688       if (p == 0)
1689         p = arg + strlen (arg); /* So that savestring below will work */
1690     }
1691   else
1692     {
1693       /* Not setting variable value to null */
1694       val = p + 1;
1695       while (*val == ' ' || *val == '\t')
1696         val++;
1697     }
1698
1699   while (p != arg && (p[-1] == ' ' || p[-1] == '\t'))
1700     p--;
1701
1702   var = savestring (arg, p - arg);
1703   if (nullset)
1704     {
1705       printf_filtered (_("\
1706 Setting environment variable \"%s\" to null value.\n"),
1707                        var);
1708       set_in_environ (inferior_environ, var, "");
1709     }
1710   else
1711     set_in_environ (inferior_environ, var, val);
1712   xfree (var);
1713 }
1714
1715 static void
1716 unset_environment_command (char *var, int from_tty)
1717 {
1718   if (var == 0)
1719     {
1720       /* If there is no argument, delete all environment variables.
1721          Ask for confirmation if reading from the terminal.  */
1722       if (!from_tty || query (_("Delete all environment variables? ")))
1723         {
1724           free_environ (inferior_environ);
1725           inferior_environ = make_environ ();
1726         }
1727     }
1728   else
1729     unset_in_environ (inferior_environ, var);
1730 }
1731
1732 /* Handle the execution path (PATH variable) */
1733
1734 static const char path_var_name[] = "PATH";
1735
1736 static void
1737 path_info (char *args, int from_tty)
1738 {
1739   puts_filtered ("Executable and object file path: ");
1740   puts_filtered (get_in_environ (inferior_environ, path_var_name));
1741   puts_filtered ("\n");
1742 }
1743
1744 /* Add zero or more directories to the front of the execution path.  */
1745
1746 static void
1747 path_command (char *dirname, int from_tty)
1748 {
1749   char *exec_path;
1750   char *env;
1751   dont_repeat ();
1752   env = get_in_environ (inferior_environ, path_var_name);
1753   /* Can be null if path is not set */
1754   if (!env)
1755     env = "";
1756   exec_path = xstrdup (env);
1757   mod_path (dirname, &exec_path);
1758   set_in_environ (inferior_environ, path_var_name, exec_path);
1759   xfree (exec_path);
1760   if (from_tty)
1761     path_info ((char *) NULL, from_tty);
1762 }
1763 \f
1764
1765 /* Print out the machine register regnum. If regnum is -1, print all
1766    registers (print_all == 1) or all non-float and non-vector
1767    registers (print_all == 0).
1768
1769    For most machines, having all_registers_info() print the
1770    register(s) one per line is good enough.  If a different format is
1771    required, (eg, for MIPS or Pyramid 90x, which both have lots of
1772    regs), or there is an existing convention for showing all the
1773    registers, define the architecture method PRINT_REGISTERS_INFO to
1774    provide that format.  */
1775
1776 void
1777 default_print_registers_info (struct gdbarch *gdbarch,
1778                               struct ui_file *file,
1779                               struct frame_info *frame,
1780                               int regnum, int print_all)
1781 {
1782   int i;
1783   const int numregs = gdbarch_num_regs (gdbarch)
1784                       + gdbarch_num_pseudo_regs (gdbarch);
1785   gdb_byte buffer[MAX_REGISTER_SIZE];
1786
1787   for (i = 0; i < numregs; i++)
1788     {
1789       /* Decide between printing all regs, non-float / vector regs, or
1790          specific reg.  */
1791       if (regnum == -1)
1792         {
1793           if (print_all)
1794             {
1795               if (!gdbarch_register_reggroup_p (gdbarch, i, all_reggroup))
1796                 continue;
1797             }
1798           else
1799             {
1800               if (!gdbarch_register_reggroup_p (gdbarch, i, general_reggroup))
1801                 continue;
1802             }
1803         }
1804       else
1805         {
1806           if (i != regnum)
1807             continue;
1808         }
1809
1810       /* If the register name is empty, it is undefined for this
1811          processor, so don't display anything.  */
1812       if (gdbarch_register_name (gdbarch, i) == NULL
1813           || *(gdbarch_register_name (gdbarch, i)) == '\0')
1814         continue;
1815
1816       fputs_filtered (gdbarch_register_name (gdbarch, i), file);
1817       print_spaces_filtered (15 - strlen (gdbarch_register_name
1818                                           (gdbarch, i)), file);
1819
1820       /* Get the data in raw format.  */
1821       if (! frame_register_read (frame, i, buffer))
1822         {
1823           fprintf_filtered (file, "*value not available*\n");
1824           continue;
1825         }
1826
1827       /* If virtual format is floating, print it that way, and in raw
1828          hex.  */
1829       if (TYPE_CODE (register_type (gdbarch, i)) == TYPE_CODE_FLT
1830           || TYPE_CODE (register_type (gdbarch, i)) == TYPE_CODE_DECFLOAT)
1831         {
1832           int j;
1833           struct value_print_options opts;
1834
1835           get_user_print_options (&opts);
1836           opts.deref_ref = 1;
1837           val_print (register_type (gdbarch, i), buffer, 0, 0,
1838                      file, 0, &opts, current_language);
1839
1840           fprintf_filtered (file, "\t(raw 0x");
1841           for (j = 0; j < register_size (gdbarch, i); j++)
1842             {
1843               int idx;
1844               if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
1845                 idx = j;
1846               else
1847                 idx = register_size (gdbarch, i) - 1 - j;
1848               fprintf_filtered (file, "%02x", (unsigned char) buffer[idx]);
1849             }
1850           fprintf_filtered (file, ")");
1851         }
1852       else
1853         {
1854           struct value_print_options opts;
1855
1856           /* Print the register in hex.  */
1857           get_formatted_print_options (&opts, 'x');
1858           opts.deref_ref = 1;
1859           val_print (register_type (gdbarch, i), buffer, 0, 0,
1860                      file, 0, &opts,
1861                      current_language);
1862           /* If not a vector register, print it also according to its
1863              natural format.  */
1864           if (TYPE_VECTOR (register_type (gdbarch, i)) == 0)
1865             {
1866               get_user_print_options (&opts);
1867               opts.deref_ref = 1;
1868               fprintf_filtered (file, "\t");
1869               val_print (register_type (gdbarch, i), buffer, 0, 0,
1870                          file, 0, &opts, current_language);
1871             }
1872         }
1873
1874       fprintf_filtered (file, "\n");
1875     }
1876 }
1877
1878 void
1879 registers_info (char *addr_exp, int fpregs)
1880 {
1881   struct frame_info *frame;
1882   struct gdbarch *gdbarch;
1883   int regnum, numregs;
1884   char *end;
1885
1886   if (!target_has_registers)
1887     error (_("The program has no registers now."));
1888   frame = get_selected_frame (NULL);
1889   gdbarch = get_frame_arch (frame);
1890
1891   if (!addr_exp)
1892     {
1893       gdbarch_print_registers_info (gdbarch, gdb_stdout,
1894                                     frame, -1, fpregs);
1895       return;
1896     }
1897
1898   while (*addr_exp != '\0')
1899     {
1900       char *start;
1901       const char *end;
1902
1903       /* Keep skipping leading white space.  */
1904       if (isspace ((*addr_exp)))
1905         {
1906           addr_exp++;
1907           continue;
1908         }
1909
1910       /* Discard any leading ``$''.  Check that there is something
1911          resembling a register following it.  */
1912       if (addr_exp[0] == '$')
1913         addr_exp++;
1914       if (isspace ((*addr_exp)) || (*addr_exp) == '\0')
1915         error (_("Missing register name"));
1916
1917       /* Find the start/end of this register name/num/group.  */
1918       start = addr_exp;
1919       while ((*addr_exp) != '\0' && !isspace ((*addr_exp)))
1920         addr_exp++;
1921       end = addr_exp;
1922
1923       /* Figure out what we've found and display it.  */
1924
1925       /* A register name?  */
1926       {
1927         int regnum = user_reg_map_name_to_regnum (gdbarch, start, end - start);
1928         if (regnum >= 0)
1929           {
1930             /* User registers lie completely outside of the range of
1931                normal registers.  Catch them early so that the target
1932                never sees them.  */
1933             if (regnum >= gdbarch_num_regs (gdbarch)
1934                           + gdbarch_num_pseudo_regs (gdbarch))
1935               {
1936                 struct value_print_options opts;
1937                 struct value *val = value_of_user_reg (regnum, frame);
1938
1939                 printf_filtered ("%s: ", start);
1940                 get_formatted_print_options (&opts, 'x');
1941                 print_scalar_formatted (value_contents (val),
1942                                         check_typedef (value_type (val)),
1943                                         &opts, 0, gdb_stdout);
1944                 printf_filtered ("\n");
1945               }
1946             else
1947               gdbarch_print_registers_info (gdbarch, gdb_stdout,
1948                                             frame, regnum, fpregs);
1949             continue;
1950           }
1951       }
1952
1953       /* A register group?  */
1954       {
1955         struct reggroup *group;
1956         for (group = reggroup_next (gdbarch, NULL);
1957              group != NULL;
1958              group = reggroup_next (gdbarch, group))
1959           {
1960             /* Don't bother with a length check.  Should the user
1961                enter a short register group name, go with the first
1962                group that matches.  */
1963             if (strncmp (start, reggroup_name (group), end - start) == 0)
1964               break;
1965           }
1966         if (group != NULL)
1967           {
1968             int regnum;
1969             for (regnum = 0;
1970                  regnum < gdbarch_num_regs (gdbarch)
1971                           + gdbarch_num_pseudo_regs (gdbarch);
1972                  regnum++)
1973               {
1974                 if (gdbarch_register_reggroup_p (gdbarch, regnum, group))
1975                   gdbarch_print_registers_info (gdbarch,
1976                                                 gdb_stdout, frame,
1977                                                 regnum, fpregs);
1978               }
1979             continue;
1980           }
1981       }
1982
1983       /* Nothing matched.  */
1984       error (_("Invalid register `%.*s'"), (int) (end - start), start);
1985     }
1986 }
1987
1988 void
1989 all_registers_info (char *addr_exp, int from_tty)
1990 {
1991   registers_info (addr_exp, 1);
1992 }
1993
1994 static void
1995 nofp_registers_info (char *addr_exp, int from_tty)
1996 {
1997   registers_info (addr_exp, 0);
1998 }
1999
2000 static void
2001 print_vector_info (struct gdbarch *gdbarch, struct ui_file *file,
2002                    struct frame_info *frame, const char *args)
2003 {
2004   if (gdbarch_print_vector_info_p (gdbarch))
2005     gdbarch_print_vector_info (gdbarch, file, frame, args);
2006   else
2007     {
2008       int regnum;
2009       int printed_something = 0;
2010
2011       for (regnum = 0;
2012            regnum < gdbarch_num_regs (gdbarch)
2013                     + gdbarch_num_pseudo_regs (gdbarch);
2014            regnum++)
2015         {
2016           if (gdbarch_register_reggroup_p (gdbarch, regnum, vector_reggroup))
2017             {
2018               printed_something = 1;
2019               gdbarch_print_registers_info (gdbarch, file, frame, regnum, 1);
2020             }
2021         }
2022       if (!printed_something)
2023         fprintf_filtered (file, "No vector information\n");
2024     }
2025 }
2026
2027 static void
2028 vector_info (char *args, int from_tty)
2029 {
2030   if (!target_has_registers)
2031     error (_("The program has no registers now."));
2032
2033   print_vector_info (current_gdbarch, gdb_stdout,
2034                      get_selected_frame (NULL), args);
2035 }
2036 \f
2037
2038 /* Used in `attach&' command.  ARG is a point to an integer
2039    representing a process id.  Proceed threads of this process iff
2040    they stopped due to debugger request, and when they did, they
2041    reported a clean stop (TARGET_SIGNAL_0).  Do not proceed threads
2042    that have been explicitly been told to stop.  */
2043
2044 static int
2045 proceed_after_attach_callback (struct thread_info *thread,
2046                                void *arg)
2047 {
2048   int pid = * (int *) arg;
2049
2050   if (ptid_get_pid (thread->ptid) == pid
2051       && !is_exited (thread->ptid)
2052       && !is_executing (thread->ptid)
2053       && !thread->stop_requested
2054       && thread->stop_signal == TARGET_SIGNAL_0)
2055     {
2056       switch_to_thread (thread->ptid);
2057       clear_proceed_status ();
2058       proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
2059     }
2060
2061   return 0;
2062 }
2063
2064 static void
2065 proceed_after_attach (int pid)
2066 {
2067   /* Don't error out if the current thread is running, because
2068      there may be other stopped threads.  */
2069   struct cleanup *old_chain;
2070
2071   /* Backup current thread and selected frame.  */
2072   old_chain = make_cleanup_restore_current_thread ();
2073
2074   iterate_over_threads (proceed_after_attach_callback, &pid);
2075
2076   /* Restore selected ptid.  */
2077   do_cleanups (old_chain);
2078 }
2079
2080 /*
2081  * TODO:
2082  * Should save/restore the tty state since it might be that the
2083  * program to be debugged was started on this tty and it wants
2084  * the tty in some state other than what we want.  If it's running
2085  * on another terminal or without a terminal, then saving and
2086  * restoring the tty state is a harmless no-op.
2087  * This only needs to be done if we are attaching to a process.
2088  */
2089
2090 /*
2091    attach_command --
2092    takes a program started up outside of gdb and ``attaches'' to it.
2093    This stops it cold in its tracks and allows us to start debugging it.
2094    and wait for the trace-trap that results from attaching.  */
2095
2096 static void
2097 attach_command_post_wait (char *args, int from_tty, int async_exec)
2098 {
2099   char *exec_file;
2100   char *full_exec_path = NULL;
2101   struct inferior *inferior;
2102
2103   inferior = current_inferior ();
2104   inferior->stop_soon = NO_STOP_QUIETLY;
2105
2106   /* If no exec file is yet known, try to determine it from the
2107      process itself.  */
2108   exec_file = (char *) get_exec_file (0);
2109   if (!exec_file)
2110     {
2111       exec_file = target_pid_to_exec_file (PIDGET (inferior_ptid));
2112       if (exec_file)
2113         {
2114           /* It's possible we don't have a full path, but rather just a
2115              filename.  Some targets, such as HP-UX, don't provide the
2116              full path, sigh.
2117
2118              Attempt to qualify the filename against the source path.
2119              (If that fails, we'll just fall back on the original
2120              filename.  Not much more we can do...)
2121            */
2122           if (!source_full_path_of (exec_file, &full_exec_path))
2123             full_exec_path = savestring (exec_file, strlen (exec_file));
2124
2125           exec_file_attach (full_exec_path, from_tty);
2126           symbol_file_add_main (full_exec_path, from_tty);
2127         }
2128     }
2129   else
2130     {
2131       reopen_exec_file ();
2132       reread_symbols ();
2133     }
2134
2135   /* Take any necessary post-attaching actions for this platform.  */
2136   target_post_attach (PIDGET (inferior_ptid));
2137
2138   post_create_inferior (&current_target, from_tty);
2139
2140   /* Install inferior's terminal modes.  */
2141   target_terminal_inferior ();
2142
2143   if (async_exec)
2144     {
2145       /* The user requested an `attach&', so be sure to leave threads
2146          that didn't get a signal running.  */
2147
2148       /* Immediatelly resume all suspended threads of this inferior,
2149          and this inferior only.  This should have no effect on
2150          already running threads.  If a thread has been stopped with a
2151          signal, leave it be.  */
2152       if (non_stop)
2153         proceed_after_attach (inferior->pid);
2154       else
2155         {
2156           if (inferior_thread ()->stop_signal == TARGET_SIGNAL_0)
2157             {
2158               clear_proceed_status ();
2159               proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
2160             }
2161         }
2162     }
2163   else
2164     {
2165       /* The user requested a plain `attach', so be sure to leave
2166          the inferior stopped.  */
2167
2168       if (target_can_async_p ())
2169         async_enable_stdin ();
2170
2171       /* At least the current thread is already stopped.  */
2172
2173       /* In all-stop, by definition, all threads have to be already
2174          stopped at this point.  In non-stop, however, although the
2175          selected thread is stopped, others may still be executing.
2176          Be sure to explicitly stop all threads of the process.  This
2177          should have no effect on already stopped threads.  */
2178       if (non_stop)
2179         target_stop (pid_to_ptid (inferior->pid));
2180
2181       /* Tell the user/frontend where we're stopped.  */
2182       normal_stop ();
2183       if (deprecated_attach_hook)
2184         deprecated_attach_hook ();
2185     }
2186 }
2187
2188 struct attach_command_continuation_args
2189 {
2190   char *args;
2191   int from_tty;
2192   int async_exec;
2193 };
2194
2195 static void
2196 attach_command_continuation (void *args)
2197 {
2198   struct attach_command_continuation_args *a = args;
2199   attach_command_post_wait (a->args, a->from_tty, a->async_exec);
2200 }
2201
2202 static void
2203 attach_command_continuation_free_args (void *args)
2204 {
2205   struct attach_command_continuation_args *a = args;
2206   xfree (a->args);
2207   xfree (a);
2208 }
2209
2210 void
2211 attach_command (char *args, int from_tty)
2212 {
2213   char *exec_file;
2214   char *full_exec_path = NULL;
2215   int async_exec = 0;
2216   struct cleanup *back_to = make_cleanup (null_cleanup, NULL);
2217
2218   dont_repeat ();               /* Not for the faint of heart */
2219
2220   if (target_supports_multi_process ())
2221     /* Don't complain if we can be attached to multiple processes.  */
2222     ;
2223   else if (target_has_execution)
2224     {
2225       if (query (_("A program is being debugged already.  Kill it? ")))
2226         target_kill ();
2227       else
2228         error (_("Not killed."));
2229     }
2230
2231   /* Clean up any leftovers from other runs.  Some other things from
2232      this function should probably be moved into target_pre_inferior.  */
2233   target_pre_inferior (from_tty);
2234
2235   if (non_stop && !target_supports_non_stop ())
2236     error (_("Cannot attach to this target in non-stop mode"));
2237
2238   if (args)
2239     {
2240       async_exec = strip_bg_char (&args);
2241
2242       /* If we get a request for running in the bg but the target
2243          doesn't support it, error out. */
2244       if (async_exec && !target_can_async_p ())
2245         error (_("Asynchronous execution not supported on this target."));
2246     }
2247
2248   /* If we don't get a request of running in the bg, then we need
2249      to simulate synchronous (fg) execution.  */
2250   if (!async_exec && target_can_async_p ())
2251     {
2252       /* Simulate synchronous execution */
2253       async_disable_stdin ();
2254       make_cleanup ((make_cleanup_ftype *)async_enable_stdin, NULL);
2255     }
2256
2257   target_attach (args, from_tty);
2258
2259   /* Set up the "saved terminal modes" of the inferior
2260      based on what modes we are starting it with.  */
2261   target_terminal_init ();
2262
2263   /* Set up execution context to know that we should return from
2264      wait_for_inferior as soon as the target reports a stop.  */
2265   init_wait_for_inferior ();
2266   clear_proceed_status ();
2267
2268   if (non_stop)
2269     {
2270       /* If we find that the current thread isn't stopped, explicitly
2271          do so now, because we're going to install breakpoints and
2272          poke at memory.  */
2273
2274       if (async_exec)
2275         /* The user requested an `attach&'; stop just one thread.  */
2276         target_stop (inferior_ptid);
2277       else
2278         /* The user requested an `attach', so stop all threads of this
2279            inferior.  */
2280         target_stop (pid_to_ptid (ptid_get_pid (inferior_ptid)));
2281     }
2282
2283   /* Some system don't generate traps when attaching to inferior.
2284      E.g. Mach 3 or GNU hurd.  */
2285   if (!target_attach_no_wait)
2286     {
2287       struct inferior *inferior = current_inferior ();
2288
2289       /* Careful here. See comments in inferior.h.  Basically some
2290          OSes don't ignore SIGSTOPs on continue requests anymore.  We
2291          need a way for handle_inferior_event to reset the stop_signal
2292          variable after an attach, and this is what
2293          STOP_QUIETLY_NO_SIGSTOP is for.  */
2294       inferior->stop_soon = STOP_QUIETLY_NO_SIGSTOP;
2295
2296       if (target_can_async_p ())
2297         {
2298           /* sync_execution mode.  Wait for stop.  */
2299           struct attach_command_continuation_args *a;
2300
2301           a = xmalloc (sizeof (*a));
2302           a->args = xstrdup (args);
2303           a->from_tty = from_tty;
2304           a->async_exec = async_exec;
2305           add_inferior_continuation (attach_command_continuation, a,
2306                                      attach_command_continuation_free_args);
2307           discard_cleanups (back_to);
2308           return;
2309         }
2310
2311       wait_for_inferior (0);
2312     }
2313
2314   attach_command_post_wait (args, from_tty, async_exec);
2315   discard_cleanups (back_to);
2316 }
2317
2318 /* We had just found out that the target was already attached to an
2319    inferior.  PTID points at a thread of this new inferior, that is
2320    the most likely to be stopped right now, but not necessarily so.
2321    The new inferior is assumed to be already added to the inferior
2322    list at this point.  If LEAVE_RUNNING, then leave the threads of
2323    this inferior running, except those we've explicitly seen reported
2324    as stopped.  */
2325
2326 void
2327 notice_new_inferior (ptid_t ptid, int leave_running, int from_tty)
2328 {
2329   struct cleanup* old_chain;
2330   int async_exec;
2331
2332   old_chain = make_cleanup (null_cleanup, NULL);
2333
2334   /* If in non-stop, leave threads as running as they were.  If
2335      they're stopped for some reason other than us telling it to, the
2336      target reports a signal != TARGET_SIGNAL_0.  We don't try to
2337      resume threads with such a stop signal.  */
2338   async_exec = non_stop;
2339
2340   if (!ptid_equal (inferior_ptid, null_ptid))
2341     make_cleanup_restore_current_thread ();
2342
2343   switch_to_thread (ptid);
2344
2345   /* When we "notice" a new inferior we need to do all the things we
2346      would normally do if we had just attached to it.  */
2347
2348   if (is_executing (inferior_ptid))
2349     {
2350       struct inferior *inferior = current_inferior ();
2351
2352       /* We're going to install breakpoints, and poke at memory,
2353          ensure that the inferior is stopped for a moment while we do
2354          that.  */
2355       target_stop (inferior_ptid);
2356
2357       inferior->stop_soon = STOP_QUIETLY_REMOTE;
2358
2359       /* Wait for stop before proceeding.  */
2360       if (target_can_async_p ())
2361         {
2362           struct attach_command_continuation_args *a;
2363
2364           a = xmalloc (sizeof (*a));
2365           a->args = xstrdup ("");
2366           a->from_tty = from_tty;
2367           a->async_exec = async_exec;
2368           add_inferior_continuation (attach_command_continuation, a,
2369                                      attach_command_continuation_free_args);
2370
2371           do_cleanups (old_chain);
2372           return;
2373         }
2374       else
2375         wait_for_inferior (0);
2376     }
2377
2378   async_exec = leave_running;
2379   attach_command_post_wait ("" /* args */, from_tty, async_exec);
2380
2381   do_cleanups (old_chain);
2382 }
2383
2384 /*
2385  * detach_command --
2386  * takes a program previously attached to and detaches it.
2387  * The program resumes execution and will no longer stop
2388  * on signals, etc.  We better not have left any breakpoints
2389  * in the program or it'll die when it hits one.  For this
2390  * to work, it may be necessary for the process to have been
2391  * previously attached.  It *might* work if the program was
2392  * started via the normal ptrace (PTRACE_TRACEME).
2393  */
2394
2395 void
2396 detach_command (char *args, int from_tty)
2397 {
2398   dont_repeat ();               /* Not for the faint of heart.  */
2399
2400   if (ptid_equal (inferior_ptid, null_ptid))
2401     error (_("The program is not being run."));
2402
2403   target_detach (args, from_tty);
2404
2405   /* If the solist is global across inferiors, don't clear it when we
2406      detach from a single inferior.  */
2407   if (!gdbarch_has_global_solist (target_gdbarch))
2408     no_shared_libraries (NULL, from_tty);
2409
2410   /* If the current target interface claims there's still execution,
2411      then don't mess with threads of other processes.  */
2412   if (!target_has_execution)
2413     init_thread_list ();
2414
2415   if (deprecated_detach_hook)
2416     deprecated_detach_hook ();
2417 }
2418
2419 /* Disconnect from the current target without resuming it (leaving it
2420    waiting for a debugger).
2421
2422    We'd better not have left any breakpoints in the program or the
2423    next debugger will get confused.  Currently only supported for some
2424    remote targets, since the normal attach mechanisms don't work on
2425    stopped processes on some native platforms (e.g. GNU/Linux).  */
2426
2427 static void
2428 disconnect_command (char *args, int from_tty)
2429 {
2430   dont_repeat ();               /* Not for the faint of heart */
2431   target_disconnect (args, from_tty);
2432   no_shared_libraries (NULL, from_tty);
2433   init_thread_list ();
2434   if (deprecated_detach_hook)
2435     deprecated_detach_hook ();
2436 }
2437
2438 void 
2439 interrupt_target_1 (int all_threads)
2440 {
2441   ptid_t ptid;
2442   if (all_threads)
2443     ptid = minus_one_ptid;
2444   else
2445     ptid = inferior_ptid;
2446   target_stop (ptid);
2447
2448   /* Tag the thread as having been explicitly requested to stop, so
2449      other parts of gdb know not to resume this thread automatically,
2450      if it was stopped due to an internal event.  Limit this to
2451      non-stop mode, as when debugging a multi-threaded application in
2452      all-stop mode, we will only get one stop event --- it's undefined
2453      which thread will report the event.  */
2454   if (non_stop)
2455     set_stop_requested (ptid, 1);
2456 }
2457
2458 /* Stop the execution of the target while running in async mode, in
2459    the backgound.  In all-stop, stop the whole process.  In non-stop
2460    mode, stop the current thread only by default, or stop all threads
2461    if the `-a' switch is used.  */
2462
2463 /* interrupt [-a]  */
2464 void
2465 interrupt_target_command (char *args, int from_tty)
2466 {
2467   if (target_can_async_p ())
2468     {
2469       int all_threads = 0;
2470
2471       dont_repeat ();           /* Not for the faint of heart */
2472
2473       if (args != NULL
2474           && strncmp (args, "-a", sizeof ("-a") - 1) == 0)
2475         all_threads = 1;
2476
2477       if (!non_stop && all_threads)
2478         error (_("-a is meaningless in all-stop mode."));
2479
2480       interrupt_target_1 (all_threads);
2481     }
2482 }
2483
2484 static void
2485 print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
2486                   struct frame_info *frame, const char *args)
2487 {
2488   if (gdbarch_print_float_info_p (gdbarch))
2489     gdbarch_print_float_info (gdbarch, file, frame, args);
2490   else
2491     {
2492       int regnum;
2493       int printed_something = 0;
2494
2495       for (regnum = 0;
2496            regnum < gdbarch_num_regs (gdbarch)
2497                     + gdbarch_num_pseudo_regs (gdbarch);
2498            regnum++)
2499         {
2500           if (gdbarch_register_reggroup_p (gdbarch, regnum, float_reggroup))
2501             {
2502               printed_something = 1;
2503               gdbarch_print_registers_info (gdbarch, file, frame, regnum, 1);
2504             }
2505         }
2506       if (!printed_something)
2507         fprintf_filtered (file, "\
2508 No floating-point info available for this processor.\n");
2509     }
2510 }
2511
2512 static void
2513 float_info (char *args, int from_tty)
2514 {
2515   if (!target_has_registers)
2516     error (_("The program has no registers now."));
2517
2518   print_float_info (current_gdbarch, gdb_stdout, 
2519                     get_selected_frame (NULL), args);
2520 }
2521 \f
2522 static void
2523 unset_command (char *args, int from_tty)
2524 {
2525   printf_filtered (_("\
2526 \"unset\" must be followed by the name of an unset subcommand.\n"));
2527   help_list (unsetlist, "unset ", -1, gdb_stdout);
2528 }
2529
2530 void
2531 _initialize_infcmd (void)
2532 {
2533   struct cmd_list_element *c = NULL;
2534
2535   /* add the filename of the terminal connected to inferior I/O */
2536   add_setshow_filename_cmd ("inferior-tty", class_run,
2537                             &inferior_io_terminal, _("\
2538 Set terminal for future runs of program being debugged."), _("\
2539 Show terminal for future runs of program being debugged."), _("\
2540 Usage: set inferior-tty /dev/pts/1"), NULL, NULL, &setlist, &showlist);
2541   add_com_alias ("tty", "set inferior-tty", class_alias, 0);
2542
2543   add_setshow_optional_filename_cmd ("args", class_run,
2544                                      &inferior_args, _("\
2545 Set argument list to give program being debugged when it is started."), _("\
2546 Show argument list to give program being debugged when it is started."), _("\
2547 Follow this command with any number of args, to be passed to the program."),
2548                                      notice_args_set,
2549                                      notice_args_read,
2550                                      &setlist, &showlist);
2551
2552   c = add_cmd ("environment", no_class, environment_info, _("\
2553 The environment to give the program, or one variable's value.\n\
2554 With an argument VAR, prints the value of environment variable VAR to\n\
2555 give the program being debugged.  With no arguments, prints the entire\n\
2556 environment to be given to the program."), &showlist);
2557   set_cmd_completer (c, noop_completer);
2558
2559   add_prefix_cmd ("unset", no_class, unset_command,
2560                   _("Complement to certain \"set\" commands."),
2561                   &unsetlist, "unset ", 0, &cmdlist);
2562
2563   c = add_cmd ("environment", class_run, unset_environment_command, _("\
2564 Cancel environment variable VAR for the program.\n\
2565 This does not affect the program until the next \"run\" command."),
2566                &unsetlist);
2567   set_cmd_completer (c, noop_completer);
2568
2569   c = add_cmd ("environment", class_run, set_environment_command, _("\
2570 Set environment variable value to give the program.\n\
2571 Arguments are VAR VALUE where VAR is variable name and VALUE is value.\n\
2572 VALUES of environment variables are uninterpreted strings.\n\
2573 This does not affect the program until the next \"run\" command."),
2574                &setlist);
2575   set_cmd_completer (c, noop_completer);
2576
2577   c = add_com ("path", class_files, path_command, _("\
2578 Add directory DIR(s) to beginning of search path for object files.\n\
2579 $cwd in the path means the current working directory.\n\
2580 This path is equivalent to the $PATH shell variable.  It is a list of\n\
2581 directories, separated by colons.  These directories are searched to find\n\
2582 fully linked executable files and separately compiled object files as needed."));
2583   set_cmd_completer (c, filename_completer);
2584
2585   c = add_cmd ("paths", no_class, path_info, _("\
2586 Current search path for finding object files.\n\
2587 $cwd in the path means the current working directory.\n\
2588 This path is equivalent to the $PATH shell variable.  It is a list of\n\
2589 directories, separated by colons.  These directories are searched to find\n\
2590 fully linked executable files and separately compiled object files as needed."),
2591                &showlist);
2592   set_cmd_completer (c, noop_completer);
2593
2594   add_com ("attach", class_run, attach_command, _("\
2595 Attach to a process or file outside of GDB.\n\
2596 This command attaches to another target, of the same type as your last\n\
2597 \"target\" command (\"info files\" will show your target stack).\n\
2598 The command may take as argument a process id or a device file.\n\
2599 For a process id, you must have permission to send the process a signal,\n\
2600 and it must have the same effective uid as the debugger.\n\
2601 When using \"attach\" with a process id, the debugger finds the\n\
2602 program running in the process, looking first in the current working\n\
2603 directory, or (if not found there) using the source file search path\n\
2604 (see the \"directory\" command).  You can also use the \"file\" command\n\
2605 to specify the program, and to load its symbol table."));
2606
2607   add_prefix_cmd ("detach", class_run, detach_command, _("\
2608 Detach a process or file previously attached.\n\
2609 If a process, it is no longer traced, and it continues its execution.  If\n\
2610 you were debugging a file, the file is closed and gdb no longer accesses it."),
2611                   &detachlist, "detach ", 0, &cmdlist);
2612
2613   add_com ("disconnect", class_run, disconnect_command, _("\
2614 Disconnect from a target.\n\
2615 The target will wait for another debugger to connect.  Not available for\n\
2616 all targets."));
2617
2618   add_com ("signal", class_run, signal_command, _("\
2619 Continue program giving it signal specified by the argument.\n\
2620 An argument of \"0\" means continue program without giving it a signal."));
2621
2622   add_com ("stepi", class_run, stepi_command, _("\
2623 Step one instruction exactly.\n\
2624 Argument N means do this N times (or till program stops for another reason)."));
2625   add_com_alias ("si", "stepi", class_alias, 0);
2626
2627   add_com ("nexti", class_run, nexti_command, _("\
2628 Step one instruction, but proceed through subroutine calls.\n\
2629 Argument N means do this N times (or till program stops for another reason)."));
2630   add_com_alias ("ni", "nexti", class_alias, 0);
2631
2632   add_com ("finish", class_run, finish_command, _("\
2633 Execute until selected stack frame returns.\n\
2634 Upon return, the value returned is printed and put in the value history."));
2635   add_com_alias ("fin", "finish", class_run, 1);
2636
2637   add_com ("next", class_run, next_command, _("\
2638 Step program, proceeding through subroutine calls.\n\
2639 Like the \"step\" command as long as subroutine calls do not happen;\n\
2640 when they do, the call is treated as one instruction.\n\
2641 Argument N means do this N times (or till program stops for another reason)."));
2642   add_com_alias ("n", "next", class_run, 1);
2643   if (xdb_commands)
2644     add_com_alias ("S", "next", class_run, 1);
2645
2646   add_com ("step", class_run, step_command, _("\
2647 Step program until it reaches a different source line.\n\
2648 Argument N means do this N times (or till program stops for another reason)."));
2649   add_com_alias ("s", "step", class_run, 1);
2650
2651   c = add_com ("until", class_run, until_command, _("\
2652 Execute until the program reaches a source line greater than the current\n\
2653 or a specified location (same args as break command) within the current frame."));
2654   set_cmd_completer (c, location_completer);
2655   add_com_alias ("u", "until", class_run, 1);
2656
2657   c = add_com ("advance", class_run, advance_command, _("\
2658 Continue the program up to the given location (same form as args for break command).\n\
2659 Execution will also stop upon exit from the current stack frame."));
2660   set_cmd_completer (c, location_completer);
2661
2662   c = add_com ("jump", class_run, jump_command, _("\
2663 Continue program being debugged at specified line or address.\n\
2664 Give as argument either LINENUM or *ADDR, where ADDR is an expression\n\
2665 for an address to start at."));
2666   set_cmd_completer (c, location_completer);
2667
2668   if (xdb_commands)
2669     {
2670       c = add_com ("go", class_run, go_command, _("\
2671 Usage: go <location>\n\
2672 Continue program being debugged, stopping at specified line or \n\
2673 address.\n\
2674 Give as argument either LINENUM or *ADDR, where ADDR is an \n\
2675 expression for an address to start at.\n\
2676 This command is a combination of tbreak and jump."));
2677       set_cmd_completer (c, location_completer);
2678     }
2679
2680   if (xdb_commands)
2681     add_com_alias ("g", "go", class_run, 1);
2682
2683   c = add_com ("continue", class_run, continue_command, _("\
2684 Continue program being debugged, after signal or breakpoint.\n\
2685 If proceeding from breakpoint, a number N may be used as an argument,\n\
2686 which means to set the ignore count of that breakpoint to N - 1 (so that\n\
2687 the breakpoint won't break until the Nth time it is reached).\n\
2688 \n\
2689 If non-stop mode is enabled, continue only the current thread,\n\
2690 otherwise all the threads in the program are continued.  To \n\
2691 continue all stopped threads in non-stop mode, use the -a option.\n\
2692 Specifying -a and an ignore count simultaneously is an error."));
2693   add_com_alias ("c", "cont", class_run, 1);
2694   add_com_alias ("fg", "cont", class_run, 1);
2695
2696   c = add_com ("run", class_run, run_command, _("\
2697 Start debugged program.  You may specify arguments to give it.\n\
2698 Args may include \"*\", or \"[...]\"; they are expanded using \"sh\".\n\
2699 Input and output redirection with \">\", \"<\", or \">>\" are also allowed.\n\n\
2700 With no arguments, uses arguments last specified (with \"run\" or \"set args\").\n\
2701 To cancel previous arguments and run with no arguments,\n\
2702 use \"set args\" without arguments."));
2703   set_cmd_completer (c, filename_completer);
2704   add_com_alias ("r", "run", class_run, 1);
2705   if (xdb_commands)
2706     add_com ("R", class_run, run_no_args_command,
2707              _("Start debugged program with no arguments."));
2708
2709   c = add_com ("start", class_run, start_command, _("\
2710 Run the debugged program until the beginning of the main procedure.\n\
2711 You may specify arguments to give to your program, just as with the\n\
2712 \"run\" command."));
2713   set_cmd_completer (c, filename_completer);
2714
2715   c = add_com ("interrupt", class_run, interrupt_target_command,
2716                _("Interrupt the execution of the debugged program.\n\
2717 If non-stop mode is enabled, interrupt only the current thread,\n\
2718 otherwise all the threads in the program are stopped.  To \n\
2719 interrupt all running threads in non-stop mode, use the -a option."));
2720
2721   add_info ("registers", nofp_registers_info, _("\
2722 List of integer registers and their contents, for selected stack frame.\n\
2723 Register name as argument means describe only that register."));
2724   add_info_alias ("r", "registers", 1);
2725
2726   if (xdb_commands)
2727     add_com ("lr", class_info, nofp_registers_info, _("\
2728 List of integer registers and their contents, for selected stack frame.\n\
2729 Register name as argument means describe only that register."));
2730   add_info ("all-registers", all_registers_info, _("\
2731 List of all registers and their contents, for selected stack frame.\n\
2732 Register name as argument means describe only that register."));
2733
2734   add_info ("program", program_info,
2735             _("Execution status of the program."));
2736
2737   add_info ("float", float_info,
2738             _("Print the status of the floating point unit\n"));
2739
2740   add_info ("vector", vector_info,
2741             _("Print the status of the vector unit\n"));
2742
2743   inferior_environ = make_environ ();
2744   init_environ (inferior_environ);
2745 }