1 /* Fork a Unix child process, and set up to debug it, for GDB.
2 Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
3 2001 Free Software Foundation, Inc.
4 Contributed by Cygnus Support.
6 This file is part of GDB.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA. */
24 #include "gdb_string.h"
25 #include "frame.h" /* required by inferior.h */
29 #include "gdb_vfork.h"
32 #include "gdbthread.h"
33 #include "command.h" /* for dont_repeat () */
37 /* This just gets used as a default if we can't find SHELL */
39 #define SHELL_FILE "/bin/sh"
42 extern char **environ;
44 /* This function breaks up an argument string into an argument
45 * vector suitable for passing to execvp().
46 * E.g., on "run a b c d" this routine would get as input
47 * the string "a b c d", and as output it would fill in argv with
48 * the four arguments "a", "b", "c", "d".
51 breakup_args (char *scratch, char **argv)
58 /* Scan past leading separators */
59 while (*cp == ' ' || *cp == '\t' || *cp == '\n')
64 /* Break if at end of string */
71 /* Scan for next arg separator */
72 cp = strchr (cp, ' ');
74 cp = strchr (cp, '\t');
76 cp = strchr (cp, '\n');
78 /* No separators => end of string => break */
82 /* Replace the separator with a terminator */
86 /* execv requires a null-terminated arg vector */
92 /* Start an inferior Unix child process and sets inferior_pid to its pid.
93 EXEC_FILE is the file to run.
94 ALLARGS is a string containing the arguments to the program.
95 ENV is the environment vector to pass. SHELL_FILE is the shell file,
96 or NULL if we should pick one. Errors reported with error(). */
98 /* This function is NOT-REENTRANT. Some of the variables have been
99 made static to ensure that they survive the vfork() call. */
102 fork_inferior (char *exec_file_arg, char *allargs, char **env,
103 void (*traceme_fun) (void), void (*init_trace_fun) (int),
104 void (*pre_trace_fun) (void), char *shell_file_arg)
108 static char default_shell_file[] = SHELL_FILE;
110 /* Set debug_fork then attach to the child while it sleeps, to debug. */
111 static int debug_fork = 0;
112 /* This is set to the result of setpgrp, which if vforked, will be visible
113 to you in the parent process. It's only used by humans for debugging. */
114 static int debug_setpgrp = 657473;
115 static char *shell_file;
116 static char *exec_file;
121 /* If no exec file handed to us, get it from the exec-file command -- with
122 a good, common error message if none is specified. */
123 exec_file = exec_file_arg;
125 exec_file = get_exec_file (1);
127 /* STARTUP_WITH_SHELL is defined in inferior.h.
128 * If 0, we'll just do a fork/exec, no shell, so don't
129 * bother figuring out what shell.
131 shell_file = shell_file_arg;
132 if (STARTUP_WITH_SHELL)
134 /* Figure out what shell to start up the user program under. */
135 if (shell_file == NULL)
136 shell_file = getenv ("SHELL");
137 if (shell_file == NULL)
138 shell_file = default_shell_file;
142 /* Multiplying the length of exec_file by 4 is to account for the fact
143 that it may expand when quoted; it is a worst-case number based on
144 every character being '. */
145 len = 5 + 4 * strlen (exec_file) + 1 + strlen (allargs) + 1 + /*slop */ 12;
146 /* If desired, concat something onto the front of ALLARGS.
147 SHELL_COMMAND is the result. */
148 #ifdef SHELL_COMMAND_CONCAT
149 shell_command = (char *) alloca (strlen (SHELL_COMMAND_CONCAT) + len);
150 strcpy (shell_command, SHELL_COMMAND_CONCAT);
152 shell_command = (char *) alloca (len);
153 shell_command[0] = '\0';
158 /* We're going to call execvp. Create argv */
159 /* Largest case: every other character is a separate arg */
160 argv = (char **) xmalloc (((strlen (allargs) + 1) / (unsigned) 2 + 2) * sizeof (*argv));
162 breakup_args (allargs, &argv[1]);
168 /* We're going to call a shell */
170 /* Now add exec_file, quoting as necessary. */
175 strcat (shell_command, "exec ");
177 /* Quoting in this style is said to work with all shells. But csh
178 on IRIX 4.0.1 can't deal with it. So we only quote it if we need
212 strcat (shell_command, "'");
213 for (p = exec_file; *p != '\0'; ++p)
216 strcat (shell_command, "'\\''");
218 strncat (shell_command, p, 1);
220 strcat (shell_command, "'");
223 strcat (shell_command, exec_file);
225 strcat (shell_command, " ");
226 strcat (shell_command, allargs);
230 /* exec is said to fail if the executable is open. */
233 /* Retain a copy of our environment variables, since the child will
234 replace the value of environ and if we're vforked, we have to
236 save_our_env = environ;
238 /* Tell the terminal handling subsystem what tty we plan to run on;
239 it will just record the information for later. */
241 new_tty_prefork (inferior_io_terminal);
243 /* It is generally good practice to flush any possible pending stdio
244 output prior to doing a fork, to avoid the possibility of both the
245 parent and child flushing the same data after the fork. */
247 gdb_flush (gdb_stdout);
248 gdb_flush (gdb_stderr);
250 /* If there's any initialization of the target layers that must happen
251 to prepare to handle the child we're about fork, do it now...
253 if (pre_trace_fun != NULL)
262 perror_with_name ("vfork");
269 /* Run inferior in a separate process group. */
270 debug_setpgrp = gdb_setpgid ();
271 if (debug_setpgrp == -1)
272 perror ("setpgrp failed in child");
274 /* Ask the tty subsystem to switch to the one we specified earlier
275 (or to share the current terminal, if none was specified). */
279 /* Changing the signal handlers for the inferior after
280 a vfork can also change them for the superior, so we don't mess
281 with signals here. See comments in
282 initialize_signals for how we get the right signal handlers
285 /* "Trace me, Dr. Memory!" */
287 /* The call above set this process (the "child") as debuggable
288 * by the original gdb process (the "parent"). Since processes
289 * (unlike people) can have only one parent, if you are
290 * debugging gdb itself (and your debugger is thus _already_ the
291 * controller/parent for this child), code from here on out
292 * is undebuggable. Indeed, you probably got an error message
293 * saying "not parent". Sorry--you'll have to use print statements!
296 /* There is no execlpe call, so we have to set the environment
297 for our child in the global variable. If we've vforked, this
298 clobbers the parent, but environ is restored a few lines down
299 in the parent. By the way, yes we do need to look down the
300 path to find $SHELL. Rich Pixley says so, and I agree. */
303 /* If we decided above to start up with a shell,
305 * "-c" says to interpret the next arg as a shell command
306 * to execute, and this command is "exec <target-program> <args>".
307 * "-f" means "fast startup" to the c-shell, which means
308 * don't do .cshrc file. Doing .cshrc may cause fork/exec
309 * events which will confuse debugger start-up code.
313 execlp (shell_file, shell_file, "-c", shell_command, (char *) 0);
315 /* If we get here, it's an error */
316 fprintf_unfiltered (gdb_stderr, "Cannot exec %s: %s.\n", shell_file,
317 safe_strerror (errno));
318 gdb_flush (gdb_stderr);
323 /* Otherwise, we directly exec the target program with execvp. */
327 execvp (exec_file, argv);
329 /* If we get here, it's an error */
330 errstring = safe_strerror (errno);
331 fprintf_unfiltered (gdb_stderr, "Cannot exec %s ", exec_file);
334 while (argv[i] != NULL)
337 fprintf_unfiltered (gdb_stderr, " ");
338 fprintf_unfiltered (gdb_stderr, "%s", argv[i]);
341 fprintf_unfiltered (gdb_stderr, ".\n");
342 /* This extra info seems to be useless
343 fprintf_unfiltered (gdb_stderr, "Got error %s.\n", errstring);
345 gdb_flush (gdb_stderr);
350 /* Restore our environment in case a vforked child clob'd it. */
351 environ = save_our_env;
355 inferior_pid = pid; /* Needed for wait_for_inferior stuff below */
357 /* Now that we have a child process, make it our target, and
358 initialize anything target-vector-specific that needs initializing. */
360 (*init_trace_fun) (pid);
362 /* We are now in the child process of interest, having exec'd the
363 correct program, and are poised at the first instruction of the
366 /* Allow target dependent code to play with the new process. This might be
367 used to have target-specific code initialize a variable in the new process
368 prior to executing the first instruction. */
369 TARGET_CREATE_INFERIOR_HOOK (pid);
371 #ifdef SOLIB_CREATE_INFERIOR_HOOK
372 SOLIB_CREATE_INFERIOR_HOOK (pid);
376 /* An inferior Unix process CHILD_PID has been created by a call to
377 fork() (or variants like vfork). It is presently stopped, and waiting
378 to be resumed. clone_and_follow_inferior will fork the debugger,
379 and that clone will "follow" (attach to) CHILD_PID. The original copy
380 of the debugger will not touch CHILD_PID again.
382 Also, the original debugger will set FOLLOWED_CHILD FALSE, while the
383 clone will set it TRUE.
386 clone_and_follow_inferior (int child_pid, int *followed_child)
388 extern int auto_solib_add;
392 char pid_spelling[100]; /* Arbitrary but sufficient length. */
394 /* This semaphore is used to coordinate the two debuggers' handoff
395 of CHILD_PID. The original debugger will detach from CHILD_PID,
396 and then the clone debugger will attach to it. (It must be done
397 this way because on some targets, only one process at a time can
398 trace another. Thus, the original debugger must relinquish its
399 tracing rights before the clone can pick them up.)
402 #define SEM_LISTEN (0)
403 int handoff_semaphore[2]; /* Original "talks" to [1], clone "listens" to [0] */
407 /* Set debug_fork then attach to the child while it sleeps, to debug. */
408 static int debug_fork = 0;
410 /* It is generally good practice to flush any possible pending stdio
411 output prior to doing a fork, to avoid the possibility of both the
412 parent and child flushing the same data after the fork. */
414 gdb_flush (gdb_stdout);
415 gdb_flush (gdb_stderr);
417 /* Open the semaphore pipes.
419 status = pipe (handoff_semaphore);
421 error ("error getting pipe for handoff semaphore");
423 /* Clone the debugger. */
426 debugger_pid = fork ();
428 debugger_pid = vfork ();
430 debugger_pid = fork ();
433 if (debugger_pid < 0)
434 perror_with_name ("fork");
436 /* Are we the original debugger? If so, we must relinquish all claims
438 if (debugger_pid != 0)
440 char signal_spelling[100]; /* Arbitrary but sufficient length */
442 /* Detach from CHILD_PID. Deliver a "stop" signal when we do, though,
443 so that it remains stopped until the clone debugger can attach
446 detach_breakpoints (child_pid);
448 sprintf (signal_spelling, "%d", target_signal_to_host (TARGET_SIGNAL_STOP));
449 target_require_detach (child_pid, signal_spelling, 1);
451 /* Notify the clone debugger that it should attach to CHILD_PID. */
452 write (handoff_semaphore[SEM_TALK], &talk_value, sizeof (talk_value));
457 /* We're the child. */
463 /* The child (i.e., the cloned debugger) must now attach to
464 CHILD_PID. inferior_pid is presently set to the parent process
465 of the fork, while CHILD_PID should be the child process of the
468 Wait until the original debugger relinquishes control of CHILD_PID,
471 read (handoff_semaphore[SEM_LISTEN], &listen_value, sizeof (listen_value));
473 /* Note that we DON'T want to actually detach from inferior_pid,
474 because that would allow it to run free. The original
475 debugger wants to retain control of the process. So, we
476 just reset inferior_pid to CHILD_PID, and then ensure that all
477 breakpoints are really set in CHILD_PID.
479 target_mourn_inferior ();
481 /* Ask the tty subsystem to switch to the one we specified earlier
482 (or to share the current terminal, if none was specified). */
487 sprintf (pid_spelling, "%d", child_pid);
488 target_require_attach (pid_spelling, 1);
490 /* Perform any necessary cleanup, after attachment. (This form
491 of attaching can behave differently on some targets than the
492 standard method, where a process formerly not under debugger
493 control was suddenly attached to..)
495 target_post_follow_inferior_by_clone ();
500 /* Discard the handoff sempahore. */
501 (void) close (handoff_semaphore[SEM_LISTEN]);
502 (void) close (handoff_semaphore[SEM_TALK]);
505 /* Accept NTRAPS traps from the inferior. */
508 startup_inferior (int ntraps)
510 int pending_execs = ntraps;
511 int terminal_initted;
513 /* The process was started by the fork that created it,
514 but it will have stopped one instruction after execing the shell.
515 Here we must get it up to actual execution of the real program. */
517 clear_proceed_status ();
519 init_wait_for_inferior ();
521 terminal_initted = 0;
523 if (STARTUP_WITH_SHELL)
524 inferior_ignoring_startup_exec_events = ntraps;
526 inferior_ignoring_startup_exec_events = 0;
527 inferior_ignoring_leading_exec_events =
528 target_reported_exec_events_per_exec_call () - 1;
530 #ifdef STARTUP_INFERIOR
531 STARTUP_INFERIOR (pending_execs);
535 stop_soon_quietly = 1; /* Make wait_for_inferior be quiet */
536 wait_for_inferior ();
537 if (stop_signal != TARGET_SIGNAL_TRAP)
539 /* Let shell child handle its own signals in its own way */
540 /* FIXME, what if child has exit()ed? Must exit loop somehow */
541 resume (0, stop_signal);
545 /* We handle SIGTRAP, however; it means child did an exec. */
546 if (!terminal_initted)
548 /* Now that the child has exec'd we know it has already set its
549 process group. On POSIX systems, tcsetpgrp will fail with
550 EPERM if we try it before the child's setpgid. */
552 /* Set up the "saved terminal modes" of the inferior
553 based on what modes we are starting it with. */
554 target_terminal_init ();
556 /* Install inferior's terminal modes. */
557 target_terminal_inferior ();
559 terminal_initted = 1;
562 pending_execs = pending_execs - 1;
563 if (0 == pending_execs)
566 resume (0, TARGET_SIGNAL_0); /* Just make it go on */
569 #endif /* STARTUP_INFERIOR */
570 stop_soon_quietly = 0;