Update/correct copyright notices.
[deliverable/binutils-gdb.git] / gdb / fork-child.c
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.
5
6 This file is part of GDB.
7
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.
12
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.
17
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. */
22
23 #include "defs.h"
24 #include "gdb_string.h"
25 #include "frame.h" /* required by inferior.h */
26 #include "inferior.h"
27 #include "target.h"
28 #include "gdb_wait.h"
29 #include "gdb_vfork.h"
30 #include "gdbcore.h"
31 #include "terminal.h"
32 #include "gdbthread.h"
33 #include "command.h" /* for dont_repeat () */
34
35 #include <signal.h>
36
37 /* This just gets used as a default if we can't find SHELL */
38 #ifndef SHELL_FILE
39 #define SHELL_FILE "/bin/sh"
40 #endif
41
42 extern char **environ;
43
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".
49 */
50 static void
51 breakup_args (char *scratch, char **argv)
52 {
53 char *cp = scratch;
54
55 for (;;)
56 {
57
58 /* Scan past leading separators */
59 while (*cp == ' ' || *cp == '\t' || *cp == '\n')
60 {
61 cp++;
62 }
63
64 /* Break if at end of string */
65 if (*cp == '\0')
66 break;
67
68 /* Take an arg */
69 *argv++ = cp;
70
71 /* Scan for next arg separator */
72 cp = strchr (cp, ' ');
73 if (cp == NULL)
74 cp = strchr (cp, '\t');
75 if (cp == NULL)
76 cp = strchr (cp, '\n');
77
78 /* No separators => end of string => break */
79 if (cp == NULL)
80 break;
81
82 /* Replace the separator with a terminator */
83 *cp++ = '\0';
84 }
85
86 /* execv requires a null-terminated arg vector */
87 *argv = NULL;
88
89 }
90
91
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(). */
97
98 void
99 fork_inferior (char *exec_file, char *allargs, char **env,
100 void (*traceme_fun) (void), void (*init_trace_fun) (int),
101 void (*pre_trace_fun) (void), char *shell_file)
102 {
103 int pid;
104 char *shell_command;
105 static char default_shell_file[] = SHELL_FILE;
106 int len;
107 /* Set debug_fork then attach to the child while it sleeps, to debug. */
108 static int debug_fork = 0;
109 /* This is set to the result of setpgrp, which if vforked, will be visible
110 to you in the parent process. It's only used by humans for debugging. */
111 static int debug_setpgrp = 657473;
112 char **save_our_env;
113 int shell = 0;
114 char **argv;
115
116 /* If no exec file handed to us, get it from the exec-file command -- with
117 a good, common error message if none is specified. */
118 if (exec_file == 0)
119 exec_file = get_exec_file (1);
120
121 /* STARTUP_WITH_SHELL is defined in inferior.h.
122 * If 0, we'll just do a fork/exec, no shell, so don't
123 * bother figuring out what shell.
124 */
125 if (STARTUP_WITH_SHELL)
126 {
127 /* Figure out what shell to start up the user program under. */
128 if (shell_file == NULL)
129 shell_file = getenv ("SHELL");
130 if (shell_file == NULL)
131 shell_file = default_shell_file;
132 shell = 1;
133 }
134
135 /* Multiplying the length of exec_file by 4 is to account for the fact
136 that it may expand when quoted; it is a worst-case number based on
137 every character being '. */
138 len = 5 + 4 * strlen (exec_file) + 1 + strlen (allargs) + 1 + /*slop */ 12;
139 /* If desired, concat something onto the front of ALLARGS.
140 SHELL_COMMAND is the result. */
141 #ifdef SHELL_COMMAND_CONCAT
142 shell_command = (char *) alloca (strlen (SHELL_COMMAND_CONCAT) + len);
143 strcpy (shell_command, SHELL_COMMAND_CONCAT);
144 #else
145 shell_command = (char *) alloca (len);
146 shell_command[0] = '\0';
147 #endif
148
149 if (!shell)
150 {
151 /* We're going to call execvp. Create argv */
152 /* Largest case: every other character is a separate arg */
153 argv = (char **) xmalloc (((strlen (allargs) + 1) / (unsigned) 2 + 2) * sizeof (*argv));
154 argv[0] = exec_file;
155 breakup_args (allargs, &argv[1]);
156
157 }
158 else
159 {
160
161 /* We're going to call a shell */
162
163 /* Now add exec_file, quoting as necessary. */
164
165 char *p;
166 int need_to_quote;
167
168 strcat (shell_command, "exec ");
169
170 /* Quoting in this style is said to work with all shells. But csh
171 on IRIX 4.0.1 can't deal with it. So we only quote it if we need
172 to. */
173 p = exec_file;
174 while (1)
175 {
176 switch (*p)
177 {
178 case '\'':
179 case '"':
180 case '(':
181 case ')':
182 case '$':
183 case '&':
184 case ';':
185 case '<':
186 case '>':
187 case ' ':
188 case '\n':
189 case '\t':
190 need_to_quote = 1;
191 goto end_scan;
192
193 case '\0':
194 need_to_quote = 0;
195 goto end_scan;
196
197 default:
198 break;
199 }
200 ++p;
201 }
202 end_scan:
203 if (need_to_quote)
204 {
205 strcat (shell_command, "'");
206 for (p = exec_file; *p != '\0'; ++p)
207 {
208 if (*p == '\'')
209 strcat (shell_command, "'\\''");
210 else
211 strncat (shell_command, p, 1);
212 }
213 strcat (shell_command, "'");
214 }
215 else
216 strcat (shell_command, exec_file);
217
218 strcat (shell_command, " ");
219 strcat (shell_command, allargs);
220
221 }
222
223 /* exec is said to fail if the executable is open. */
224 close_exec_file ();
225
226 /* Retain a copy of our environment variables, since the child will
227 replace the value of environ and if we're vforked, we have to
228 restore it. */
229 save_our_env = environ;
230
231 /* Tell the terminal handling subsystem what tty we plan to run on;
232 it will just record the information for later. */
233
234 new_tty_prefork (inferior_io_terminal);
235
236 /* It is generally good practice to flush any possible pending stdio
237 output prior to doing a fork, to avoid the possibility of both the
238 parent and child flushing the same data after the fork. */
239
240 gdb_flush (gdb_stdout);
241 gdb_flush (gdb_stderr);
242
243 /* If there's any initialization of the target layers that must happen
244 to prepare to handle the child we're about fork, do it now...
245 */
246 if (pre_trace_fun != NULL)
247 (*pre_trace_fun) ();
248
249 if (debug_fork)
250 pid = fork ();
251 else
252 pid = vfork ();
253
254 if (pid < 0)
255 perror_with_name ("vfork");
256
257 if (pid == 0)
258 {
259 if (debug_fork)
260 sleep (debug_fork);
261
262 /* Run inferior in a separate process group. */
263 debug_setpgrp = gdb_setpgid ();
264 if (debug_setpgrp == -1)
265 perror ("setpgrp failed in child");
266
267 /* Ask the tty subsystem to switch to the one we specified earlier
268 (or to share the current terminal, if none was specified). */
269
270 new_tty ();
271
272 /* Changing the signal handlers for the inferior after
273 a vfork can also change them for the superior, so we don't mess
274 with signals here. See comments in
275 initialize_signals for how we get the right signal handlers
276 for the inferior. */
277
278 /* "Trace me, Dr. Memory!" */
279 (*traceme_fun) ();
280 /* The call above set this process (the "child") as debuggable
281 * by the original gdb process (the "parent"). Since processes
282 * (unlike people) can have only one parent, if you are
283 * debugging gdb itself (and your debugger is thus _already_ the
284 * controller/parent for this child), code from here on out
285 * is undebuggable. Indeed, you probably got an error message
286 * saying "not parent". Sorry--you'll have to use print statements!
287 */
288
289 /* There is no execlpe call, so we have to set the environment
290 for our child in the global variable. If we've vforked, this
291 clobbers the parent, but environ is restored a few lines down
292 in the parent. By the way, yes we do need to look down the
293 path to find $SHELL. Rich Pixley says so, and I agree. */
294 environ = env;
295
296 /* If we decided above to start up with a shell,
297 * we exec the shell,
298 * "-c" says to interpret the next arg as a shell command
299 * to execute, and this command is "exec <target-program> <args>".
300 * "-f" means "fast startup" to the c-shell, which means
301 * don't do .cshrc file. Doing .cshrc may cause fork/exec
302 * events which will confuse debugger start-up code.
303 */
304 if (shell)
305 {
306 execlp (shell_file, shell_file, "-c", shell_command, (char *) 0);
307
308 /* If we get here, it's an error */
309 fprintf_unfiltered (gdb_stderr, "Cannot exec %s: %s.\n", shell_file,
310 safe_strerror (errno));
311 gdb_flush (gdb_stderr);
312 _exit (0177);
313 }
314 else
315 {
316 /* Otherwise, we directly exec the target program with execvp. */
317 int i;
318 char *errstring;
319
320 execvp (exec_file, argv);
321
322 /* If we get here, it's an error */
323 errstring = safe_strerror (errno);
324 fprintf_unfiltered (gdb_stderr, "Cannot exec %s ", exec_file);
325
326 i = 1;
327 while (argv[i] != NULL)
328 {
329 if (i != 1)
330 fprintf_unfiltered (gdb_stderr, " ");
331 fprintf_unfiltered (gdb_stderr, "%s", argv[i]);
332 i++;
333 }
334 fprintf_unfiltered (gdb_stderr, ".\n");
335 /* This extra info seems to be useless
336 fprintf_unfiltered (gdb_stderr, "Got error %s.\n", errstring);
337 */
338 gdb_flush (gdb_stderr);
339 _exit (0177);
340 }
341 }
342
343 /* Restore our environment in case a vforked child clob'd it. */
344 environ = save_our_env;
345
346 init_thread_list ();
347
348 inferior_pid = pid; /* Needed for wait_for_inferior stuff below */
349
350 /* Now that we have a child process, make it our target, and
351 initialize anything target-vector-specific that needs initializing. */
352
353 (*init_trace_fun) (pid);
354
355 /* We are now in the child process of interest, having exec'd the
356 correct program, and are poised at the first instruction of the
357 new program. */
358
359 /* Allow target dependent code to play with the new process. This might be
360 used to have target-specific code initialize a variable in the new process
361 prior to executing the first instruction. */
362 TARGET_CREATE_INFERIOR_HOOK (pid);
363
364 #ifdef SOLIB_CREATE_INFERIOR_HOOK
365 SOLIB_CREATE_INFERIOR_HOOK (pid);
366 #endif
367 }
368
369 /* An inferior Unix process CHILD_PID has been created by a call to
370 fork() (or variants like vfork). It is presently stopped, and waiting
371 to be resumed. clone_and_follow_inferior will fork the debugger,
372 and that clone will "follow" (attach to) CHILD_PID. The original copy
373 of the debugger will not touch CHILD_PID again.
374
375 Also, the original debugger will set FOLLOWED_CHILD FALSE, while the
376 clone will set it TRUE.
377 */
378 void
379 clone_and_follow_inferior (int child_pid, int *followed_child)
380 {
381 extern int auto_solib_add;
382
383 int debugger_pid;
384 int status;
385 char pid_spelling[100]; /* Arbitrary but sufficient length. */
386
387 /* This semaphore is used to coordinate the two debuggers' handoff
388 of CHILD_PID. The original debugger will detach from CHILD_PID,
389 and then the clone debugger will attach to it. (It must be done
390 this way because on some targets, only one process at a time can
391 trace another. Thus, the original debugger must relinquish its
392 tracing rights before the clone can pick them up.)
393 */
394 #define SEM_TALK (1)
395 #define SEM_LISTEN (0)
396 int handoff_semaphore[2]; /* Original "talks" to [1], clone "listens" to [0] */
397 int talk_value = 99;
398 int listen_value;
399
400 /* Set debug_fork then attach to the child while it sleeps, to debug. */
401 static int debug_fork = 0;
402
403 /* It is generally good practice to flush any possible pending stdio
404 output prior to doing a fork, to avoid the possibility of both the
405 parent and child flushing the same data after the fork. */
406
407 gdb_flush (gdb_stdout);
408 gdb_flush (gdb_stderr);
409
410 /* Open the semaphore pipes.
411 */
412 status = pipe (handoff_semaphore);
413 if (status < 0)
414 error ("error getting pipe for handoff semaphore");
415
416 /* Clone the debugger. */
417 #ifdef HAVE_VFORK
418 if (debug_fork)
419 debugger_pid = fork ();
420 else
421 debugger_pid = vfork ();
422 #else
423 debugger_pid = fork ();
424 #endif
425
426 if (debugger_pid < 0)
427 perror_with_name ("fork");
428
429 /* Are we the original debugger? If so, we must relinquish all claims
430 to CHILD_PID. */
431 if (debugger_pid != 0)
432 {
433 char signal_spelling[100]; /* Arbitrary but sufficient length */
434
435 /* Detach from CHILD_PID. Deliver a "stop" signal when we do, though,
436 so that it remains stopped until the clone debugger can attach
437 to it.
438 */
439 detach_breakpoints (child_pid);
440
441 sprintf (signal_spelling, "%d", target_signal_to_host (TARGET_SIGNAL_STOP));
442 target_require_detach (child_pid, signal_spelling, 1);
443
444 /* Notify the clone debugger that it should attach to CHILD_PID. */
445 write (handoff_semaphore[SEM_TALK], &talk_value, sizeof (talk_value));
446
447 *followed_child = 0;
448 }
449
450 /* We're the child. */
451 else
452 {
453 if (debug_fork)
454 sleep (debug_fork);
455
456 /* The child (i.e., the cloned debugger) must now attach to
457 CHILD_PID. inferior_pid is presently set to the parent process
458 of the fork, while CHILD_PID should be the child process of the
459 fork.
460
461 Wait until the original debugger relinquishes control of CHILD_PID,
462 though.
463 */
464 read (handoff_semaphore[SEM_LISTEN], &listen_value, sizeof (listen_value));
465
466 /* Note that we DON'T want to actually detach from inferior_pid,
467 because that would allow it to run free. The original
468 debugger wants to retain control of the process. So, we
469 just reset inferior_pid to CHILD_PID, and then ensure that all
470 breakpoints are really set in CHILD_PID.
471 */
472 target_mourn_inferior ();
473
474 /* Ask the tty subsystem to switch to the one we specified earlier
475 (or to share the current terminal, if none was specified). */
476
477 new_tty ();
478
479 dont_repeat ();
480 sprintf (pid_spelling, "%d", child_pid);
481 target_require_attach (pid_spelling, 1);
482
483 /* Perform any necessary cleanup, after attachment. (This form
484 of attaching can behave differently on some targets than the
485 standard method, where a process formerly not under debugger
486 control was suddenly attached to..)
487 */
488 target_post_follow_inferior_by_clone ();
489
490 *followed_child = 1;
491 }
492
493 /* Discard the handoff sempahore. */
494 (void) close (handoff_semaphore[SEM_LISTEN]);
495 (void) close (handoff_semaphore[SEM_TALK]);
496 }
497
498 /* Accept NTRAPS traps from the inferior. */
499
500 void
501 startup_inferior (int ntraps)
502 {
503 int pending_execs = ntraps;
504 int terminal_initted;
505
506 /* The process was started by the fork that created it,
507 but it will have stopped one instruction after execing the shell.
508 Here we must get it up to actual execution of the real program. */
509
510 clear_proceed_status ();
511
512 init_wait_for_inferior ();
513
514 terminal_initted = 0;
515
516 if (STARTUP_WITH_SHELL)
517 inferior_ignoring_startup_exec_events = ntraps;
518 else
519 inferior_ignoring_startup_exec_events = 0;
520 inferior_ignoring_leading_exec_events =
521 target_reported_exec_events_per_exec_call () - 1;
522
523 #ifdef STARTUP_INFERIOR
524 STARTUP_INFERIOR (pending_execs);
525 #else
526 while (1)
527 {
528 stop_soon_quietly = 1; /* Make wait_for_inferior be quiet */
529 wait_for_inferior ();
530 if (stop_signal != TARGET_SIGNAL_TRAP)
531 {
532 /* Let shell child handle its own signals in its own way */
533 /* FIXME, what if child has exit()ed? Must exit loop somehow */
534 resume (0, stop_signal);
535 }
536 else
537 {
538 /* We handle SIGTRAP, however; it means child did an exec. */
539 if (!terminal_initted)
540 {
541 /* Now that the child has exec'd we know it has already set its
542 process group. On POSIX systems, tcsetpgrp will fail with
543 EPERM if we try it before the child's setpgid. */
544
545 /* Set up the "saved terminal modes" of the inferior
546 based on what modes we are starting it with. */
547 target_terminal_init ();
548
549 /* Install inferior's terminal modes. */
550 target_terminal_inferior ();
551
552 terminal_initted = 1;
553 }
554
555 pending_execs = pending_execs - 1;
556 if (0 == pending_execs)
557 break;
558
559 resume (0, TARGET_SIGNAL_0); /* Just make it go on */
560 }
561 }
562 #endif /* STARTUP_INFERIOR */
563 stop_soon_quietly = 0;
564 }
This page took 0.050724 seconds and 5 git commands to generate.