OSDN Git Service

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