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