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