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