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