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