Move parts of inferior job control to common/
[external/binutils.git] / gdb / fork-child.c
1 /* Fork a Unix child process, and set up to debug it, for GDB.
2
3    Copyright (C) 1990-2017 Free Software Foundation, Inc.
4
5    Contributed by Cygnus Support.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "terminal.h"
25 #include "target.h"
26 #include "gdb_wait.h"
27 #include "gdb_vfork.h"
28 #include "gdbcore.h"
29 #include "gdbthread.h"
30 #include "command.h" /* for dont_repeat () */
31 #include "gdbcmd.h"
32 #include "solib.h"
33 #include "filestuff.h"
34 #include "top.h"
35 #include "signals-state-save-restore.h"
36 #include "job-control.h"
37 #include <signal.h>
38 #include <vector>
39
40 /* This just gets used as a default if we can't find SHELL.  */
41 #define SHELL_FILE "/bin/sh"
42
43 extern char **environ;
44
45 static char *exec_wrapper;
46
47 /* Build the argument vector for execv(3).  */
48
49 class execv_argv
50 {
51 public:
52   /* EXEC_FILE is the file to run.  ALLARGS is a string containing the
53      arguments to the program.  If starting with a shell, SHELL_FILE
54      is the shell to run.  Otherwise, SHELL_FILE is NULL.  */
55   execv_argv (const char *exec_file, const std::string &allargs,
56               const char *shell_file);
57
58   /* Return a pointer to the built argv, in the type expected by
59      execv.  The result is (only) valid for as long as this execv_argv
60      object is live.  We return a "char **" because that's the type
61      that the execv functions expect.  Note that it is guaranteed that
62      the execv functions do not modify the argv[] array nor the
63      strings to which the array point.  */
64   char **argv ()
65   {
66     return const_cast<char **> (&m_argv[0]);
67   }
68
69 private:
70   /* Disable copying.  */
71   execv_argv (const execv_argv &) = delete;
72   void operator= (const execv_argv &) = delete;
73
74   /* Helper methods for constructing the argument vector.  */
75
76   /* Used when building an argv for a straight execv call, without
77      going via the shell.  */
78   void init_for_no_shell (const char *exec_file,
79                           const std::string &allargs);
80
81   /* Used when building an argv for execing a shell that execs the
82      child program.  */
83   void init_for_shell (const char *exec_file,
84                        const std::string &allargs,
85                        const char *shell_file);
86
87   /* The argument vector built.  Holds non-owning pointers.  Elements
88      either point to the strings passed to the execv_argv ctor, or
89      inside M_STORAGE.  */
90   std::vector<const char *> m_argv;
91
92   /* Storage.  In the no-shell case, this contains a copy of the
93      arguments passed to the ctor, split by '\0'.  In the shell case,
94      this contains the quoted shell command.  I.e., SHELL_COMMAND in
95      {"$SHELL" "-c", SHELL_COMMAND, NULL}.  */
96   std::string m_storage;
97 };
98
99 /* Create argument vector for straight call to execvp.  Breaks up
100    ALLARGS into an argument vector suitable for passing to execvp and
101    stores it in M_ARGV.  E.g., on "run a b c d" this routine would get
102    as input the string "a b c d", and as output it would fill in
103    M_ARGV with the four arguments "a", "b", "c", "d".  Each argument
104    in M_ARGV points to a substring of a copy of ALLARGS stored in
105    M_STORAGE.  */
106
107 void
108 execv_argv::init_for_no_shell (const char *exec_file,
109                                const std::string &allargs)
110 {
111
112   /* Save/work with a copy stored in our storage.  The pointers pushed
113      to M_ARGV point directly into M_STORAGE, which is modified in
114      place with the necessary NULL terminators.  This avoids N heap
115      allocations and string dups when 1 is sufficient.  */
116   std::string &args_copy = m_storage = allargs;
117
118   m_argv.push_back (exec_file);
119
120   for (size_t cur_pos = 0; cur_pos < args_copy.size ();)
121     {
122       /* Skip whitespace-like chars.  */
123       std::size_t pos = args_copy.find_first_not_of (" \t\n", cur_pos);
124
125       if (pos != std::string::npos)
126         cur_pos = pos;
127
128       /* Find the position of the next separator.  */
129       std::size_t next_sep = args_copy.find_first_of (" \t\n", cur_pos);
130
131       if (next_sep == std::string::npos)
132         {
133           /* No separator found, which means this is the last
134              argument.  */
135           next_sep = args_copy.size ();
136         }
137       else
138         {
139           /* Replace the separator with a terminator.  */
140           args_copy[next_sep++] = '\0';
141         }
142
143       m_argv.push_back (&args_copy[cur_pos]);
144
145       cur_pos = next_sep;
146     }
147
148   /* NULL-terminate the vector.  */
149   m_argv.push_back (NULL);
150 }
151
152 /* When executing a command under the given shell, return true if the
153    '!' character should be escaped when embedded in a quoted
154    command-line argument.  */
155
156 static bool
157 escape_bang_in_quoted_argument (const char *shell_file)
158 {
159   size_t shell_file_len = strlen (shell_file);
160
161   /* Bang should be escaped only in C Shells.  For now, simply check
162      that the shell name ends with 'csh', which covers at least csh
163      and tcsh.  This should be good enough for now.  */
164
165   if (shell_file_len < 3)
166     return false;
167
168   if (shell_file[shell_file_len - 3] == 'c'
169       && shell_file[shell_file_len - 2] == 's'
170       && shell_file[shell_file_len - 1] == 'h')
171     return true;
172
173   return false;
174 }
175
176 /* See declaration.  */
177
178 execv_argv::execv_argv (const char *exec_file,
179                         const std::string &allargs,
180                         const char *shell_file)
181 {
182   if (shell_file == NULL)
183     init_for_no_shell (exec_file, allargs);
184   else
185     init_for_shell (exec_file, allargs, shell_file);
186 }
187
188 /* See declaration.  */
189
190 void
191 execv_argv::init_for_shell (const char *exec_file,
192                             const std::string &allargs,
193                             const char *shell_file)
194 {
195   /* We're going to call a shell.  */
196   bool escape_bang = escape_bang_in_quoted_argument (shell_file);
197
198   /* We need to build a new shell command string, and make argv point
199      to it.  So build it in the storage.  */
200   std::string &shell_command = m_storage;
201
202   shell_command = "exec ";
203
204   /* Add any exec wrapper.  That may be a program name with arguments,
205      so the user must handle quoting.  */
206   if (exec_wrapper)
207     {
208       shell_command += exec_wrapper;
209       shell_command += ' ';
210     }
211
212   /* Now add exec_file, quoting as necessary.  */
213
214   /* Quoting in this style is said to work with all shells.  But csh
215      on IRIX 4.0.1 can't deal with it.  So we only quote it if we need
216      to.  */
217   bool need_to_quote;
218   const char *p = exec_file;
219   while (1)
220     {
221       switch (*p)
222         {
223         case '\'':
224         case '!':
225         case '"':
226         case '(':
227         case ')':
228         case '$':
229         case '&':
230         case ';':
231         case '<':
232         case '>':
233         case ' ':
234         case '\n':
235         case '\t':
236           need_to_quote = true;
237           goto end_scan;
238
239         case '\0':
240           need_to_quote = false;
241           goto end_scan;
242
243         default:
244           break;
245         }
246       ++p;
247     }
248  end_scan:
249   if (need_to_quote)
250     {
251       shell_command += '\'';
252       for (p = exec_file; *p != '\0'; ++p)
253         {
254           if (*p == '\'')
255             shell_command += "'\\''";
256           else if (*p == '!' && escape_bang)
257             shell_command += "\\!";
258           else
259             shell_command += *p;
260         }
261       shell_command += '\'';
262     }
263   else
264     shell_command += exec_file;
265
266   shell_command += ' ' + allargs;
267
268   /* If we decided above to start up with a shell, we exec the shell.
269      "-c" says to interpret the next arg as a shell command to
270      execute, and this command is "exec <target-program> <args>".  */
271   m_argv.reserve (4);
272   m_argv.push_back (shell_file);
273   m_argv.push_back ("-c");
274   m_argv.push_back (shell_command.c_str ());
275   m_argv.push_back (NULL);
276 }
277
278 /* See inferior.h.  */
279
280 void
281 trace_start_error (const char *fmt, ...)
282 {
283   va_list ap;
284
285   va_start (ap, fmt);
286   fprintf_unfiltered (gdb_stderr, "Could not trace the inferior "
287                                   "process.\nError: ");
288   vfprintf_unfiltered (gdb_stderr, fmt, ap);
289   va_end (ap);
290
291   gdb_flush (gdb_stderr);
292   _exit (0177);
293 }
294
295 /* See inferior.h.  */
296
297 void
298 trace_start_error_with_name (const char *string)
299 {
300   trace_start_error ("%s: %s", string, safe_strerror (errno));
301 }
302
303 /* Start an inferior Unix child process and sets inferior_ptid to its
304    pid.  EXEC_FILE is the file to run.  ALLARGS is a string containing
305    the arguments to the program.  ENV is the environment vector to
306    pass.  SHELL_FILE is the shell file, or NULL if we should pick
307    one.  EXEC_FUN is the exec(2) function to use, or NULL for the default
308    one.  */
309
310 /* This function is NOT reentrant.  Some of the variables have been
311    made static to ensure that they survive the vfork call.  */
312
313 int
314 fork_inferior (const char *exec_file_arg, const std::string &allargs,
315                char **env, void (*traceme_fun) (void),
316                void (*init_trace_fun) (int), void (*pre_trace_fun) (void),
317                char *shell_file_arg,
318                void (*exec_fun)(const char *file, char * const *argv,
319                                 char * const *env))
320 {
321   int pid;
322   static char default_shell_file[] = SHELL_FILE;
323   /* Set debug_fork then attach to the child while it sleeps, to debug.  */
324   static int debug_fork = 0;
325   /* This is set to the result of setpgrp, which if vforked, will be visible
326      to you in the parent process.  It's only used by humans for debugging.  */
327   static int debug_setpgrp = 657473;
328   static char *shell_file;
329   static const char *exec_file;
330   char **save_our_env;
331   const char *inferior_io_terminal = get_inferior_io_terminal ();
332   struct inferior *inf;
333   int i;
334   int save_errno;
335   struct ui *save_ui;
336
337   /* If no exec file handed to us, get it from the exec-file command
338      -- with a good, common error message if none is specified.  */
339   if (exec_file_arg == NULL)
340     exec_file = get_exec_file (1);
341   else
342     exec_file = exec_file_arg;
343
344   /* 'startup_with_shell' is declared in inferior.h and bound to the
345      "set startup-with-shell" option.  If 0, we'll just do a
346      fork/exec, no shell, so don't bother figuring out what shell.  */
347   if (startup_with_shell)
348     {
349       shell_file = shell_file_arg;
350       /* Figure out what shell to start up the user program under.  */
351       if (shell_file == NULL)
352         shell_file = getenv ("SHELL");
353       if (shell_file == NULL)
354         shell_file = default_shell_file;
355     }
356   else
357     shell_file = NULL;
358
359   /* Build the argument vector.  */
360   execv_argv child_argv (exec_file, allargs, shell_file);
361
362   /* Retain a copy of our environment variables, since the child will
363      replace the value of environ and if we're vforked, we have to
364      restore it.  */
365   save_our_env = environ;
366
367   /* Likewise the current UI.  */
368   save_ui = current_ui;
369
370   /* Tell the terminal handling subsystem what tty we plan to run on;
371      it will just record the information for later.  */
372   new_tty_prefork (inferior_io_terminal);
373
374   /* It is generally good practice to flush any possible pending stdio
375      output prior to doing a fork, to avoid the possibility of both
376      the parent and child flushing the same data after the fork.  */
377   gdb_flush (main_ui->m_gdb_stdout);
378   gdb_flush (main_ui->m_gdb_stderr);
379
380   /* If there's any initialization of the target layers that must
381      happen to prepare to handle the child we're about fork, do it
382      now...  */
383   if (pre_trace_fun != NULL)
384     (*pre_trace_fun) ();
385
386   /* Create the child process.  Since the child process is going to
387      exec(3) shortly afterwards, try to reduce the overhead by
388      calling vfork(2).  However, if PRE_TRACE_FUN is non-null, it's
389      likely that this optimization won't work since there's too much
390      work to do between the vfork(2) and the exec(3).  This is known
391      to be the case on ttrace(2)-based HP-UX, where some handshaking
392      between parent and child needs to happen between fork(2) and
393      exec(2).  However, since the parent is suspended in the vforked
394      state, this doesn't work.  Also note that the vfork(2) call might
395      actually be a call to fork(2) due to the fact that autoconf will
396      ``#define vfork fork'' on certain platforms.  */
397   if (pre_trace_fun || debug_fork)
398     pid = fork ();
399   else
400     pid = vfork ();
401
402   if (pid < 0)
403     perror_with_name (("vfork"));
404
405   if (pid == 0)
406     {
407       /* Switch to the main UI, so that gdb_std{in/out/err} in the
408          child are mapped to std{in/out/err}.  This makes it possible
409          to use fprintf_unfiltered/warning/error/etc. in the child
410          from here on.  */
411       current_ui = main_ui;
412
413       /* Close all file descriptors except those that gdb inherited
414          (usually 0/1/2), so they don't leak to the inferior.  Note
415          that this closes the file descriptors of all secondary
416          UIs.  */
417       close_most_fds ();
418
419       if (debug_fork)
420         sleep (debug_fork);
421
422       /* Create a new session for the inferior process, if necessary.
423          It will also place the inferior in a separate process group.  */
424       if (create_tty_session () <= 0)
425         {
426           /* No session was created, but we still want to run the inferior
427              in a separate process group.  */
428           debug_setpgrp = gdb_setpgid ();
429           if (debug_setpgrp == -1)
430             perror (_("setpgrp failed in child"));
431         }
432
433       /* Ask the tty subsystem to switch to the one we specified
434          earlier (or to share the current terminal, if none was
435          specified).  */
436       new_tty ();
437
438       /* Changing the signal handlers for the inferior after
439          a vfork can also change them for the superior, so we don't mess
440          with signals here.  See comments in
441          initialize_signals for how we get the right signal handlers
442          for the inferior.  */
443
444       /* "Trace me, Dr. Memory!"  */
445       (*traceme_fun) ();
446
447       /* The call above set this process (the "child") as debuggable
448         by the original gdb process (the "parent").  Since processes
449         (unlike people) can have only one parent, if you are debugging
450         gdb itself (and your debugger is thus _already_ the
451         controller/parent for this child), code from here on out is
452         undebuggable.  Indeed, you probably got an error message
453         saying "not parent".  Sorry; you'll have to use print
454         statements!  */
455
456       restore_original_signals_state ();
457
458       /* There is no execlpe call, so we have to set the environment
459          for our child in the global variable.  If we've vforked, this
460          clobbers the parent, but environ is restored a few lines down
461          in the parent.  By the way, yes we do need to look down the
462          path to find $SHELL.  Rich Pixley says so, and I agree.  */
463       environ = env;
464
465       char **argv = child_argv.argv ();
466
467       if (exec_fun != NULL)
468         (*exec_fun) (argv[0], &argv[0], env);
469       else
470         execvp (argv[0], &argv[0]);
471
472       /* If we get here, it's an error.  */
473       save_errno = errno;
474       fprintf_unfiltered (gdb_stderr, "Cannot exec %s", argv[0]);
475       for (i = 1; argv[i] != NULL; i++)
476         fprintf_unfiltered (gdb_stderr, " %s", argv[i]);
477       fprintf_unfiltered (gdb_stderr, ".\n");
478       fprintf_unfiltered (gdb_stderr, "Error: %s\n",
479                           safe_strerror (save_errno));
480       gdb_flush (gdb_stderr);
481       _exit (0177);
482     }
483
484   /* Restore our environment in case a vforked child clob'd it.  */
485   environ = save_our_env;
486
487   /* Likewise the current UI.  */
488   current_ui = save_ui;
489
490   if (!have_inferiors ())
491     init_thread_list ();
492
493   inf = current_inferior ();
494
495   inferior_appeared (inf, pid);
496
497   /* Needed for wait_for_inferior stuff below.  */
498   inferior_ptid = pid_to_ptid (pid);
499
500   new_tty_postfork ();
501
502   /* We have something that executes now.  We'll be running through
503      the shell at this point, but the pid shouldn't change.  Targets
504      supporting MT should fill this task's ptid with more data as soon
505      as they can.  */
506   add_thread_silent (inferior_ptid);
507
508   /* Now that we have a child process, make it our target, and
509      initialize anything target-vector-specific that needs
510      initializing.  */
511   if (init_trace_fun)
512     (*init_trace_fun) (pid);
513
514   /* We are now in the child process of interest, having exec'd the
515      correct program, and are poised at the first instruction of the
516      new program.  */
517   return pid;
518 }
519
520 /* Accept NTRAPS traps from the inferior.  */
521
522 void
523 startup_inferior (int ntraps)
524 {
525   int pending_execs = ntraps;
526   int terminal_initted = 0;
527   ptid_t resume_ptid;
528
529   if (startup_with_shell)
530     {
531       /* One trap extra for exec'ing the shell.  */
532       pending_execs++;
533     }
534
535   if (target_supports_multi_process ())
536     resume_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
537   else
538     resume_ptid = minus_one_ptid;
539
540   /* The process was started by the fork that created it, but it will
541      have stopped one instruction after execing the shell.  Here we
542      must get it up to actual execution of the real program.  */
543
544   if (exec_wrapper)
545     pending_execs++;
546
547   while (1)
548     {
549       enum gdb_signal resume_signal = GDB_SIGNAL_0;
550       ptid_t event_ptid;
551
552       struct target_waitstatus ws;
553       memset (&ws, 0, sizeof (ws));
554       event_ptid = target_wait (resume_ptid, &ws, 0);
555
556       if (ws.kind == TARGET_WAITKIND_IGNORE)
557         /* The inferior didn't really stop, keep waiting.  */
558         continue;
559
560       switch (ws.kind)
561         {
562           case TARGET_WAITKIND_SPURIOUS:
563           case TARGET_WAITKIND_LOADED:
564           case TARGET_WAITKIND_FORKED:
565           case TARGET_WAITKIND_VFORKED:
566           case TARGET_WAITKIND_SYSCALL_ENTRY:
567           case TARGET_WAITKIND_SYSCALL_RETURN:
568             /* Ignore gracefully during startup of the inferior.  */
569             switch_to_thread (event_ptid);
570             break;
571
572           case TARGET_WAITKIND_SIGNALLED:
573             target_terminal_ours ();
574             target_mourn_inferior (event_ptid);
575             error (_("During startup program terminated with signal %s, %s."),
576                    gdb_signal_to_name (ws.value.sig),
577                    gdb_signal_to_string (ws.value.sig));
578             return;
579
580           case TARGET_WAITKIND_EXITED:
581             target_terminal_ours ();
582             target_mourn_inferior (event_ptid);
583             if (ws.value.integer)
584               error (_("During startup program exited with code %d."),
585                      ws.value.integer);
586             else
587               error (_("During startup program exited normally."));
588             return;
589
590           case TARGET_WAITKIND_EXECD:
591             /* Handle EXEC signals as if they were SIGTRAP signals.  */
592             xfree (ws.value.execd_pathname);
593             resume_signal = GDB_SIGNAL_TRAP;
594             switch_to_thread (event_ptid);
595             break;
596
597           case TARGET_WAITKIND_STOPPED:
598             resume_signal = ws.value.sig;
599             switch_to_thread (event_ptid);
600             break;
601         }
602
603       if (resume_signal != GDB_SIGNAL_TRAP)
604         {
605           /* Let shell child handle its own signals in its own way.  */
606           target_continue (resume_ptid, resume_signal);
607         }
608       else
609         {
610           /* We handle SIGTRAP, however; it means child did an exec.  */
611           if (!terminal_initted)
612             {
613               /* Now that the child has exec'd we know it has already
614                  set its process group.  On POSIX systems, tcsetpgrp
615                  will fail with EPERM if we try it before the child's
616                  setpgid.  */
617
618               /* Set up the "saved terminal modes" of the inferior
619                  based on what modes we are starting it with.  */
620               target_terminal_init ();
621
622               /* Install inferior's terminal modes.  */
623               target_terminal_inferior ();
624
625               terminal_initted = 1;
626             }
627
628           if (--pending_execs == 0)
629             break;
630
631           /* Just make it go on.  */
632           target_continue_no_signal (resume_ptid);
633         }
634     }
635
636   /* Mark all threads non-executing.  */
637   set_executing (resume_ptid, 0);
638 }
639
640 /* Implement the "unset exec-wrapper" command.  */
641
642 static void
643 unset_exec_wrapper_command (char *args, int from_tty)
644 {
645   xfree (exec_wrapper);
646   exec_wrapper = NULL;
647 }
648
649 static void
650 show_startup_with_shell (struct ui_file *file, int from_tty,
651                          struct cmd_list_element *c, const char *value)
652 {
653   fprintf_filtered (file,
654                     _("Use of shell to start subprocesses is %s.\n"),
655                     value);
656 }
657
658 /* Provide a prototype to silence -Wmissing-prototypes.  */
659 extern initialize_file_ftype _initialize_fork_child;
660
661 void
662 _initialize_fork_child (void)
663 {
664   add_setshow_filename_cmd ("exec-wrapper", class_run, &exec_wrapper, _("\
665 Set a wrapper for running programs.\n\
666 The wrapper prepares the system and environment for the new program."),
667                             _("\
668 Show the wrapper for running programs."), NULL,
669                             NULL, NULL,
670                             &setlist, &showlist);
671
672   add_cmd ("exec-wrapper", class_run, unset_exec_wrapper_command,
673            _("Disable use of an execution wrapper."),
674            &unsetlist);
675
676   add_setshow_boolean_cmd ("startup-with-shell", class_support,
677                            &startup_with_shell, _("\
678 Set use of shell to start subprocesses.  The default is on."), _("\
679 Show use of shell to start subprocesses."), NULL,
680                            NULL,
681                            show_startup_with_shell,
682                            &setlist, &showlist);
683 }