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