1 /* Multi-process control for GDB, the GNU debugger.
2 
3    Copyright (C) 2008-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 "exec.h"
21 #include "inferior.h"
22 #include "target.h"
23 #include "command.h"
24 #include "completer.h"
25 #include "cli/cli-cmds.h"
26 #include "gdbthread.h"
27 #include "ui-out.h"
28 #include "observable.h"
29 #include "gdbcore.h"
30 #include "symfile.h"
31 #include "gdbsupport/environ.h"
32 #include "cli/cli-utils.h"
33 #include "arch-utils.h"
34 #include "target-descriptions.h"
35 #include "target-connection.h"
36 #include "readline/tilde.h"
37 #include "progspace-and-thread.h"
38 #include "gdbsupport/buildargv.h"
39 #include "cli/cli-style.h"
40 #include "interps.h"
41 
42 intrusive_list<inferior> inferior_list;
43 static int highest_inferior_num;
44 
45 /* See inferior.h.  */
46 bool print_inferior_events = true;
47 
48 /* The Current Inferior.  This is a strong reference.  I.e., whenever
49    an inferior is the current inferior, its refcount is
50    incremented.  */
51 static inferior_ref current_inferior_;
52 
53 struct inferior*
current_inferior(void)54 current_inferior (void)
55 {
56   return current_inferior_.get ();
57 }
58 
59 void
set_current_inferior(struct inferior * inf)60 set_current_inferior (struct inferior *inf)
61 {
62   /* There's always an inferior.  */
63   gdb_assert (inf != NULL);
64 
65   current_inferior_ = inferior_ref::new_reference (inf);
66 }
67 
68 private_inferior::~private_inferior () = default;
69 
~inferior()70 inferior::~inferior ()
71 {
72   /* Before the inferior is deleted, all target_ops should be popped from
73      the target stack, this leaves just the dummy_target behind.  If this
74      is not done, then any target left in the target stack will be left
75      with an artificially high reference count.  As the dummy_target is
76      still on the target stack then we are about to loose a reference to
77      that target, leaving its reference count artificially high.  However,
78      this is not critical as the dummy_target is a singleton.  */
79   gdb_assert (m_target_stack.top ()->stratum () == dummy_stratum);
80 
81   m_continuations.clear ();
82 }
83 
inferior(int pid_)84 inferior::inferior (int pid_)
85   : num (++highest_inferior_num),
86     pid (pid_),
87     environment (gdb_environ::from_host_environ ())
88 {
89   m_target_stack.push (get_dummy_target ());
90 }
91 
92 /* See inferior.h.  */
93 
94 int
unpush_target(struct target_ops * t)95 inferior::unpush_target (struct target_ops *t)
96 {
97   /* If unpushing the process stratum target from the inferior while threads
98      exist in the inferior, ensure that we don't leave any threads of the
99      inferior in the target's "resumed with pending wait status" list.
100 
101      See also the comment in set_thread_exited.  */
102   if (t->stratum () == process_stratum)
103     {
104       process_stratum_target *proc_target = as_process_stratum_target (t);
105 
106       for (thread_info *thread : this->non_exited_threads ())
107           proc_target->maybe_remove_resumed_with_pending_wait_status (thread);
108     }
109 
110   return m_target_stack.unpush (t);
111 }
112 
113 /* See inferior.h.  */
114 
115 void
unpush_target_and_assert(struct target_ops * target)116 inferior::unpush_target_and_assert (struct target_ops *target)
117 {
118   gdb_assert (current_inferior () == this);
119 
120   if (!unpush_target (target))
121     internal_error ("pop_all_targets couldn't find target %s\n",
122                         target->shortname ());
123 }
124 
125 /* See inferior.h.  */
126 
127 void
pop_all_targets_above(enum strata stratum)128 inferior::pop_all_targets_above (enum strata stratum)
129 {
130   /* Unpushing a target might cause it to close.  Some targets currently
131      rely on the current_inferior being set for their ::close method, so we
132      temporarily switch inferior now.  */
133   scoped_restore_current_pspace_and_thread restore_pspace_and_thread;
134   switch_to_inferior_no_thread (this);
135 
136   while (top_target ()->stratum () > stratum)
137     unpush_target_and_assert (top_target ());
138 }
139 
140 /* See inferior.h.  */
141 
142 void
pop_all_targets_at_and_above(enum strata stratum)143 inferior::pop_all_targets_at_and_above (enum strata stratum)
144 {
145   /* Unpushing a target might cause it to close.  Some targets currently
146      rely on the current_inferior being set for their ::close method, so we
147      temporarily switch inferior now.  */
148   scoped_restore_current_pspace_and_thread restore_pspace_and_thread;
149   switch_to_inferior_no_thread (this);
150 
151   while (top_target ()->stratum () >= stratum)
152     unpush_target_and_assert (top_target ());
153 }
154 
155 void
set_tty(std::string terminal_name)156 inferior::set_tty (std::string terminal_name)
157 {
158   m_terminal = std::move (terminal_name);
159 }
160 
161 const std::string &
tty()162 inferior::tty ()
163 {
164   return m_terminal;
165 }
166 
167 /* See inferior.h.  */
168 
169 void
set_args(gdb::array_view<char * const> args)170 inferior::set_args (gdb::array_view<char * const> args)
171 {
172   set_args (construct_inferior_arguments (args));
173 }
174 
175 void
set_arch(gdbarch * arch)176 inferior::set_arch (gdbarch *arch)
177 {
178   gdb_assert (arch != nullptr);
179   gdb_assert (gdbarch_initialized_p (arch));
180   m_gdbarch = arch;
181 
182   process_stratum_target *proc_target = this->process_target ();
183   if (proc_target != nullptr)
184     registers_changed_ptid (proc_target, ptid_t (this->pid));
185 }
186 
187 void
add_continuation(std::function<void ()> && cont)188 inferior::add_continuation (std::function<void ()> &&cont)
189 {
190   m_continuations.emplace_front (std::move (cont));
191 }
192 
193 void
do_all_continuations()194 inferior::do_all_continuations ()
195 {
196   while (!m_continuations.empty ())
197     {
198       auto iter = m_continuations.begin ();
199       (*iter) ();
200       m_continuations.erase (iter);
201     }
202 }
203 
204 /* Notify interpreters and observers that inferior INF was added.  */
205 
206 static void
notify_inferior_added(inferior * inf)207 notify_inferior_added (inferior *inf)
208 {
209   interps_notify_inferior_added (inf);
210   gdb::observers::inferior_added.notify (inf);
211 }
212 
213 struct inferior *
add_inferior_silent(int pid)214 add_inferior_silent (int pid)
215 {
216   inferior *inf = new inferior (pid);
217 
218   inferior_list.push_back (*inf);
219 
220   notify_inferior_added (inf);
221 
222   if (pid != 0)
223     inferior_appeared (inf, pid);
224 
225   return inf;
226 }
227 
228 struct inferior *
add_inferior(int pid)229 add_inferior (int pid)
230 {
231   struct inferior *inf = add_inferior_silent (pid);
232 
233   if (print_inferior_events)
234     {
235       if (pid != 0)
236           gdb_printf (_("[New inferior %d (%s)]\n"),
237                         inf->num,
238                         target_pid_to_str (ptid_t (pid)).c_str ());
239       else
240           gdb_printf (_("[New inferior %d]\n"), inf->num);
241     }
242 
243   return inf;
244 }
245 
246 /* See inferior.h.  */
247 
248 thread_info *
find_thread(ptid_t ptid)249 inferior::find_thread (ptid_t ptid)
250 {
251   auto it = this->ptid_thread_map.find (ptid);
252   if (it != this->ptid_thread_map.end ())
253     return it->second;
254   else
255     return nullptr;
256 }
257 
258 /* See inferior.h.  */
259 
260 void
clear_thread_list()261 inferior::clear_thread_list ()
262 {
263   thread_list.clear_and_dispose ([=] (thread_info *thr)
264     {
265       threads_debug_printf ("deleting thread %s",
266                                   thr->ptid.to_string ().c_str ());
267       set_thread_exited (thr, {}, true /* silent */);
268       if (thr->deletable ())
269           delete thr;
270     });
271   ptid_thread_map.clear ();
272 }
273 
274 /* Notify interpreters and observers that inferior INF was removed.  */
275 
276 static void
notify_inferior_removed(inferior * inf)277 notify_inferior_removed (inferior *inf)
278 {
279   interps_notify_inferior_removed (inf);
280   gdb::observers::inferior_removed.notify (inf);
281 }
282 
283 void
delete_inferior(struct inferior * inf)284 delete_inferior (struct inferior *inf)
285 {
286   inf->clear_thread_list ();
287 
288   auto it = inferior_list.iterator_to (*inf);
289   inferior_list.erase (it);
290 
291   notify_inferior_removed (inf);
292 
293   /* Pop all targets now, this ensures that inferior::unpush is called
294      correctly.  As pop_all_targets ends up making a temporary switch to
295      inferior INF then we need to make this call before we delete the
296      program space, which we do below.  */
297   inf->pop_all_targets ();
298 
299   /* If this program space is rendered useless, remove it. */
300   if (inf->pspace->empty ())
301     delete inf->pspace;
302 
303   delete inf;
304 }
305 
306 /* Notify interpreters and observers that inferior INF disappeared.  */
307 
308 static void
notify_inferior_disappeared(inferior * inf)309 notify_inferior_disappeared (inferior *inf)
310 {
311   interps_notify_inferior_disappeared (inf);
312   gdb::observers::inferior_exit.notify (inf);
313 }
314 
315 /* See inferior.h.  */
316 
317 void
exit_inferior(struct inferior * inf)318 exit_inferior (struct inferior *inf)
319 {
320   inf->clear_thread_list ();
321 
322   notify_inferior_disappeared (inf);
323 
324   inf->pid = 0;
325   inf->fake_pid_p = false;
326   inf->priv = NULL;
327 
328   if (inf->vfork_parent != NULL)
329     {
330       inf->vfork_parent->vfork_child = NULL;
331       inf->vfork_parent = NULL;
332     }
333   if (inf->vfork_child != NULL)
334     {
335       inf->vfork_child->vfork_parent = NULL;
336       inf->vfork_child = NULL;
337     }
338 
339   inf->pending_detach = false;
340   /* Reset it.  */
341   inf->control = inferior_control_state (NO_STOP_QUIETLY);
342 
343   /* Clear the register cache and the frame cache.  */
344   registers_changed ();
345   reinit_frame_cache ();
346 }
347 
348 /* See inferior.h.  */
349 
350 void
detach_inferior(inferior * inf)351 detach_inferior (inferior *inf)
352 {
353   /* Save the pid, since exit_inferior will reset it.  */
354   int pid = inf->pid;
355 
356   exit_inferior (inf);
357 
358   if (print_inferior_events)
359     gdb_printf (_("[Inferior %d (%s) detached]\n"),
360                     inf->num,
361                     target_pid_to_str (ptid_t (pid)).c_str ());
362 }
363 
364 /* Notify interpreters and observers that inferior INF appeared.  */
365 
366 static void
notify_inferior_appeared(inferior * inf)367 notify_inferior_appeared (inferior *inf)
368 {
369   interps_notify_inferior_appeared (inf);
370   gdb::observers::inferior_appeared.notify (inf);
371 }
372 
373 void
inferior_appeared(struct inferior * inf,int pid)374 inferior_appeared (struct inferior *inf, int pid)
375 {
376   /* If this is the first inferior with threads, reset the global
377      thread id.  */
378   delete_exited_threads ();
379   if (!any_thread_p ())
380     init_thread_list ();
381 
382   inf->pid = pid;
383   inf->has_exit_code = false;
384   inf->exit_code = 0;
385 
386   notify_inferior_appeared (inf);
387 }
388 
389 struct inferior *
find_inferior_id(int num)390 find_inferior_id (int num)
391 {
392   for (inferior *inf : all_inferiors ())
393     if (inf->num == num)
394       return inf;
395 
396   return NULL;
397 }
398 
399 struct inferior *
find_inferior_pid(process_stratum_target * targ,int pid)400 find_inferior_pid (process_stratum_target *targ, int pid)
401 {
402   /* Looking for inferior pid == 0 is always wrong, and indicative of
403      a bug somewhere else.  There may be more than one with pid == 0,
404      for instance.  */
405   gdb_assert (pid != 0);
406 
407   for (inferior *inf : all_inferiors (targ))
408     if (inf->pid == pid)
409       return inf;
410 
411   return NULL;
412 }
413 
414 /* See inferior.h */
415 
416 struct inferior *
find_inferior_ptid(process_stratum_target * targ,ptid_t ptid)417 find_inferior_ptid (process_stratum_target *targ, ptid_t ptid)
418 {
419   return find_inferior_pid (targ, ptid.pid ());
420 }
421 
422 /* See inferior.h.  */
423 
424 struct inferior *
find_inferior_for_program_space(struct program_space * pspace)425 find_inferior_for_program_space (struct program_space *pspace)
426 {
427   struct inferior *cur_inf = current_inferior ();
428 
429   if (cur_inf->pspace == pspace)
430     return cur_inf;
431 
432   for (inferior *inf : all_inferiors ())
433     if (inf->pspace == pspace)
434       return inf;
435 
436   return NULL;
437 }
438 
439 int
have_inferiors(void)440 have_inferiors (void)
441 {
442   for (inferior *inf ATTRIBUTE_UNUSED : all_non_exited_inferiors ())
443     return 1;
444 
445   return 0;
446 }
447 
448 /* Return the number of live inferiors.  We account for the case
449    where an inferior might have a non-zero pid but no threads, as
450    in the middle of a 'mourn' operation.  */
451 
452 int
number_of_live_inferiors(process_stratum_target * proc_target)453 number_of_live_inferiors (process_stratum_target *proc_target)
454 {
455   int num_inf = 0;
456 
457   for (inferior *inf : all_non_exited_inferiors (proc_target))
458     if (inf->has_execution ())
459       for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
460           {
461             /* Found a live thread in this inferior, go to the next
462                inferior.  */
463             ++num_inf;
464             break;
465           }
466 
467   return num_inf;
468 }
469 
470 /* Return true if there is at least one live inferior.  */
471 
472 int
have_live_inferiors(void)473 have_live_inferiors (void)
474 {
475   return number_of_live_inferiors (NULL) > 0;
476 }
477 
478 /* Prune away any unused inferiors, and then prune away no longer used
479    program spaces.  */
480 
481 void
prune_inferiors(void)482 prune_inferiors (void)
483 {
484   for (inferior *inf : all_inferiors_safe ())
485     {
486       if (!inf->deletable ()
487             || !inf->removable
488             || inf->pid != 0)
489           continue;
490 
491       delete_inferior (inf);
492     }
493 }
494 
495 /* Simply returns the count of inferiors.  */
496 
497 int
number_of_inferiors(void)498 number_of_inferiors (void)
499 {
500   auto rng = all_inferiors ();
501   return std::distance (rng.begin (), rng.end ());
502 }
503 
504 /* Converts an inferior process id to a string.  Like
505    target_pid_to_str, but special cases the null process.  */
506 
507 static std::string
inferior_pid_to_str(int pid)508 inferior_pid_to_str (int pid)
509 {
510   if (pid != 0)
511     return target_pid_to_str (ptid_t (pid));
512   else
513     return _("<null>");
514 }
515 
516 /* See inferior.h.  */
517 
518 void
print_selected_inferior(struct ui_out * uiout)519 print_selected_inferior (struct ui_out *uiout)
520 {
521   struct inferior *inf = current_inferior ();
522   const char *filename = inf->pspace->exec_filename.get ();
523 
524   if (filename == NULL)
525     filename = _("<noexec>");
526 
527   uiout->message (_("[Switching to inferior %d [%s] (%s)]\n"),
528                       inf->num, inferior_pid_to_str (inf->pid).c_str (), filename);
529 }
530 
531 /* Helper for print_inferior.  Returns the 'connection-id' string for
532    PROC_TARGET.  */
533 
534 static std::string
uiout_field_connection(process_stratum_target * proc_target)535 uiout_field_connection (process_stratum_target *proc_target)
536 {
537   if (proc_target == NULL)
538     return {};
539   else
540     {
541       std::string conn_str = make_target_connection_string (proc_target);
542       return string_printf ("%d (%s)", proc_target->connection_number,
543                                   conn_str.c_str ());
544     }
545 }
546 
547 /* Prints the list of inferiors and their details on UIOUT.  This is a
548    version of 'info_inferior_command' suitable for use from MI.
549 
550    If REQUESTED_INFERIORS is not NULL, it's a list of GDB ids of the
551    inferiors that should be printed.  Otherwise, all inferiors are
552    printed.  */
553 
554 static void
print_inferior(struct ui_out * uiout,const char * requested_inferiors)555 print_inferior (struct ui_out *uiout, const char *requested_inferiors)
556 {
557   int inf_count = 0;
558   size_t connection_id_len = 20;
559 
560   /* Compute number of inferiors we will print.  */
561   for (inferior *inf : all_inferiors ())
562     {
563       if (!number_is_in_list (requested_inferiors, inf->num))
564           continue;
565 
566       std::string conn = uiout_field_connection (inf->process_target ());
567       if (connection_id_len < conn.size ())
568           connection_id_len = conn.size ();
569 
570       ++inf_count;
571     }
572 
573   if (inf_count == 0)
574     {
575       uiout->message ("No inferiors.\n");
576       return;
577     }
578 
579   ui_out_emit_table table_emitter (uiout, 5, inf_count, "inferiors");
580   uiout->table_header (1, ui_left, "current", "");
581   uiout->table_header (4, ui_left, "number", "Num");
582   uiout->table_header (17, ui_left, "target-id", "Description");
583   uiout->table_header (connection_id_len, ui_left,
584                            "connection-id", "Connection");
585   uiout->table_header (17, ui_left, "exec", "Executable");
586 
587   uiout->table_body ();
588 
589   /* Restore the current thread after the loop because we switch the
590      inferior in the loop.  */
591   scoped_restore_current_pspace_and_thread restore_pspace_thread;
592   inferior *current_inf = current_inferior ();
593   for (inferior *inf : all_inferiors ())
594     {
595       if (!number_is_in_list (requested_inferiors, inf->num))
596           continue;
597 
598       ui_out_emit_tuple tuple_emitter (uiout, NULL);
599 
600       if (inf == current_inf)
601           uiout->field_string ("current", "*");
602       else
603           uiout->field_skip ("current");
604 
605       uiout->field_signed ("number", inf->num);
606 
607       /* Because target_pid_to_str uses the current inferior,
608            switch the inferior.  */
609       switch_to_inferior_no_thread (inf);
610 
611       uiout->field_string ("target-id", inferior_pid_to_str (inf->pid));
612 
613       std::string conn = uiout_field_connection (inf->process_target ());
614       uiout->field_string ("connection-id", conn);
615 
616       if (inf->pspace->exec_filename != nullptr)
617           uiout->field_string ("exec", inf->pspace->exec_filename.get (),
618                                    file_name_style.style ());
619       else
620           uiout->field_skip ("exec");
621 
622       /* Print extra info that isn't really fit to always present in
623            tabular form.  Currently we print the vfork parent/child
624            relationships, if any.  */
625       if (inf->vfork_parent)
626           {
627             uiout->text (_("\n\tis vfork child of inferior "));
628             uiout->field_signed ("vfork-parent", inf->vfork_parent->num);
629           }
630       if (inf->vfork_child)
631           {
632             uiout->text (_("\n\tis vfork parent of inferior "));
633             uiout->field_signed ("vfork-child", inf->vfork_child->num);
634           }
635 
636       uiout->text ("\n");
637     }
638 }
639 
640 static void
detach_inferior_command(const char * args,int from_tty)641 detach_inferior_command (const char *args, int from_tty)
642 {
643   if (!args || !*args)
644     error (_("Requires argument (inferior id(s) to detach)"));
645 
646   scoped_restore_current_thread restore_thread;
647 
648   number_or_range_parser parser (args);
649   while (!parser.finished ())
650     {
651       int num = parser.get_number ();
652 
653       inferior *inf = find_inferior_id (num);
654       if (inf == NULL)
655           {
656             warning (_("Inferior ID %d not known."), num);
657             continue;
658           }
659 
660       if (inf->pid == 0)
661           {
662             warning (_("Inferior ID %d is not running."), num);
663             continue;
664           }
665 
666       thread_info *tp = any_thread_of_inferior (inf);
667       if (tp == NULL)
668           {
669             warning (_("Inferior ID %d has no threads."), num);
670             continue;
671           }
672 
673       switch_to_thread (tp);
674 
675       detach_command (NULL, from_tty);
676     }
677 }
678 
679 static void
kill_inferior_command(const char * args,int from_tty)680 kill_inferior_command (const char *args, int from_tty)
681 {
682   if (!args || !*args)
683     error (_("Requires argument (inferior id(s) to kill)"));
684 
685   scoped_restore_current_thread restore_thread;
686 
687   number_or_range_parser parser (args);
688   while (!parser.finished ())
689     {
690       int num = parser.get_number ();
691 
692       inferior *inf = find_inferior_id (num);
693       if (inf == NULL)
694           {
695             warning (_("Inferior ID %d not known."), num);
696             continue;
697           }
698 
699       if (inf->pid == 0)
700           {
701             warning (_("Inferior ID %d is not running."), num);
702             continue;
703           }
704 
705       thread_info *tp = any_thread_of_inferior (inf);
706       if (tp == NULL)
707           {
708             warning (_("Inferior ID %d has no threads."), num);
709             continue;
710           }
711 
712       switch_to_thread (tp);
713 
714       target_kill ();
715     }
716 }
717 
718 /* See inferior.h.  */
719 
720 void
switch_to_inferior_no_thread(inferior * inf)721 switch_to_inferior_no_thread (inferior *inf)
722 {
723   set_current_inferior (inf);
724   switch_to_no_thread ();
725   set_current_program_space (inf->pspace);
726 }
727 
728 /* See regcache.h.  */
729 
730 std::optional<scoped_restore_current_thread>
maybe_switch_inferior(inferior * inf)731 maybe_switch_inferior (inferior *inf)
732 {
733   std::optional<scoped_restore_current_thread> maybe_restore_thread;
734   if (inf != current_inferior ())
735     {
736       maybe_restore_thread.emplace ();
737       switch_to_inferior_no_thread (inf);
738     }
739 
740   return maybe_restore_thread;
741 }
742 
743 static void
inferior_command(const char * args,int from_tty)744 inferior_command (const char *args, int from_tty)
745 {
746   struct inferior *inf;
747   int num;
748 
749   if (args == nullptr)
750     {
751       inf = current_inferior ();
752       gdb_assert (inf != nullptr);
753       const char *filename = inf->pspace->exec_filename.get ();
754 
755       if (filename == nullptr)
756           filename = _("<noexec>");
757 
758       gdb_printf (_("[Current inferior is %d [%s] (%s)]\n"),
759                       inf->num, inferior_pid_to_str (inf->pid).c_str (),
760                       filename);
761     }
762   else
763     {
764       num = parse_and_eval_long (args);
765 
766       inf = find_inferior_id (num);
767       if (inf == NULL)
768           error (_("Inferior ID %d not known."), num);
769 
770       if (inf->pid != 0)
771           {
772             if (inf != current_inferior ())
773               {
774                 thread_info *tp = any_thread_of_inferior (inf);
775                 if (tp == NULL)
776                     error (_("Inferior has no threads."));
777 
778                 switch_to_thread (tp);
779               }
780 
781             notify_user_selected_context_changed
782               (USER_SELECTED_INFERIOR
783                | USER_SELECTED_THREAD
784                | USER_SELECTED_FRAME);
785           }
786       else
787           {
788             switch_to_inferior_no_thread (inf);
789 
790             notify_user_selected_context_changed
791               (USER_SELECTED_INFERIOR);
792           }
793     }
794 }
795 
796 /* Print information about currently known inferiors.  */
797 
798 static void
info_inferiors_command(const char * args,int from_tty)799 info_inferiors_command (const char *args, int from_tty)
800 {
801   print_inferior (current_uiout, args);
802 }
803 
804 /* remove-inferior ID */
805 
806 static void
remove_inferior_command(const char * args,int from_tty)807 remove_inferior_command (const char *args, int from_tty)
808 {
809   if (args == NULL || *args == '\0')
810     error (_("Requires an argument (inferior id(s) to remove)"));
811 
812   number_or_range_parser parser (args);
813   while (!parser.finished ())
814     {
815       int num = parser.get_number ();
816       struct inferior *inf = find_inferior_id (num);
817 
818       if (inf == NULL)
819           {
820             warning (_("Inferior ID %d not known."), num);
821             continue;
822           }
823 
824       if (!inf->deletable ())
825           {
826             warning (_("Can not remove current inferior %d."), num);
827             continue;
828           }
829 
830       if (inf->pid != 0)
831           {
832             warning (_("Can not remove active inferior %d."), num);
833             continue;
834           }
835 
836       delete_inferior (inf);
837     }
838 }
839 
840 struct inferior *
add_inferior_with_spaces(void)841 add_inferior_with_spaces (void)
842 {
843   struct program_space *pspace;
844   struct inferior *inf;
845 
846   /* If all inferiors share an address space on this system, this
847      doesn't really return a new address space; otherwise, it
848      really does.  */
849   pspace = new program_space (maybe_new_address_space ());
850   inf = add_inferior (0);
851   inf->pspace = pspace;
852   inf->aspace = pspace->aspace;
853 
854   /* Setup the inferior's initial arch, based on information obtained
855      from the global "set ..." options.  */
856   gdbarch_info info;
857   inf->set_arch (gdbarch_find_by_info (info));
858   /* The "set ..." options reject invalid settings, so we should
859      always have a valid arch by now.  */
860   gdb_assert (inf->arch () != nullptr);
861 
862   return inf;
863 }
864 
865 /* See inferior.h.  */
866 
867 void
switch_to_inferior_and_push_target(inferior * new_inf,bool no_connection,inferior * org_inf)868 switch_to_inferior_and_push_target (inferior *new_inf,
869                                             bool no_connection, inferior *org_inf)
870 {
871   process_stratum_target *proc_target = org_inf->process_target ();
872 
873   /* Switch over temporarily, while reading executable and
874      symbols.  */
875   switch_to_inferior_no_thread (new_inf);
876 
877   /* Reuse the target for new inferior.  */
878   if (!no_connection && proc_target != NULL)
879     {
880       new_inf->push_target (proc_target);
881       gdb_printf (_("Added inferior %d on connection %d (%s)\n"),
882                       new_inf->num,
883                       proc_target->connection_number,
884                       make_target_connection_string (proc_target).c_str ());
885     }
886   else
887     gdb_printf (_("Added inferior %d\n"), new_inf->num);
888 }
889 
890 /* add-inferior [-copies N] [-exec FILENAME] [-no-connection] */
891 
892 static void
add_inferior_command(const char * args,int from_tty)893 add_inferior_command (const char *args, int from_tty)
894 {
895   int i, copies = 1;
896   gdb::unique_xmalloc_ptr<char> exec;
897   symfile_add_flags add_flags = 0;
898   bool no_connection = false;
899 
900   if (from_tty)
901     add_flags |= SYMFILE_VERBOSE;
902 
903   if (args)
904     {
905       gdb_argv built_argv (args);
906 
907       for (char **argv = built_argv.get (); *argv != NULL; argv++)
908           {
909             if (**argv == '-')
910               {
911                 if (strcmp (*argv, "-copies") == 0)
912                     {
913                       ++argv;
914                       if (!*argv)
915                         error (_("No argument to -copies"));
916                       copies = parse_and_eval_long (*argv);
917                     }
918                 else if (strcmp (*argv, "-no-connection") == 0)
919                     no_connection = true;
920                 else if (strcmp (*argv, "-exec") == 0)
921                     {
922                       ++argv;
923                       if (!*argv)
924                         error (_("No argument to -exec"));
925                       exec.reset (tilde_expand (*argv));
926                     }
927               }
928             else
929               error (_("Invalid argument"));
930           }
931     }
932 
933   inferior *orginf = current_inferior ();
934 
935   scoped_restore_current_pspace_and_thread restore_pspace_thread;
936 
937   for (i = 0; i < copies; ++i)
938     {
939       inferior *inf = add_inferior_with_spaces ();
940 
941       switch_to_inferior_and_push_target (inf, no_connection, orginf);
942 
943       if (exec != NULL)
944           {
945             exec_file_attach (exec.get (), from_tty);
946             symbol_file_add_main (exec.get (), add_flags);
947           }
948     }
949 }
950 
951 /* clone-inferior [-copies N] [ID] [-no-connection] */
952 
953 static void
clone_inferior_command(const char * args,int from_tty)954 clone_inferior_command (const char *args, int from_tty)
955 {
956   int i, copies = 1;
957   struct inferior *orginf = NULL;
958   bool no_connection = false;
959 
960   if (args)
961     {
962       gdb_argv built_argv (args);
963 
964       char **argv = built_argv.get ();
965       for (; *argv != NULL; argv++)
966           {
967             if (**argv == '-')
968               {
969                 if (strcmp (*argv, "-copies") == 0)
970                     {
971                       ++argv;
972                       if (!*argv)
973                         error (_("No argument to -copies"));
974                       copies = parse_and_eval_long (*argv);
975 
976                       if (copies < 0)
977                         error (_("Invalid copies number"));
978                     }
979                 else if (strcmp (*argv, "-no-connection") == 0)
980                     no_connection = true;
981               }
982             else
983               {
984                 if (orginf == NULL)
985                     {
986                       int num;
987 
988                       /* The first non-option (-) argument specified the
989                          program space ID.  */
990                       num = parse_and_eval_long (*argv);
991                       orginf = find_inferior_id (num);
992 
993                       if (orginf == NULL)
994                         error (_("Inferior ID %d not known."), num);
995                       continue;
996                     }
997                 else
998                     error (_("Invalid argument"));
999               }
1000           }
1001     }
1002 
1003   /* If no inferior id was specified, then the user wants to clone the
1004      current inferior.  */
1005   if (orginf == NULL)
1006     orginf = current_inferior ();
1007 
1008   scoped_restore_current_pspace_and_thread restore_pspace_thread;
1009 
1010   for (i = 0; i < copies; ++i)
1011     {
1012       struct program_space *pspace;
1013       struct inferior *inf;
1014 
1015       /* If all inferiors share an address space on this system, this
1016            doesn't really return a new address space; otherwise, it
1017            really does.  */
1018       pspace = new program_space (maybe_new_address_space ());
1019       inf = add_inferior (0);
1020       inf->pspace = pspace;
1021       inf->aspace = pspace->aspace;
1022       inf->set_arch (orginf->arch ());
1023 
1024       switch_to_inferior_and_push_target (inf, no_connection, orginf);
1025 
1026       /* If the original inferior had a user specified target
1027            description, make the clone use it too.  */
1028       if (inf->tdesc_info.from_user_p ())
1029           inf->tdesc_info = orginf->tdesc_info;
1030 
1031       clone_program_space (pspace, orginf->pspace);
1032 
1033       /* Copy properties from the original inferior to the new one.  */
1034       inf->set_args (orginf->args ());
1035       inf->set_cwd (orginf->cwd ());
1036       inf->set_tty (orginf->tty ());
1037       for (const std::string &set_var : orginf->environment.user_set_env ())
1038           {
1039             /* set_var has the form NAME=value.  Split on the first '='.  */
1040             const std::string::size_type pos = set_var.find ('=');
1041             gdb_assert (pos != std::string::npos);
1042             const std::string varname = set_var.substr (0, pos);
1043             inf->environment.set
1044               (varname.c_str (), orginf->environment.get (varname.c_str ()));
1045           }
1046       for (const std::string &unset_var
1047              : orginf->environment.user_unset_env ())
1048           inf->environment.unset (unset_var.c_str ());
1049 
1050       gdb::observers::inferior_cloned.notify (orginf, inf);
1051     }
1052 }
1053 
1054 /* Print notices when new inferiors are created and die.  */
1055 static void
show_print_inferior_events(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)1056 show_print_inferior_events (struct ui_file *file, int from_tty,
1057                                  struct cmd_list_element *c, const char *value)
1058 {
1059   gdb_printf (file, _("Printing of inferior events is %s.\n"), value);
1060 }
1061 
1062 /* Return a new value for the selected inferior's id.  */
1063 
1064 static struct value *
inferior_id_make_value(struct gdbarch * gdbarch,struct internalvar * var,void * ignore)1065 inferior_id_make_value (struct gdbarch *gdbarch, struct internalvar *var,
1066                               void *ignore)
1067 {
1068   struct inferior *inf = current_inferior ();
1069 
1070   return value_from_longest (builtin_type (gdbarch)->builtin_int, inf->num);
1071 }
1072 
1073 /* Implementation of `$_inferior' variable.  */
1074 
1075 static const struct internalvar_funcs inferior_funcs =
1076 {
1077   inferior_id_make_value,
1078   NULL,
1079 };
1080 
1081 /* See inferior.h.  */
1082 
1083 void
initialize_inferiors()1084 initialize_inferiors ()
1085 {
1086   struct cmd_list_element *c = NULL;
1087 
1088   /* There's always one inferior.  Note that this function isn't an
1089      automatic _initialize_foo function, since other _initialize_foo
1090      routines may need to install their per-inferior data keys.  We
1091      can only allocate an inferior when all those modules have done
1092      that.  Do this after initialize_progspace, due to the
1093      current_program_space reference.  */
1094   set_current_inferior (add_inferior_silent (0));
1095   current_inferior_->pspace = current_program_space;
1096   current_inferior_->aspace = current_program_space->aspace;
1097   /* The architecture will be initialized shortly, by
1098      initialize_current_architecture.  */
1099 
1100   add_info ("inferiors", info_inferiors_command,
1101               _("Print a list of inferiors being managed.\n\
1102 Usage: info inferiors [ID]...\n\
1103 If IDs are specified, the list is limited to just those inferiors.\n\
1104 By default all inferiors are displayed."));
1105 
1106   c = add_com ("add-inferior", no_class, add_inferior_command, _("\
1107 Add a new inferior.\n\
1108 Usage: add-inferior [-copies N] [-exec FILENAME] [-no-connection]\n\
1109 N is the optional number of inferiors to add, default is 1.\n\
1110 FILENAME is the file name of the executable to use\n\
1111 as main program.\n\
1112 By default, the new inferior inherits the current inferior's connection.\n\
1113 If -no-connection is specified, the new inferior begins with\n\
1114 no target connection yet."));
1115   set_cmd_completer (c, filename_completer);
1116 
1117   add_com ("remove-inferiors", no_class, remove_inferior_command, _("\
1118 Remove inferior ID (or list of IDs).\n\
1119 Usage: remove-inferiors ID..."));
1120 
1121   add_com ("clone-inferior", no_class, clone_inferior_command, _("\
1122 Clone inferior ID.\n\
1123 Usage: clone-inferior [-copies N] [-no-connection] [ID]\n\
1124 Add N copies of inferior ID.  The new inferiors have the same\n\
1125 executable loaded as the copied inferior.  If -copies is not specified,\n\
1126 adds 1 copy.  If ID is not specified, it is the current inferior\n\
1127 that is cloned.\n\
1128 By default, the new inferiors inherit the copied inferior's connection.\n\
1129 If -no-connection is specified, the new inferiors begin with\n\
1130 no target connection yet."));
1131 
1132   add_cmd ("inferiors", class_run, detach_inferior_command, _("\
1133 Detach from inferior ID (or list of IDS).\n\
1134 Usage; detach inferiors ID..."),
1135              &detachlist);
1136 
1137   add_cmd ("inferiors", class_run, kill_inferior_command, _("\
1138 Kill inferior ID (or list of IDs).\n\
1139 Usage: kill inferiors ID..."),
1140              &killlist);
1141 
1142   add_cmd ("inferior", class_run, inferior_command, _("\
1143 Use this command to switch between inferiors.\n\
1144 Usage: inferior ID\n\
1145 The new inferior ID must be currently known."),
1146              &cmdlist);
1147 
1148   add_setshow_boolean_cmd ("inferior-events", no_class,
1149            &print_inferior_events, _("\
1150 Set printing of inferior events (such as inferior start and exit)."), _("\
1151 Show printing of inferior events (such as inferior start and exit)."), NULL,
1152            NULL,
1153            show_print_inferior_events,
1154            &setprintlist, &showprintlist);
1155 
1156   create_internalvar_type_lazy ("_inferior", &inferior_funcs, NULL);
1157 }
1158