Imported from ../bash-2.05a.tar.gz.
[platform/upstream/bash.git] / shell.c
diff --git a/shell.c b/shell.c
index 4cb95e0..98d8303 100644 (file)
--- a/shell.c
+++ b/shell.c
@@ -31,6 +31,7 @@
 #  include <sys/file.h>
 #endif
 #include "posixstat.h"
+#include "posixtime.h"
 #include "bashansi.h"
 #include <stdio.h>
 #include <signal.h>
@@ -42,6 +43,8 @@
 #  include <unistd.h>
 #endif
 
+#define NEED_SH_SETLINEBUF_DECL                /* used in externs.h */
+
 #include "shell.h"
 #include "flags.h"
 #include "trap.h"
@@ -63,7 +66,7 @@
 #endif
 
 #include <tilde/tilde.h>
-#include <glob/fnmatch.h>
+#include <glob/strmatch.h>
 
 #if defined (__OPENNT)
 #  include <opennt/opennt.h>
@@ -101,7 +104,8 @@ COMMAND *global_command = (COMMAND *)NULL;
 /* Information about the current user. */
 struct user_info current_user =
 {
-  -1, -1, -1, -1, (char *)NULL, (char *)NULL, (char *)NULL
+  (uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
+  (char *)NULL, (char *)NULL, (char *)NULL
 };
 
 /* The current host's name. */
@@ -202,6 +206,7 @@ struct {
   { "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
   { "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
   { "help", Int, &want_initial_help, (char **)0x0 },
+  { "init-file", Charp, (int *)0x0, &bashrc_file },
   { "login", Int, &make_login_shell, (char **)0x0 },
   { "noediting", Int, &no_line_editing, (char **)0x0 },
   { "noprofile", Int, &no_profile, (char **)0x0 },
@@ -235,30 +240,41 @@ int default_buffered_input = -1;
 int read_from_stdin;           /* -s flag supplied */
 int want_pending_command;      /* -c flag supplied */
 
+static int shell_reinitialized = 0;
 static char *local_pending_command;
 
 static FILE *default_input;
 
-static int parse_long_options ();
-static int parse_shell_options ();
-static void run_startup_files ();
-static int bind_args ();
-static int open_shell_script ();
-static void set_bash_input ();
-static int run_one_command ();
-static int run_wordexp ();
+static STRING_INT_ALIST *shopt_alist;
+static int shopt_ind = 0, shopt_len = 0;
+
+static int parse_long_options __P((char **, int, int));
+static int parse_shell_options __P((char **, int, int));
+static int bind_args __P((char **, int, int, int));
+
+static void add_shopt_to_alist __P((char *, int));
+static void run_shopt_alist __P((void));
+
+static void execute_env_file __P((char *));
+static void run_startup_files __P((void));
+static int open_shell_script __P((char *));
+static void set_bash_input __P((void));
+static int run_one_command __P((char *));
+static int run_wordexp __P((char *));
+
+static int uidget __P((void));
+static int isnetconn __P((int));
 
-static int uidget ();
-static int isnetconn ();
+static void init_interactive __P((void));
+static void init_noninteractive __P((void));
 
-static void init_interactive (), init_noninteractive ();
-static void set_shell_name ();
-static void shell_initialize ();
-static void shell_reinitialize ();
+static void set_shell_name __P((char *));
+static void shell_initialize __P((void));
+static void shell_reinitialize __P((void));
 
-static void show_shell_usage ();
+static void show_shell_usage __P((FILE *, int));
 
-#ifdef __CYGWIN32__
+#ifdef __CYGWIN__
 static void
 _cygwin32_check_tmp ()
 {
@@ -272,7 +288,7 @@ _cygwin32_check_tmp ()
        internal_warning ("/tmp must be a valid directory name");
     }
 }
-#endif /* __CYGWIN32__ */
+#endif /* __CYGWIN__ */
 
 #if defined (NO_MAIN_ENV_ARG)
 /* systems without third argument to main() */
@@ -288,7 +304,10 @@ main (argc, argv, env)
 #endif /* !NO_MAIN_ENV_ARG */
 {
   register int i;
-  int code, saverst, old_errexit_flag;
+  int code, old_errexit_flag;
+#if defined (RESTRICTED_SHELL)
+  int saverst;
+#endif
   volatile int locally_skip_execution;
   volatile int arg_index, top_level_arg_index;
 #ifdef __OPENNT
@@ -297,16 +316,35 @@ main (argc, argv, env)
   env = environ;
 #endif /* __OPENNT */
 
+  USE_VAR(argc);
+  USE_VAR(argv);
+  USE_VAR(env);
+  USE_VAR(code);
+  USE_VAR(old_errexit_flag);
+#if defined (RESTRICTED_SHELL)
+  USE_VAR(saverst);
+#endif
+
   /* Catch early SIGINTs. */
   code = setjmp (top_level);
   if (code)
     exit (2);
 
+#if defined (USING_BASH_MALLOC) && defined (DEBUG)
+#  if 0                /* memory tracing */
+  malloc_set_trace(1);
+#  endif
+
+#  if 0
+  malloc_set_register (1);
+#  endif
+#endif
+
   check_dev_tty ();
 
-#ifdef __CYGWIN32__
+#ifdef __CYGWIN__
   _cygwin32_check_tmp ();
-#endif
+#endif /* __CYGWIN__ */
 
   /* Wait forever if we are debugging a login shell. */
   while (debugging_login_shell);
@@ -315,8 +353,8 @@ main (argc, argv, env)
 
   running_setuid = uidget ();
 
-  posixly_correct = (getenv ("POSIXLY_CORRECT") != (char *)NULL) ||
-                   (getenv ("POSIX_PEDANTIC") != (char *)NULL);
+  if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
+    posixly_correct = 1;
 
 #if defined (USE_GNU_MALLOC_LIBRARY)
   mcheck (programming_error, (void (*) ())0);
@@ -330,6 +368,8 @@ main (argc, argv, env)
       sourced_env = 0;
     }
 
+  shell_reinitialized = 0;
+
   /* Initialize `local' variables for all `invocations' of main (). */
   arg_index = 1;
   local_pending_command = (char *)NULL;
@@ -384,6 +424,8 @@ main (argc, argv, env)
       login_shell = -login_shell;
     }
 
+  set_login_shell (login_shell != 0);
+
   /* All done with full word options; do standard shell option parsing.*/
   this_command_name = shell_name;      /* for error reporting */
   arg_index = parse_shell_options (argv, arg_index, argc);
@@ -452,13 +494,14 @@ main (argc, argv, env)
      other Posix.2 things. */
   if (posixly_correct)
     {
-      posix_initialize (posixly_correct);
-#if defined (READLINE)
-      if (interactive_shell)
-       posix_readline_initialize (posixly_correct);
-#endif
+      bind_variable ("POSIXLY_CORRECT", "y");
+      sv_strict_posix ("POSIXLY_CORRECT");
     }
 
+  /* Now we run the shopt_alist and process the options. */
+  if (shopt_alist)
+    run_shopt_alist ();
+
   /* From here on in, the shell must be a normal functioning shell.
      Variables from the environment are expected to be set, etc. */
   shell_initialize ();
@@ -472,7 +515,7 @@ main (argc, argv, env)
       term = getenv ("TERM");
       no_line_editing |= term && (STREQ (term, "emacs"));
       term = getenv ("EMACS");
-      running_under_emacs = term ? ((fnmatch ("*term*", term, 0) == 0) ? 2 : 1)
+      running_under_emacs = term ? ((strmatch ("*term*", term, 0) == 0) ? 2 : 1)
                                 : 0;
     }
 
@@ -508,7 +551,8 @@ main (argc, argv, env)
     {
       makunbound ("PS1", shell_variables);
       makunbound ("PS2", shell_variables);
-      interactive = expand_aliases = 0;
+      interactive = 0;
+      expand_aliases = posixly_correct;
     }
   else
     {
@@ -535,18 +579,14 @@ main (argc, argv, env)
       exit_immediately_on_error = 0;
 
       run_startup_files ();
-
       exit_immediately_on_error += old_errexit_flag;
     }
 
   /* If we are invoked as `sh', turn on Posix mode. */
   if (act_like_sh)
     {
-      posix_initialize (posixly_correct = 1);
-#if defined (READLINE)
-      if (interactive_shell)
-        posix_readline_initialize (posixly_correct);
-#endif
+      bind_variable ("POSIXLY_CORRECT", "y");
+      sv_strict_posix ("POSIXLY_CORRECT");
     }
 
 #if defined (RESTRICTED_SHELL)
@@ -554,7 +594,8 @@ main (argc, argv, env)
      means that `bash -r' or `set -r' invoked from a startup file will
      turn on the restrictions after the startup files are executed. */
   restricted = saverst || restricted;
-  maybe_make_restricted (shell_name);
+  if (shell_reinitialized == 0)
+    maybe_make_restricted (shell_name);
 #endif /* RESTRICTED_SHELL */
 
   if (wordexp_only)
@@ -567,9 +608,9 @@ main (argc, argv, env)
   if (local_pending_command)
     {
       arg_index = bind_args (argv, arg_index, argc, 0);
-
       startup_state = 2;
 #if defined (ONESHOT)
+      executing = 1;
       run_one_command (local_pending_command);
       exit_shell (last_command_exit_value);
 #else /* ONESHOT */
@@ -598,7 +639,6 @@ main (argc, argv, env)
 
   /* Bind remaining args to $1 ... $n */
   arg_index = bind_args (argv, arg_index, argc, 1);
-
   /* Do the things that should be done only for interactive shells. */
   if (interactive_shell)
     {
@@ -735,6 +775,21 @@ parse_shell_options (argv, arg_start, arg_end)
              next_arg++;
              break;
 
+           case 'O':
+             /* Since some of these can be overridden by the normal
+                interactive/non-interactive shell initialization or
+                initializing posix mode, we save the options and process
+                them after initialization. */
+             o_option = argv[next_arg];
+             if (o_option == 0)
+               {
+                 shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
+                 break;
+               }
+             add_shopt_to_alist (o_option, on_or_off);
+             next_arg++;
+             break;
+
            case 'D':
              dump_translatable_strings = 1;
              break;
@@ -782,14 +837,18 @@ exit_shell (s)
     hangup_all_jobs ();
 
   /* If this shell is interactive, terminate all stopped jobs and
-     restore the original terminal process group. */
-  end_job_control ();
+     restore the original terminal process group.  Don't do this if we're
+     in a subshell and calling exit_shell after, for example, a failed
+     word expansion. */
+  if (subshell_environment == 0)
+    end_job_control ();
 #endif /* JOB_CONTROL */
 
   /* Always return the exit status of the last command to our parent. */
   exit (s);
 }
 
+#ifdef INCLUDE_UNUSED
 /* A wrapper for exit that (optionally) can do other things, like malloc
    statistics tracing. */
 void
@@ -798,6 +857,7 @@ sh_exit (s)
 {
   exit (s);
 }
+#endif
 
 /* Source the bash startup files.  If POSIXLY_CORRECT is non-zero, we obey
    the Posix.2 startup file rules:  $ENV is expanded, and if the file it
@@ -814,16 +874,16 @@ sh_exit (s)
 
    then:
 
-         COMMAND           EXECUTE BASHRC
-         --------------------------------
-         bash -c foo           NO
-         bash foo              NO
-         foo                   NO
-         rsh machine ls                YES (for rsh, which calls `bash -c')
-         rsh machine foo       YES (for shell started by rsh) NO (for foo!)
-         echo ls | bash                NO
-         login                 NO
-         bash                  YES
+        COMMAND            EXECUTE BASHRC
+        --------------------------------
+        bash -c foo            NO
+        bash foo               NO
+        foo                    NO
+        rsh machine ls         YES (for rsh, which calls `bash -c')
+        rsh machine foo        YES (for shell started by rsh) NO (for foo!)
+        echo ls | bash         NO
+        login                  NO
+        bash                   YES
 */
 
 static void
@@ -831,20 +891,13 @@ execute_env_file (env_file)
       char *env_file;
 {
   char *fn;
-  WORD_LIST *list;
 
   if (env_file && *env_file)
     {
-      list = expand_string_unsplit (env_file, Q_DOUBLE_QUOTES);
-      if (list)
-       {
-         fn = string_list (list);
-         dispose_words (list);
-
-         if (fn && *fn)
-           maybe_execute_file (fn, 1);
-         FREE (fn);
-       }
+      fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
+      if (fn && *fn)
+       maybe_execute_file (fn, 1);
+      FREE (fn);
     }
 }
 
@@ -860,8 +913,12 @@ run_startup_files ()
   if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
       act_like_sh == 0 && local_pending_command)
     {
-      run_by_ssh = find_variable ("SSH_CLIENT") != (SHELL_VAR *)0;
-      run_by_ssh |= find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0;
+#ifdef SSH_SOURCE_BASHRC
+      run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
+                  (find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
+#else
+      run_by_ssh = 0;
+#endif
 
       /* If we were run by sshd or we think we were run by rshd, execute
         ~/.bashrc if we are a top-level shell. */
@@ -959,17 +1016,17 @@ run_startup_files ()
          maybe_execute_file (SYS_BASHRC, 1);
 #  endif
 #endif
-          maybe_execute_file (bashrc_file, 1);
+         maybe_execute_file (bashrc_file, 1);
        }
       /* sh */
       else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
-        execute_env_file (get_string_value ("ENV"));
+       execute_env_file (get_string_value ("ENV"));
     }
   else         /* bash --posix, sh --posix */
     {
       /* bash and sh */
       if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
-        execute_env_file (get_string_value ("ENV"));
+       execute_env_file (get_string_value ("ENV"));
     }
 
 #if defined (JOB_CONTROL)
@@ -1013,7 +1070,7 @@ maybe_make_restricted (name)
       set_var_read_only ("SHELL");
       set_var_read_only ("ENV");
       set_var_read_only ("BASH_ENV");
-      restricted++;
+      restricted = 1;
     }
   return (restricted);
 }
@@ -1058,7 +1115,6 @@ run_wordexp (words)
      char *words;
 {
   int code, nw, nb;
-  WORD_DESC *w;
   WORD_LIST *wl, *result;
 
   code = setjmp (top_level);
@@ -1084,14 +1140,14 @@ run_wordexp (words)
     {
       with_input_from_string (words, "--wordexp");
       if (parse_command () != 0)
-        return (126);
+       return (126);
       if (global_command == 0)
        {
          printf ("0\n0\n");
          return (0);
        }
       if (global_command->type != cm_simple)
-        return (126);
+       return (126);
       wl = global_command->value.Simple->words;
       result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
     }
@@ -1178,7 +1234,7 @@ bind_args (argv, arg_start, arg_end, start_index)
          remember_args (args->next, 1);
        }
       else                     /* bind to $1...$n for shell script */
-        remember_args (args, 1);
+       remember_args (args, 1);
 
       dispose_words (args);
     }
@@ -1196,9 +1252,9 @@ static int
 open_shell_script (script_name)
      char *script_name;
 {
-  int fd, e;
+  int fd, e, fd_is_tty;
   char *filename, *path_filename;
-  unsigned char sample[80];
+  char sample[80];
   int sample_len;
   struct stat sb;
 
@@ -1230,8 +1286,14 @@ open_shell_script (script_name)
       exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
     }
 
-  /* Only do this with file descriptors we can seek on. */
-  if (lseek (fd, 0L, 1) != -1)
+#ifdef HAVE_DEV_FD
+  fd_is_tty = isatty (fd);
+#else
+  fd_is_tty = 0;
+#endif
+
+  /* Only do this with non-tty file descriptors we can seek on. */
+  if (fd_is_tty == 0 && (lseek (fd, 0L, 1) != -1))
     {
       /* Check to see if the `file' in `bash file' is a binary file
         according to the same tests done by execute_simple_command (),
@@ -1242,7 +1304,7 @@ open_shell_script (script_name)
          e = errno;
          if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
            internal_error ("%s: is a directory", filename);
-          else
+         else
            {
              errno = e;
              file_error (filename);
@@ -1263,16 +1325,12 @@ open_shell_script (script_name)
      not match with ours. */
   fd = move_to_high_fd (fd, 0, -1);
 
+#if defined (__CYGWIN__) && defined (O_TEXT)
+  setmode (fd, O_TEXT);
+#endif
+
 #if defined (BUFFERED_INPUT)
   default_buffered_input = fd;
-#  if 0
-  /* This is never executed. */
-  if (default_buffered_input == -1)
-    {
-      file_error (filename);
-      exit (EX_NOTFOUND);
-    }
-#  endif
   SET_CLOSE_ON_EXEC (default_buffered_input);
 #else /* !BUFFERED_INPUT */
   default_input = fdopen (fd, "r");
@@ -1288,13 +1346,10 @@ open_shell_script (script_name)
     SET_CLOSE_ON_EXEC (fileno (default_input));
 #endif /* !BUFFERED_INPUT */
 
-  if (interactive_shell == 0 || isatty (fd) == 0)
-    /* XXX - does this really need to be called again here? */
-    init_noninteractive ();
-  else
+  /* Just about the only way for this code to be executed is if something
+     like `bash -i /dev/stdin' is executed. */
+  if (interactive_shell && fd_is_tty)
     {
-      /* I don't believe that this code is ever executed, even in
-        the presence of /dev/fd. */
       dup2 (fd, 0);
       close (fd);
       fd = 0;
@@ -1305,6 +1360,12 @@ open_shell_script (script_name)
       default_input = stdin;
 #endif
     }
+  else if (forced_interactive && fd_is_tty == 0)
+    /* But if a script is called with something like `bash -i scriptname',
+       we need to do a non-interactive setup here, since we didn't do it
+       before. */
+    init_noninteractive ();
+
   free (filename);
   return (fd);
 }
@@ -1317,10 +1378,10 @@ set_bash_input ()
      no-delay mode. */
 #if defined (BUFFERED_INPUT)
   if (interactive == 0)
-    unset_nodelay_mode (default_buffered_input);
+    sh_unset_nodelay_mode (default_buffered_input);
   else
 #endif /* !BUFFERED_INPUT */
-    unset_nodelay_mode (fileno (stdin));
+    sh_unset_nodelay_mode (fileno (stdin));
 
   /* with_input_from_stdin really means `with_input_from_readline' */
   if (interactive && no_line_editing == 0)
@@ -1562,10 +1623,7 @@ shell_reinitialize ()
   delete_all_variables (shell_variables);
   delete_all_variables (shell_functions);
 
-#if 0
-  /* Pretend the PATH variable has changed. */
-  flush_hashed_filenames ();
-#endif
+  shell_reinitialized = 1;
 }
 
 static void
@@ -1585,7 +1643,7 @@ show_shell_usage (fp, extra)
     fprintf (fp, "\t--%s\n", long_args[i].name);
 
   fputs ("Shell options:\n", fp);
-  fputs ("\t-irsD or -c command\t\t(invocation only)\n", fp);
+  fputs ("\t-irsD or -c command or -O shopt_option\t\t(invocation only)\n", fp);
 
   for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
     if (STREQ (shell_builtins[i].name, "set"))
@@ -1612,6 +1670,34 @@ show_shell_usage (fp, extra)
     }
 }
 
+static void
+add_shopt_to_alist (opt, on_or_off)
+     char *opt;
+     int on_or_off;
+{
+  if (shopt_ind >= shopt_len)
+    {
+      shopt_len += 8;
+      shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
+    }
+  shopt_alist[shopt_ind].word = opt;
+  shopt_alist[shopt_ind].token = on_or_off;
+  shopt_ind++;
+}
+
+static void
+run_shopt_alist ()
+{
+  register int i;
+
+  for (i = 0; i < shopt_ind; i++)
+    if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
+      exit (EX_USAGE);
+  free (shopt_alist);
+  shopt_alist = 0;
+  shopt_ind = shopt_len = 0;
+}
+
 /* The second and subsequent conditions must match those used to decide
    whether or not to call getpeername() in isnetconn(). */
 #if defined (HAVE_SYS_SOCKET_H) && defined (HAVE_GETPEERNAME) && !defined (SVR4_2)
@@ -1624,7 +1710,8 @@ isnetconn (fd)
      int fd;
 {
 #if defined (HAVE_GETPEERNAME) && !defined (SVR4_2) && !defined (__BEOS__)
-  int rv, l;
+  int rv;
+  socklen_t l;
   struct sockaddr sa;
 
   l = sizeof(sa);