1 /* Fork a Unix child process, and set up to debug it, for GDB.
3 Copyright (C) 1990-2017 Free Software Foundation, Inc.
5 Contributed by Cygnus Support.
7 This file is part of GDB.
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.
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.
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/>. */
27 #include "gdb_vfork.h"
29 #include "gdbthread.h"
30 #include "command.h" /* for dont_repeat () */
33 #include "filestuff.h"
35 #include "signals-state-save-restore.h"
39 /* This just gets used as a default if we can't find SHELL. */
40 #define SHELL_FILE "/bin/sh"
42 extern char **environ
;
44 static char *exec_wrapper
;
46 /* Build the argument vector for execv(3). */
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
);
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. */
65 return const_cast<char **> (&m_argv
[0]);
69 /* Disable copying. */
70 execv_argv (const execv_argv
&) = delete;
71 void operator= (const execv_argv
&) = delete;
73 /* Helper methods for constructing the argument vector. */
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
);
80 /* Used when building an argv for execing a shell that execs the
82 void init_for_shell (const char *exec_file
,
83 const std::string
&allargs
,
84 const char *shell_file
);
86 /* The argument vector built. Holds non-owning pointers. Elements
87 either point to the strings passed to the execv_argv ctor, or
89 std::vector
<const char *> m_argv
;
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
;
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
107 execv_argv::init_for_no_shell (const char *exec_file
,
108 const std::string
&allargs
)
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
;
117 m_argv
.push_back (exec_file
);
119 for (size_t cur_pos
= 0; cur_pos
< args_copy
.size ();)
121 /* Skip whitespace-like chars. */
122 std::size_t pos
= args_copy
.find_first_not_of (" \t\n", cur_pos
);
124 if (pos
!= std::string::npos
)
127 /* Find the position of the next separator. */
128 std::size_t next_sep
= args_copy
.find_first_of (" \t\n", cur_pos
);
130 if (next_sep
== std::string::npos
)
132 /* No separator found, which means this is the last
134 next_sep
= args_copy
.size ();
138 /* Replace the separator with a terminator. */
139 args_copy
[next_sep
++] = '\0';
142 m_argv
.push_back (&args_copy
[cur_pos
]);
147 /* NULL-terminate the vector. */
148 m_argv
.push_back (NULL
);
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. */
156 escape_bang_in_quoted_argument (const char *shell_file
)
158 size_t shell_file_len
= strlen (shell_file
);
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. */
164 if (shell_file_len
< 3)
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')
175 /* See declaration. */
177 execv_argv::execv_argv (const char *exec_file
,
178 const std::string
&allargs
,
179 const char *shell_file
)
181 if (shell_file
== NULL
)
182 init_for_no_shell (exec_file
, allargs
);
184 init_for_shell (exec_file
, allargs
, shell_file
);
187 /* See declaration. */
190 execv_argv::init_for_shell (const char *exec_file
,
191 const std::string
&allargs
,
192 const char *shell_file
)
194 /* We're going to call a shell. */
195 bool escape_bang
= escape_bang_in_quoted_argument (shell_file
);
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
;
201 shell_command
= "exec ";
203 /* Add any exec wrapper. That may be a program name with arguments,
204 so the user must handle quoting. */
207 shell_command
+= exec_wrapper
;
208 shell_command
+= ' ';
211 /* Now add exec_file, quoting as necessary. */
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
217 const char *p
= exec_file
;
235 need_to_quote
= true;
239 need_to_quote
= false;
250 shell_command
+= '\'';
251 for (p
= exec_file
; *p
!= '\0'; ++p
)
254 shell_command
+= "'\\''";
255 else if (*p
== '!' && escape_bang
)
256 shell_command
+= "\\!";
260 shell_command
+= '\'';
263 shell_command
+= exec_file
;
265 shell_command
+= ' ' + allargs
;
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>". */
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
);
277 /* See inferior.h. */
280 trace_start_error (const char *fmt
, ...)
285 fprintf_unfiltered (gdb_stderr
, "Could not trace the inferior "
286 "process.\nError: ");
287 vfprintf_unfiltered (gdb_stderr
, fmt
, ap
);
290 gdb_flush (gdb_stderr
);
294 /* See inferior.h. */
297 trace_start_error_with_name (const char *string
)
299 trace_start_error ("%s: %s", string
, safe_strerror (errno
));
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
309 /* This function is NOT reentrant. Some of the variables have been
310 made static to ensure that they survive the vfork call. */
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
,
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
;
330 const char *inferior_io_terminal
= get_inferior_io_terminal ();
331 struct inferior
*inf
;
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);
341 exec_file
= exec_file_arg
;
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
)
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
;
358 /* Build the argument vector. */
359 execv_argv
child_argv (exec_file
, allargs
, shell_file
);
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
364 save_our_env
= environ
;
366 /* Likewise the current UI. */
367 save_ui
= current_ui
;
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
);
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
);
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
382 if (pre_trace_fun
!= NULL
)
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
)
402 perror_with_name (("vfork"));
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
410 current_ui
= main_ui
;
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
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)
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"));
432 /* Ask the tty subsystem to switch to the one we specified
433 earlier (or to share the current terminal, if none was
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
443 /* "Trace me, Dr. Memory!" */
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
455 restore_original_signals_state ();
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. */
464 char **argv
= child_argv
.argv ();
466 if (exec_fun
!= NULL
)
467 (*exec_fun
) (argv
[0], &argv
[0], env
);
469 execvp (argv
[0], &argv
[0]);
471 /* If we get here, it's an error. */
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
);
483 /* Restore our environment in case a vforked child clob'd it. */
484 environ
= save_our_env
;
486 /* Likewise the current UI. */
487 current_ui
= save_ui
;
489 if (!have_inferiors ())
492 inf
= current_inferior ();
494 inferior_appeared (inf
, pid
);
496 /* Needed for wait_for_inferior stuff below. */
497 inferior_ptid
= pid_to_ptid (pid
);
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
505 add_thread_silent (inferior_ptid
);
507 /* Now that we have a child process, make it our target, and
508 initialize anything target-vector-specific that needs
511 (*init_trace_fun
) (pid
);
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
519 /* Accept NTRAPS traps from the inferior. */
522 startup_inferior (int ntraps
)
524 int pending_execs
= ntraps
;
525 int terminal_initted
= 0;
528 if (startup_with_shell
)
530 /* One trap extra for exec'ing the shell. */
534 if (target_supports_multi_process ())
535 resume_ptid
= pid_to_ptid (ptid_get_pid (inferior_ptid
));
537 resume_ptid
= minus_one_ptid
;
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. */
548 enum gdb_signal resume_signal
= GDB_SIGNAL_0
;
551 struct target_waitstatus ws
;
552 memset (&ws
, 0, sizeof (ws
));
553 event_ptid
= target_wait (resume_ptid
, &ws
, 0);
555 if (ws
.kind
== TARGET_WAITKIND_IGNORE
)
556 /* The inferior didn't really stop, keep waiting. */
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
);
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
));
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."),
586 error (_("During startup program exited normally."));
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
);
596 case TARGET_WAITKIND_STOPPED
:
597 resume_signal
= ws
.value
.sig
;
598 switch_to_thread (event_ptid
);
602 if (resume_signal
!= GDB_SIGNAL_TRAP
)
604 /* Let shell child handle its own signals in its own way. */
605 target_continue (resume_ptid
, resume_signal
);
609 /* We handle SIGTRAP, however; it means child did an exec. */
610 if (!terminal_initted
)
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
617 /* Set up the "saved terminal modes" of the inferior
618 based on what modes we are starting it with. */
619 target_terminal_init ();
621 /* Install inferior's terminal modes. */
622 target_terminal_inferior ();
624 terminal_initted
= 1;
627 if (--pending_execs
== 0)
630 /* Just make it go on. */
631 target_continue_no_signal (resume_ptid
);
635 /* Mark all threads non-executing. */
636 set_executing (resume_ptid
, 0);
639 /* Implement the "unset exec-wrapper" command. */
642 unset_exec_wrapper_command (char *args
, int from_tty
)
644 xfree (exec_wrapper
);
649 show_startup_with_shell (struct ui_file
*file
, int from_tty
,
650 struct cmd_list_element
*c
, const char *value
)
652 fprintf_filtered (file
,
653 _("Use of shell to start subprocesses is %s.\n"),
657 /* Provide a prototype to silence -Wmissing-prototypes. */
658 extern initialize_file_ftype _initialize_fork_child
;
661 _initialize_fork_child (void)
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."),
667 Show the wrapper for running programs."), NULL
,
669 &setlist
, &showlist
);
671 add_cmd ("exec-wrapper", class_run
, unset_exec_wrapper_command
,
672 _("Disable use of an execution wrapper."),
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
,
680 show_startup_with_shell
,
681 &setlist
, &showlist
);