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