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