GDB (API)
/home/stan/gdb/src/gdb/fork-child.c
Go to the documentation of this file.
00001 /* Fork a Unix child process, and set up to debug it, for GDB.
00002 
00003    Copyright (C) 1990-2013 Free Software Foundation, Inc.
00004 
00005    Contributed by Cygnus Support.
00006 
00007    This file is part of GDB.
00008 
00009    This program is free software; you can redistribute it and/or modify
00010    it under the terms of the GNU General Public License as published by
00011    the Free Software Foundation; either version 3 of the License, or
00012    (at your option) any later version.
00013 
00014    This program is distributed in the hope that it will be useful,
00015    but WITHOUT ANY WARRANTY; without even the implied warranty of
00016    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00017    GNU General Public License for more details.
00018 
00019    You should have received a copy of the GNU General Public License
00020    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00021 
00022 #include "defs.h"
00023 #include "gdb_string.h"
00024 #include "inferior.h"
00025 #include "terminal.h"
00026 #include "target.h"
00027 #include "gdb_wait.h"
00028 #include "gdb_vfork.h"
00029 #include "gdbcore.h"
00030 #include "terminal.h"
00031 #include "gdbthread.h"
00032 #include "command.h" /* for dont_repeat () */
00033 #include "gdbcmd.h"
00034 #include "solib.h"
00035 #include "filestuff.h"
00036 
00037 #include <signal.h>
00038 
00039 /* This just gets used as a default if we can't find SHELL.  */
00040 #define SHELL_FILE "/bin/sh"
00041 
00042 extern char **environ;
00043 
00044 static char *exec_wrapper;
00045 
00046 /* Break up SCRATCH into an argument vector suitable for passing to
00047    execvp and store it in ARGV.  E.g., on "run a b c d" this routine
00048    would get as input the string "a b c d", and as output it would
00049    fill in ARGV with the four arguments "a", "b", "c", "d".  */
00050 
00051 static void
00052 breakup_args (char *scratch, char **argv)
00053 {
00054   char *cp = scratch, *tmp;
00055 
00056   for (;;)
00057     {
00058       /* Scan past leading separators */
00059       while (*cp == ' ' || *cp == '\t' || *cp == '\n')
00060         cp++;
00061 
00062       /* Break if at end of string.  */
00063       if (*cp == '\0')
00064         break;
00065 
00066       /* Take an arg.  */
00067       *argv++ = cp;
00068 
00069       /* Scan for next arg separator.  */
00070       tmp = strchr (cp, ' ');
00071       if (tmp == NULL)
00072         tmp = strchr (cp, '\t');
00073       if (tmp == NULL)
00074         tmp = strchr (cp, '\n');
00075 
00076       /* No separators => end of string => break.  */
00077       if (tmp == NULL)
00078         break;
00079       cp = tmp;
00080 
00081       /* Replace the separator with a terminator.  */
00082       *cp++ = '\0';
00083     }
00084 
00085   /* Null-terminate the vector.  */
00086   *argv = NULL;
00087 }
00088 
00089 /* When executing a command under the given shell, return non-zero if
00090    the '!' character should be escaped when embedded in a quoted
00091    command-line argument.  */
00092 
00093 static int
00094 escape_bang_in_quoted_argument (const char *shell_file)
00095 {
00096   const int shell_file_len = strlen (shell_file);
00097 
00098   /* Bang should be escaped only in C Shells.  For now, simply check
00099      that the shell name ends with 'csh', which covers at least csh
00100      and tcsh.  This should be good enough for now.  */
00101 
00102   if (shell_file_len < 3)
00103     return 0;
00104 
00105   if (shell_file[shell_file_len - 3] == 'c'
00106       && shell_file[shell_file_len - 2] == 's'
00107       && shell_file[shell_file_len - 1] == 'h')
00108     return 1;
00109 
00110   return 0;
00111 }
00112 
00113 /* Start an inferior Unix child process and sets inferior_ptid to its
00114    pid.  EXEC_FILE is the file to run.  ALLARGS is a string containing
00115    the arguments to the program.  ENV is the environment vector to
00116    pass.  SHELL_FILE is the shell file, or NULL if we should pick
00117    one.  EXEC_FUN is the exec(2) function to use, or NULL for the default
00118    one.  */
00119 
00120 /* This function is NOT reentrant.  Some of the variables have been
00121    made static to ensure that they survive the vfork call.  */
00122 
00123 int
00124 fork_inferior (char *exec_file_arg, char *allargs, char **env,
00125                void (*traceme_fun) (void), void (*init_trace_fun) (int),
00126                void (*pre_trace_fun) (void), char *shell_file_arg,
00127                void (*exec_fun)(const char *file, char * const *argv,
00128                                 char * const *env))
00129 {
00130   int pid;
00131   static char default_shell_file[] = SHELL_FILE;
00132   /* Set debug_fork then attach to the child while it sleeps, to debug.  */
00133   static int debug_fork = 0;
00134   /* This is set to the result of setpgrp, which if vforked, will be visible
00135      to you in the parent process.  It's only used by humans for debugging.  */
00136   static int debug_setpgrp = 657473;
00137   static char *shell_file;
00138   static char *exec_file;
00139   char **save_our_env;
00140   int shell = 0;
00141   static char **argv;
00142   const char *inferior_io_terminal = get_inferior_io_terminal ();
00143   struct inferior *inf;
00144   int i;
00145   int save_errno;
00146 
00147   /* If no exec file handed to us, get it from the exec-file command
00148      -- with a good, common error message if none is specified.  */
00149   exec_file = exec_file_arg;
00150   if (exec_file == 0)
00151     exec_file = get_exec_file (1);
00152 
00153   /* STARTUP_WITH_SHELL is defined in inferior.h.  If 0,e we'll just
00154     do a fork/exec, no shell, so don't bother figuring out what
00155     shell.  */
00156   shell_file = shell_file_arg;
00157   if (STARTUP_WITH_SHELL)
00158     {
00159       /* Figure out what shell to start up the user program under.  */
00160       if (shell_file == NULL)
00161         shell_file = getenv ("SHELL");
00162       if (shell_file == NULL)
00163         shell_file = default_shell_file;
00164       shell = 1;
00165     }
00166 
00167   if (!shell)
00168     {
00169       /* We're going to call execvp.  Create argument vector.
00170          Calculate an upper bound on the length of the vector by
00171          assuming that every other character is a separate
00172          argument.  */
00173       int argc = (strlen (allargs) + 1) / 2 + 2;
00174 
00175       argv = (char **) alloca (argc * sizeof (*argv));
00176       argv[0] = exec_file;
00177       breakup_args (allargs, &argv[1]);
00178     }
00179   else
00180     {
00181       /* We're going to call a shell.  */
00182       char *shell_command;
00183       int len;
00184       char *p;
00185       int need_to_quote;
00186       const int escape_bang = escape_bang_in_quoted_argument (shell_file);
00187 
00188       /* Multiplying the length of exec_file by 4 is to account for the
00189          fact that it may expand when quoted; it is a worst-case number
00190          based on every character being '.  */
00191       len = 5 + 4 * strlen (exec_file) + 1 + strlen (allargs) + 1 + /*slop */ 12;
00192       if (exec_wrapper)
00193         len += strlen (exec_wrapper) + 1;
00194 
00195       shell_command = (char *) alloca (len);
00196       shell_command[0] = '\0';
00197 
00198       strcat (shell_command, "exec ");
00199 
00200       /* Add any exec wrapper.  That may be a program name with arguments, so
00201          the user must handle quoting.  */
00202       if (exec_wrapper)
00203         {
00204           strcat (shell_command, exec_wrapper);
00205           strcat (shell_command, " ");
00206         }
00207 
00208       /* Now add exec_file, quoting as necessary.  */
00209 
00210       /* Quoting in this style is said to work with all shells.  But
00211          csh on IRIX 4.0.1 can't deal with it.  So we only quote it if
00212          we need to.  */
00213       p = exec_file;
00214       while (1)
00215         {
00216           switch (*p)
00217             {
00218             case '\'':
00219             case '!':
00220             case '"':
00221             case '(':
00222             case ')':
00223             case '$':
00224             case '&':
00225             case ';':
00226             case '<':
00227             case '>':
00228             case ' ':
00229             case '\n':
00230             case '\t':
00231               need_to_quote = 1;
00232               goto end_scan;
00233 
00234             case '\0':
00235               need_to_quote = 0;
00236               goto end_scan;
00237 
00238             default:
00239               break;
00240             }
00241           ++p;
00242         }
00243     end_scan:
00244       if (need_to_quote)
00245         {
00246           strcat (shell_command, "'");
00247           for (p = exec_file; *p != '\0'; ++p)
00248             {
00249               if (*p == '\'')
00250                 strcat (shell_command, "'\\''");
00251               else if (*p == '!' && escape_bang)
00252                 strcat (shell_command, "\\!");
00253               else
00254                 strncat (shell_command, p, 1);
00255             }
00256           strcat (shell_command, "'");
00257         }
00258       else
00259         strcat (shell_command, exec_file);
00260 
00261       strcat (shell_command, " ");
00262       strcat (shell_command, allargs);
00263 
00264       /* If we decided above to start up with a shell, we exec the
00265          shell, "-c" says to interpret the next arg as a shell command
00266          to execute, and this command is "exec <target-program>
00267          <args>".  */
00268       argv = (char **) alloca (4 * sizeof (char *));
00269       argv[0] = shell_file;
00270       argv[1] = "-c";
00271       argv[2] = shell_command;
00272       argv[3] = (char *) 0;
00273     }
00274 
00275   /* Retain a copy of our environment variables, since the child will
00276      replace the value of environ and if we're vforked, we have to
00277      restore it.  */
00278   save_our_env = environ;
00279 
00280   /* Tell the terminal handling subsystem what tty we plan to run on;
00281      it will just record the information for later.  */
00282   new_tty_prefork (inferior_io_terminal);
00283 
00284   /* It is generally good practice to flush any possible pending stdio
00285      output prior to doing a fork, to avoid the possibility of both
00286      the parent and child flushing the same data after the fork.  */
00287   gdb_flush (gdb_stdout);
00288   gdb_flush (gdb_stderr);
00289 
00290   /* If there's any initialization of the target layers that must
00291      happen to prepare to handle the child we're about fork, do it
00292      now...  */
00293   if (pre_trace_fun != NULL)
00294     (*pre_trace_fun) ();
00295 
00296   /* Create the child process.  Since the child process is going to
00297      exec(3) shortly afterwards, try to reduce the overhead by
00298      calling vfork(2).  However, if PRE_TRACE_FUN is non-null, it's
00299      likely that this optimization won't work since there's too much
00300      work to do between the vfork(2) and the exec(3).  This is known
00301      to be the case on ttrace(2)-based HP-UX, where some handshaking
00302      between parent and child needs to happen between fork(2) and
00303      exec(2).  However, since the parent is suspended in the vforked
00304      state, this doesn't work.  Also note that the vfork(2) call might
00305      actually be a call to fork(2) due to the fact that autoconf will
00306      ``#define vfork fork'' on certain platforms.  */
00307   if (pre_trace_fun || debug_fork)
00308     pid = fork ();
00309   else
00310     pid = vfork ();
00311 
00312   if (pid < 0)
00313     perror_with_name (("vfork"));
00314 
00315   if (pid == 0)
00316     {
00317       close_most_fds ();
00318 
00319       if (debug_fork)
00320         sleep (debug_fork);
00321 
00322       /* Create a new session for the inferior process, if necessary.
00323          It will also place the inferior in a separate process group.  */
00324       if (create_tty_session () <= 0)
00325         {
00326           /* No session was created, but we still want to run the inferior
00327              in a separate process group.  */
00328           debug_setpgrp = gdb_setpgid ();
00329           if (debug_setpgrp == -1)
00330             perror (_("setpgrp failed in child"));
00331         }
00332 
00333       /* Ask the tty subsystem to switch to the one we specified
00334          earlier (or to share the current terminal, if none was
00335          specified).  */
00336       new_tty ();
00337 
00338       /* Changing the signal handlers for the inferior after
00339          a vfork can also change them for the superior, so we don't mess
00340          with signals here.  See comments in
00341          initialize_signals for how we get the right signal handlers
00342          for the inferior.  */
00343 
00344       /* "Trace me, Dr. Memory!"  */
00345       (*traceme_fun) ();
00346 
00347       /* The call above set this process (the "child") as debuggable
00348         by the original gdb process (the "parent").  Since processes
00349         (unlike people) can have only one parent, if you are debugging
00350         gdb itself (and your debugger is thus _already_ the
00351         controller/parent for this child), code from here on out is
00352         undebuggable.  Indeed, you probably got an error message
00353         saying "not parent".  Sorry; you'll have to use print
00354         statements!  */
00355 
00356       /* There is no execlpe call, so we have to set the environment
00357          for our child in the global variable.  If we've vforked, this
00358          clobbers the parent, but environ is restored a few lines down
00359          in the parent.  By the way, yes we do need to look down the
00360          path to find $SHELL.  Rich Pixley says so, and I agree.  */
00361       environ = env;
00362 
00363       if (exec_fun != NULL)
00364         (*exec_fun) (argv[0], argv, env);
00365       else
00366         execvp (argv[0], argv);
00367 
00368       /* If we get here, it's an error.  */
00369       save_errno = errno;
00370       fprintf_unfiltered (gdb_stderr, "Cannot exec %s", exec_file);
00371       for (i = 1; argv[i] != NULL; i++)
00372         fprintf_unfiltered (gdb_stderr, " %s", argv[i]);
00373       fprintf_unfiltered (gdb_stderr, ".\n");
00374       fprintf_unfiltered (gdb_stderr, "Error: %s\n",
00375                           safe_strerror (save_errno));
00376       gdb_flush (gdb_stderr);
00377       _exit (0177);
00378     }
00379 
00380   /* Restore our environment in case a vforked child clob'd it.  */
00381   environ = save_our_env;
00382 
00383   if (!have_inferiors ())
00384     init_thread_list ();
00385 
00386   inf = current_inferior ();
00387 
00388   inferior_appeared (inf, pid);
00389 
00390   /* Needed for wait_for_inferior stuff below.  */
00391   inferior_ptid = pid_to_ptid (pid);
00392 
00393   new_tty_postfork ();
00394 
00395   /* We have something that executes now.  We'll be running through
00396      the shell at this point, but the pid shouldn't change.  Targets
00397      supporting MT should fill this task's ptid with more data as soon
00398      as they can.  */
00399   add_thread_silent (inferior_ptid);
00400 
00401   /* Now that we have a child process, make it our target, and
00402      initialize anything target-vector-specific that needs
00403      initializing.  */
00404   if (init_trace_fun)
00405     (*init_trace_fun) (pid);
00406 
00407   /* We are now in the child process of interest, having exec'd the
00408      correct program, and are poised at the first instruction of the
00409      new program.  */
00410   return pid;
00411 }
00412 
00413 /* Accept NTRAPS traps from the inferior.  */
00414 
00415 void
00416 startup_inferior (int ntraps)
00417 {
00418   int pending_execs = ntraps;
00419   int terminal_initted = 0;
00420   ptid_t resume_ptid;
00421 
00422   if (target_supports_multi_process ())
00423     resume_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
00424   else
00425     resume_ptid = minus_one_ptid;
00426 
00427   /* The process was started by the fork that created it, but it will
00428      have stopped one instruction after execing the shell.  Here we
00429      must get it up to actual execution of the real program.  */
00430 
00431   if (exec_wrapper)
00432     pending_execs++;
00433 
00434   while (1)
00435     {
00436       enum gdb_signal resume_signal = GDB_SIGNAL_0;
00437       ptid_t event_ptid;
00438 
00439       struct target_waitstatus ws;
00440       memset (&ws, 0, sizeof (ws));
00441       event_ptid = target_wait (resume_ptid, &ws, 0);
00442 
00443       if (ws.kind == TARGET_WAITKIND_IGNORE)
00444         /* The inferior didn't really stop, keep waiting.  */
00445         continue;
00446 
00447       switch (ws.kind)
00448         {
00449           case TARGET_WAITKIND_SPURIOUS:
00450           case TARGET_WAITKIND_LOADED:
00451           case TARGET_WAITKIND_FORKED:
00452           case TARGET_WAITKIND_VFORKED:
00453           case TARGET_WAITKIND_SYSCALL_ENTRY:
00454           case TARGET_WAITKIND_SYSCALL_RETURN:
00455             /* Ignore gracefully during startup of the inferior.  */
00456             switch_to_thread (event_ptid);
00457             break;
00458 
00459           case TARGET_WAITKIND_SIGNALLED:
00460             target_terminal_ours ();
00461             target_mourn_inferior ();
00462             error (_("During startup program terminated with signal %s, %s."),
00463                    gdb_signal_to_name (ws.value.sig),
00464                    gdb_signal_to_string (ws.value.sig));
00465             return;
00466 
00467           case TARGET_WAITKIND_EXITED:
00468             target_terminal_ours ();
00469             target_mourn_inferior ();
00470             if (ws.value.integer)
00471               error (_("During startup program exited with code %d."),
00472                      ws.value.integer);
00473             else
00474               error (_("During startup program exited normally."));
00475             return;
00476 
00477           case TARGET_WAITKIND_EXECD:
00478             /* Handle EXEC signals as if they were SIGTRAP signals.  */
00479             xfree (ws.value.execd_pathname);
00480             resume_signal = GDB_SIGNAL_TRAP;
00481             switch_to_thread (event_ptid);
00482             break;
00483 
00484           case TARGET_WAITKIND_STOPPED:
00485             resume_signal = ws.value.sig;
00486             switch_to_thread (event_ptid);
00487             break;
00488         }
00489 
00490       if (resume_signal != GDB_SIGNAL_TRAP)
00491         {
00492           /* Let shell child handle its own signals in its own way.  */
00493           target_resume (resume_ptid, 0, resume_signal);
00494         }
00495       else
00496         {
00497           /* We handle SIGTRAP, however; it means child did an exec.  */
00498           if (!terminal_initted)
00499             {
00500               /* Now that the child has exec'd we know it has already
00501                  set its process group.  On POSIX systems, tcsetpgrp
00502                  will fail with EPERM if we try it before the child's
00503                  setpgid.  */
00504 
00505               /* Set up the "saved terminal modes" of the inferior
00506                  based on what modes we are starting it with.  */
00507               target_terminal_init ();
00508 
00509               /* Install inferior's terminal modes.  */
00510               target_terminal_inferior ();
00511 
00512               terminal_initted = 1;
00513             }
00514 
00515           if (--pending_execs == 0)
00516             break;
00517 
00518           /* Just make it go on.  */
00519           target_resume (resume_ptid, 0, GDB_SIGNAL_0);
00520         }
00521     }
00522 
00523   /* Mark all threads non-executing.  */
00524   set_executing (resume_ptid, 0);
00525 }
00526 
00527 /* Implement the "unset exec-wrapper" command.  */
00528 
00529 static void
00530 unset_exec_wrapper_command (char *args, int from_tty)
00531 {
00532   xfree (exec_wrapper);
00533   exec_wrapper = NULL;
00534 }
00535 
00536 /* Provide a prototype to silence -Wmissing-prototypes.  */
00537 extern initialize_file_ftype _initialize_fork_child;
00538 
00539 void
00540 _initialize_fork_child (void)
00541 {
00542   add_setshow_filename_cmd ("exec-wrapper", class_run, &exec_wrapper, _("\
00543 Set a wrapper for running programs.\n\
00544 The wrapper prepares the system and environment for the new program."),
00545                             _("\
00546 Show the wrapper for running programs."), NULL,
00547                             NULL, NULL,
00548                             &setlist, &showlist);
00549 
00550   add_cmd ("exec-wrapper", class_run, unset_exec_wrapper_command,
00551            _("Disable use of an execution wrapper."),
00552            &unsetlist);
00553 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines