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