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