1 /* Multi-process control for GDB, the GNU debugger.
3 Copyright (C) 2008-2021 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
25 #include "completer.h"
27 #include "gdbthread.h"
29 #include "observable.h"
32 #include "gdbsupport/environ.h"
33 #include "cli/cli-utils.h"
34 #include "arch-utils.h"
35 #include "target-descriptions.h"
36 #include "readline/tilde.h"
37 #include "progspace-and-thread.h"
39 /* Keep a registry of per-inferior data-pointers required by other GDB
42 DEFINE_REGISTRY (inferior, REGISTRY_ACCESS_FIELD)
44 struct inferior *inferior_list = NULL;
45 static int highest_inferior_num;
48 bool print_inferior_events = true;
50 /* The Current Inferior. This is a strong reference. I.e., whenever
51 an inferior is the current inferior, its refcount is
53 static inferior_ref current_inferior_;
56 current_inferior (void)
58 return current_inferior_.get ();
62 set_current_inferior (struct inferior *inf)
64 /* There's always an inferior. */
65 gdb_assert (inf != NULL);
67 current_inferior_ = inferior_ref::new_reference (inf);
70 private_inferior::~private_inferior () = default;
72 inferior::~inferior ()
76 m_continuations.clear ();
77 inferior_free_data (inf);
78 target_desc_info_free (inf->tdesc_info);
81 inferior::inferior (int pid_)
82 : num (++highest_inferior_num),
84 environment (gdb_environ::from_host_environ ()),
87 inferior_alloc_data (this);
89 m_target_stack.push (get_dummy_target ());
93 inferior::set_tty (const char *terminal_name)
95 if (terminal_name != nullptr && *terminal_name != '\0')
96 m_terminal = make_unique_xstrdup (terminal_name);
104 return m_terminal.get ();
108 inferior::add_continuation (std::function<void ()> &&cont)
110 m_continuations.emplace_front (std::move (cont));
114 inferior::do_all_continuations ()
116 while (!m_continuations.empty ())
118 auto iter = m_continuations.begin ();
120 m_continuations.erase (iter);
125 add_inferior_silent (int pid)
127 inferior *inf = new inferior (pid);
129 if (inferior_list == NULL)
135 for (last = inferior_list; last->next != NULL; last = last->next)
140 gdb::observers::inferior_added.notify (inf);
143 inferior_appeared (inf, pid);
149 add_inferior (int pid)
151 struct inferior *inf = add_inferior_silent (pid);
153 if (print_inferior_events)
156 printf_unfiltered (_("[New inferior %d (%s)]\n"),
158 target_pid_to_str (ptid_t (pid)).c_str ());
160 printf_unfiltered (_("[New inferior %d]\n"), inf->num);
167 delete_inferior (struct inferior *todel)
169 struct inferior *inf, *infprev;
173 for (inf = inferior_list; inf; infprev = inf, inf = inf->next)
180 for (thread_info *tp : inf->threads_safe ())
181 delete_thread_silent (tp);
184 infprev->next = inf->next;
186 inferior_list = inf->next;
188 gdb::observers::inferior_removed.notify (inf);
190 /* If this program space is rendered useless, remove it. */
191 if (inf->pspace->empty ())
197 /* If SILENT then be quiet -- don't announce a inferior exit, or the
198 exit of its threads. */
201 exit_inferior_1 (struct inferior *inftoex, int silent)
203 struct inferior *inf;
205 for (inf = inferior_list; inf; inf = inf->next)
212 for (thread_info *tp : inf->threads_safe ())
215 delete_thread_silent (tp);
220 gdb::observers::inferior_exit.notify (inf);
223 inf->fake_pid_p = false;
226 if (inf->vfork_parent != NULL)
228 inf->vfork_parent->vfork_child = NULL;
229 inf->vfork_parent = NULL;
231 if (inf->vfork_child != NULL)
233 inf->vfork_child->vfork_parent = NULL;
234 inf->vfork_child = NULL;
237 inf->pending_detach = 0;
239 inf->control = inferior_control_state (NO_STOP_QUIETLY);
241 /* Clear the register cache and the frame cache. */
242 registers_changed ();
243 reinit_frame_cache ();
247 exit_inferior (inferior *inf)
249 exit_inferior_1 (inf, 0);
253 exit_inferior_silent (inferior *inf)
255 exit_inferior_1 (inf, 1);
258 /* See inferior.h. */
261 detach_inferior (inferior *inf)
263 /* Save the pid, since exit_inferior_1 will reset it. */
266 exit_inferior_1 (inf, 0);
268 if (print_inferior_events)
269 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
271 target_pid_to_str (ptid_t (pid)).c_str ());
275 inferior_appeared (struct inferior *inf, int pid)
277 /* If this is the first inferior with threads, reset the global
279 delete_exited_threads ();
280 if (!any_thread_p ())
284 inf->has_exit_code = 0;
287 gdb::observers::inferior_appeared.notify (inf);
291 find_inferior_id (int num)
293 for (inferior *inf : all_inferiors ())
301 find_inferior_pid (process_stratum_target *targ, int pid)
303 /* Looking for inferior pid == 0 is always wrong, and indicative of
304 a bug somewhere else. There may be more than one with pid == 0,
306 gdb_assert (pid != 0);
308 for (inferior *inf : all_inferiors (targ))
318 find_inferior_ptid (process_stratum_target *targ, ptid_t ptid)
320 return find_inferior_pid (targ, ptid.pid ());
323 /* See inferior.h. */
326 find_inferior_for_program_space (struct program_space *pspace)
328 struct inferior *cur_inf = current_inferior ();
330 if (cur_inf->pspace == pspace)
333 for (inferior *inf : all_inferiors ())
334 if (inf->pspace == pspace)
341 have_inferiors (void)
343 for (inferior *inf ATTRIBUTE_UNUSED : all_non_exited_inferiors ())
349 /* Return the number of live inferiors. We account for the case
350 where an inferior might have a non-zero pid but no threads, as
351 in the middle of a 'mourn' operation. */
354 number_of_live_inferiors (process_stratum_target *proc_target)
358 for (inferior *inf : all_non_exited_inferiors (proc_target))
359 if (inf->has_execution ())
360 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
362 /* Found a live thread in this inferior, go to the next
371 /* Return true if there is at least one live inferior. */
374 have_live_inferiors (void)
376 return number_of_live_inferiors (NULL) > 0;
379 /* Prune away any unused inferiors, and then prune away no longer used
383 prune_inferiors (void)
390 if (!ss->deletable ()
398 inferior *ss_next = ss->next;
399 delete_inferior (ss);
404 /* Simply returns the count of inferiors. */
407 number_of_inferiors (void)
409 auto rng = all_inferiors ();
410 return std::distance (rng.begin (), rng.end ());
413 /* Converts an inferior process id to a string. Like
414 target_pid_to_str, but special cases the null process. */
417 inferior_pid_to_str (int pid)
420 return target_pid_to_str (ptid_t (pid));
425 /* See inferior.h. */
428 print_selected_inferior (struct ui_out *uiout)
430 struct inferior *inf = current_inferior ();
431 const char *filename = inf->pspace->exec_filename.get ();
433 if (filename == NULL)
434 filename = _("<noexec>");
436 uiout->message (_("[Switching to inferior %d [%s] (%s)]\n"),
437 inf->num, inferior_pid_to_str (inf->pid).c_str (), filename);
440 /* Helper for print_inferior. Returns the 'connection-id' string for
444 uiout_field_connection (process_stratum_target *proc_target)
446 if (proc_target == NULL)
450 else if (proc_target->connection_string () != NULL)
452 return string_printf ("%d (%s %s)",
453 proc_target->connection_number,
454 proc_target->shortname (),
455 proc_target->connection_string ());
459 return string_printf ("%d (%s)",
460 proc_target->connection_number,
461 proc_target->shortname ());
465 /* Prints the list of inferiors and their details on UIOUT. This is a
466 version of 'info_inferior_command' suitable for use from MI.
468 If REQUESTED_INFERIORS is not NULL, it's a list of GDB ids of the
469 inferiors that should be printed. Otherwise, all inferiors are
473 print_inferior (struct ui_out *uiout, const char *requested_inferiors)
476 size_t connection_id_len = 20;
478 /* Compute number of inferiors we will print. */
479 for (inferior *inf : all_inferiors ())
481 if (!number_is_in_list (requested_inferiors, inf->num))
484 std::string conn = uiout_field_connection (inf->process_target ());
485 if (connection_id_len < conn.size ())
486 connection_id_len = conn.size ();
493 uiout->message ("No inferiors.\n");
497 ui_out_emit_table table_emitter (uiout, 5, inf_count, "inferiors");
498 uiout->table_header (1, ui_left, "current", "");
499 uiout->table_header (4, ui_left, "number", "Num");
500 uiout->table_header (17, ui_left, "target-id", "Description");
501 uiout->table_header (connection_id_len, ui_left,
502 "connection-id", "Connection");
503 uiout->table_header (17, ui_left, "exec", "Executable");
505 uiout->table_body ();
507 /* Restore the current thread after the loop because we switch the
508 inferior in the loop. */
509 scoped_restore_current_pspace_and_thread restore_pspace_thread;
510 inferior *current_inf = current_inferior ();
511 for (inferior *inf : all_inferiors ())
513 if (!number_is_in_list (requested_inferiors, inf->num))
516 ui_out_emit_tuple tuple_emitter (uiout, NULL);
518 if (inf == current_inf)
519 uiout->field_string ("current", "*");
521 uiout->field_skip ("current");
523 uiout->field_signed ("number", inf->num);
525 /* Because target_pid_to_str uses the current inferior,
526 switch the inferior. */
527 switch_to_inferior_no_thread (inf);
529 uiout->field_string ("target-id", inferior_pid_to_str (inf->pid));
531 std::string conn = uiout_field_connection (inf->process_target ());
532 uiout->field_string ("connection-id", conn);
534 if (inf->pspace->exec_filename != nullptr)
535 uiout->field_string ("exec", inf->pspace->exec_filename.get ());
537 uiout->field_skip ("exec");
539 /* Print extra info that isn't really fit to always present in
540 tabular form. Currently we print the vfork parent/child
541 relationships, if any. */
542 if (inf->vfork_parent)
544 uiout->text (_("\n\tis vfork child of inferior "));
545 uiout->field_signed ("vfork-parent", inf->vfork_parent->num);
547 if (inf->vfork_child)
549 uiout->text (_("\n\tis vfork parent of inferior "));
550 uiout->field_signed ("vfork-child", inf->vfork_child->num);
558 detach_inferior_command (const char *args, int from_tty)
561 error (_("Requires argument (inferior id(s) to detach)"));
563 scoped_restore_current_thread restore_thread;
565 number_or_range_parser parser (args);
566 while (!parser.finished ())
568 int num = parser.get_number ();
570 inferior *inf = find_inferior_id (num);
573 warning (_("Inferior ID %d not known."), num);
579 warning (_("Inferior ID %d is not running."), num);
583 thread_info *tp = any_thread_of_inferior (inf);
586 warning (_("Inferior ID %d has no threads."), num);
590 switch_to_thread (tp);
592 detach_command (NULL, from_tty);
597 kill_inferior_command (const char *args, int from_tty)
600 error (_("Requires argument (inferior id(s) to kill)"));
602 scoped_restore_current_thread restore_thread;
604 number_or_range_parser parser (args);
605 while (!parser.finished ())
607 int num = parser.get_number ();
609 inferior *inf = find_inferior_id (num);
612 warning (_("Inferior ID %d not known."), num);
618 warning (_("Inferior ID %d is not running."), num);
622 thread_info *tp = any_thread_of_inferior (inf);
625 warning (_("Inferior ID %d has no threads."), num);
629 switch_to_thread (tp);
634 bfd_cache_close_all ();
637 /* See inferior.h. */
640 switch_to_inferior_no_thread (inferior *inf)
642 set_current_inferior (inf);
643 switch_to_no_thread ();
644 set_current_program_space (inf->pspace);
648 inferior_command (const char *args, int from_tty)
650 struct inferior *inf;
655 inf = current_inferior ();
656 gdb_assert (inf != nullptr);
657 const char *filename = inf->pspace->exec_filename.get ();
659 if (filename == nullptr)
660 filename = _("<noexec>");
662 printf_filtered (_("[Current inferior is %d [%s] (%s)]\n"),
663 inf->num, inferior_pid_to_str (inf->pid).c_str (),
668 num = parse_and_eval_long (args);
670 inf = find_inferior_id (num);
672 error (_("Inferior ID %d not known."), num);
676 if (inf != current_inferior ())
678 thread_info *tp = any_thread_of_inferior (inf);
680 error (_("Inferior has no threads."));
682 switch_to_thread (tp);
685 gdb::observers::user_selected_context_changed.notify
686 (USER_SELECTED_INFERIOR
687 | USER_SELECTED_THREAD
688 | USER_SELECTED_FRAME);
692 switch_to_inferior_no_thread (inf);
694 gdb::observers::user_selected_context_changed.notify
695 (USER_SELECTED_INFERIOR);
700 /* Print information about currently known inferiors. */
703 info_inferiors_command (const char *args, int from_tty)
705 print_inferior (current_uiout, args);
708 /* remove-inferior ID */
711 remove_inferior_command (const char *args, int from_tty)
713 if (args == NULL || *args == '\0')
714 error (_("Requires an argument (inferior id(s) to remove)"));
716 number_or_range_parser parser (args);
717 while (!parser.finished ())
719 int num = parser.get_number ();
720 struct inferior *inf = find_inferior_id (num);
724 warning (_("Inferior ID %d not known."), num);
728 if (!inf->deletable ())
730 warning (_("Can not remove current inferior %d."), num);
736 warning (_("Can not remove active inferior %d."), num);
740 delete_inferior (inf);
745 add_inferior_with_spaces (void)
747 struct address_space *aspace;
748 struct program_space *pspace;
749 struct inferior *inf;
750 struct gdbarch_info info;
752 /* If all inferiors share an address space on this system, this
753 doesn't really return a new address space; otherwise, it
755 aspace = maybe_new_address_space ();
756 pspace = new program_space (aspace);
757 inf = add_inferior (0);
758 inf->pspace = pspace;
759 inf->aspace = pspace->aspace;
761 /* Setup the inferior's initial arch, based on information obtained
762 from the global "set ..." options. */
763 gdbarch_info_init (&info);
764 inf->gdbarch = gdbarch_find_by_info (info);
765 /* The "set ..." options reject invalid settings, so we should
766 always have a valid arch by now. */
767 gdb_assert (inf->gdbarch != NULL);
772 /* Switch to inferior NEW_INF, a new inferior, and unless
773 NO_CONNECTION is true, push the process_stratum_target of ORG_INF
777 switch_to_inferior_and_push_target (inferior *new_inf,
778 bool no_connection, inferior *org_inf)
780 process_stratum_target *proc_target = org_inf->process_target ();
782 /* Switch over temporarily, while reading executable and
784 switch_to_inferior_no_thread (new_inf);
786 /* Reuse the target for new inferior. */
787 if (!no_connection && proc_target != NULL)
789 new_inf->push_target (proc_target);
790 if (proc_target->connection_string () != NULL)
791 printf_filtered (_("Added inferior %d on connection %d (%s %s)\n"),
793 proc_target->connection_number,
794 proc_target->shortname (),
795 proc_target->connection_string ());
797 printf_filtered (_("Added inferior %d on connection %d (%s)\n"),
799 proc_target->connection_number,
800 proc_target->shortname ());
803 printf_filtered (_("Added inferior %d\n"), new_inf->num);
806 /* add-inferior [-copies N] [-exec FILENAME] [-no-connection] */
809 add_inferior_command (const char *args, int from_tty)
812 gdb::unique_xmalloc_ptr<char> exec;
813 symfile_add_flags add_flags = 0;
814 bool no_connection = false;
817 add_flags |= SYMFILE_VERBOSE;
821 gdb_argv built_argv (args);
823 for (char **argv = built_argv.get (); *argv != NULL; argv++)
827 if (strcmp (*argv, "-copies") == 0)
831 error (_("No argument to -copies"));
832 copies = parse_and_eval_long (*argv);
834 else if (strcmp (*argv, "-no-connection") == 0)
835 no_connection = true;
836 else if (strcmp (*argv, "-exec") == 0)
840 error (_("No argument to -exec"));
841 exec.reset (tilde_expand (*argv));
845 error (_("Invalid argument"));
849 inferior *orginf = current_inferior ();
851 scoped_restore_current_pspace_and_thread restore_pspace_thread;
853 for (i = 0; i < copies; ++i)
855 inferior *inf = add_inferior_with_spaces ();
857 switch_to_inferior_and_push_target (inf, no_connection, orginf);
861 exec_file_attach (exec.get (), from_tty);
862 symbol_file_add_main (exec.get (), add_flags);
867 /* clone-inferior [-copies N] [ID] [-no-connection] */
870 clone_inferior_command (const char *args, int from_tty)
873 struct inferior *orginf = NULL;
874 bool no_connection = false;
878 gdb_argv built_argv (args);
880 char **argv = built_argv.get ();
881 for (; *argv != NULL; argv++)
885 if (strcmp (*argv, "-copies") == 0)
889 error (_("No argument to -copies"));
890 copies = parse_and_eval_long (*argv);
893 error (_("Invalid copies number"));
895 else if (strcmp (*argv, "-no-connection") == 0)
896 no_connection = true;
904 /* The first non-option (-) argument specified the
906 num = parse_and_eval_long (*argv);
907 orginf = find_inferior_id (num);
910 error (_("Inferior ID %d not known."), num);
914 error (_("Invalid argument"));
919 /* If no inferior id was specified, then the user wants to clone the
922 orginf = current_inferior ();
924 scoped_restore_current_pspace_and_thread restore_pspace_thread;
926 for (i = 0; i < copies; ++i)
928 struct address_space *aspace;
929 struct program_space *pspace;
930 struct inferior *inf;
932 /* If all inferiors share an address space on this system, this
933 doesn't really return a new address space; otherwise, it
935 aspace = maybe_new_address_space ();
936 pspace = new program_space (aspace);
937 inf = add_inferior (0);
938 inf->pspace = pspace;
939 inf->aspace = pspace->aspace;
940 inf->gdbarch = orginf->gdbarch;
942 switch_to_inferior_and_push_target (inf, no_connection, orginf);
944 /* If the original inferior had a user specified target
945 description, make the clone use it too. */
946 if (target_desc_info_from_user_p (inf->tdesc_info))
947 copy_inferior_target_desc_info (inf, orginf);
949 clone_program_space (pspace, orginf->pspace);
953 /* Print notices when new inferiors are created and die. */
955 show_print_inferior_events (struct ui_file *file, int from_tty,
956 struct cmd_list_element *c, const char *value)
958 fprintf_filtered (file, _("Printing of inferior events is %s.\n"), value);
961 /* Return a new value for the selected inferior's id. */
963 static struct value *
964 inferior_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
967 struct inferior *inf = current_inferior ();
969 return value_from_longest (builtin_type (gdbarch)->builtin_int, inf->num);
972 /* Implementation of `$_inferior' variable. */
974 static const struct internalvar_funcs inferior_funcs =
976 inferior_id_make_value,
984 initialize_inferiors (void)
986 struct cmd_list_element *c = NULL;
988 /* There's always one inferior. Note that this function isn't an
989 automatic _initialize_foo function, since other _initialize_foo
990 routines may need to install their per-inferior data keys. We
991 can only allocate an inferior when all those modules have done
992 that. Do this after initialize_progspace, due to the
993 current_program_space reference. */
994 set_current_inferior (add_inferior_silent (0));
995 current_inferior_->pspace = current_program_space;
996 current_inferior_->aspace = current_program_space->aspace;
997 /* The architecture will be initialized shortly, by
998 initialize_current_architecture. */
1000 add_info ("inferiors", info_inferiors_command,
1001 _("Print a list of inferiors being managed.\n\
1002 Usage: info inferiors [ID]...\n\
1003 If IDs are specified, the list is limited to just those inferiors.\n\
1004 By default all inferiors are displayed."));
1006 c = add_com ("add-inferior", no_class, add_inferior_command, _("\
1007 Add a new inferior.\n\
1008 Usage: add-inferior [-copies N] [-exec FILENAME] [-no-connection]\n\
1009 N is the optional number of inferiors to add, default is 1.\n\
1010 FILENAME is the file name of the executable to use\n\
1012 By default, the new inferior inherits the current inferior's connection.\n\
1013 If -no-connection is specified, the new inferior begins with\n\
1014 no target connection yet."));
1015 set_cmd_completer (c, filename_completer);
1017 add_com ("remove-inferiors", no_class, remove_inferior_command, _("\
1018 Remove inferior ID (or list of IDs).\n\
1019 Usage: remove-inferiors ID..."));
1021 add_com ("clone-inferior", no_class, clone_inferior_command, _("\
1022 Clone inferior ID.\n\
1023 Usage: clone-inferior [-copies N] [-no-connection] [ID]\n\
1024 Add N copies of inferior ID. The new inferiors have the same\n\
1025 executable loaded as the copied inferior. If -copies is not specified,\n\
1026 adds 1 copy. If ID is not specified, it is the current inferior\n\
1028 By default, the new inferiors inherit the copied inferior's connection.\n\
1029 If -no-connection is specified, the new inferiors begin with\n\
1030 no target connection yet."));
1032 add_cmd ("inferiors", class_run, detach_inferior_command, _("\
1033 Detach from inferior ID (or list of IDS).\n\
1034 Usage; detach inferiors ID..."),
1037 add_cmd ("inferiors", class_run, kill_inferior_command, _("\
1038 Kill inferior ID (or list of IDs).\n\
1039 Usage: kill inferiors ID..."),
1042 add_cmd ("inferior", class_run, inferior_command, _("\
1043 Use this command to switch between inferiors.\n\
1044 Usage: inferior ID\n\
1045 The new inferior ID must be currently known."),
1048 add_setshow_boolean_cmd ("inferior-events", no_class,
1049 &print_inferior_events, _("\
1050 Set printing of inferior events (such as inferior start and exit)."), _("\
1051 Show printing of inferior events (such as inferior start and exit)."), NULL,
1053 show_print_inferior_events,
1054 &setprintlist, &showprintlist);
1056 create_internalvar_type_lazy ("_inferior", &inferior_funcs, NULL);