Imported from ../bash-3.2.48.tar.gz.
[platform/upstream/bash.git] / shell.c
1 /* shell.c -- GNU's idea of the POSIX shell specification. */
2
3 /* Copyright (C) 1987-2005 Free Software Foundation, Inc.
4
5    This file is part of GNU Bash, the Bourne Again SHell.
6
7    Bash is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    Bash is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA.
20
21   Birthdate:
22   Sunday, January 10th, 1988.
23   Initial author: Brian Fox
24 */
25 #define INSTALL_DEBUG_MODE
26
27 #include "config.h"
28
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 #  include <sys/file.h>
32 #endif
33 #include "posixstat.h"
34 #include "posixtime.h"
35 #include "bashansi.h"
36 #include <stdio.h>
37 #include <signal.h>
38 #include <errno.h>
39 #include "filecntl.h"
40 #include <pwd.h>
41
42 #if defined (HAVE_UNISTD_H)
43 #  include <unistd.h>
44 #endif
45
46 #include "bashintl.h"
47
48 #define NEED_SH_SETLINEBUF_DECL         /* used in externs.h */
49
50 #include "shell.h"
51 #include "flags.h"
52 #include "trap.h"
53 #include "mailcheck.h"
54 #include "builtins.h"
55 #include "builtins/common.h"
56
57 #if defined (JOB_CONTROL)
58 #include "jobs.h"
59 #endif /* JOB_CONTROL */
60
61 #include "input.h"
62 #include "execute_cmd.h"
63 #include "findcmd.h"
64
65 #if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
66 #  include <malloc/shmalloc.h>
67 #endif
68
69 #if defined (HISTORY)
70 #  include "bashhist.h"
71 #  include <readline/history.h>
72 #endif
73
74 #include <tilde/tilde.h>
75 #include <glob/strmatch.h>
76
77 #if defined (__OPENNT)
78 #  include <opennt/opennt.h>
79 #endif
80
81 #if !defined (HAVE_GETPW_DECLS)
82 extern struct passwd *getpwuid ();
83 #endif /* !HAVE_GETPW_DECLS */
84
85 #if !defined (errno)
86 extern int errno;
87 #endif
88
89 #if defined (NO_MAIN_ENV_ARG)
90 extern char **environ;  /* used if no third argument to main() */
91 #endif
92
93 extern char *dist_version, *release_status;
94 extern int patch_level, build_version;
95 extern int shell_level;
96 extern int subshell_environment;
97 extern int last_command_exit_value;
98 extern int line_number;
99 extern int expand_aliases;
100 extern int array_needs_making;
101 extern int gnu_error_format;
102 extern char *primary_prompt, *secondary_prompt;
103 extern char *this_command_name;
104
105 /* Non-zero means that this shell has already been run; i.e. you should
106    call shell_reinitialize () if you need to start afresh. */
107 int shell_initialized = 0;
108
109 COMMAND *global_command = (COMMAND *)NULL;
110
111 /* Information about the current user. */
112 struct user_info current_user =
113 {
114   (uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
115   (char *)NULL, (char *)NULL, (char *)NULL
116 };
117
118 /* The current host's name. */
119 char *current_host_name = (char *)NULL;
120
121 /* Non-zero means that this shell is a login shell.
122    Specifically:
123    0 = not login shell.
124    1 = login shell from getty (or equivalent fake out)
125   -1 = login shell from "--login" (or -l) flag.
126   -2 = both from getty, and from flag.
127  */
128 int login_shell = 0;
129
130 /* Non-zero means that at this moment, the shell is interactive.  In
131    general, this means that the shell is at this moment reading input
132    from the keyboard. */
133 int interactive = 0;
134
135 /* Non-zero means that the shell was started as an interactive shell. */
136 int interactive_shell = 0;
137
138 /* Non-zero means to send a SIGHUP to all jobs when an interactive login
139    shell exits. */
140 int hup_on_exit = 0;
141
142 /* Tells what state the shell was in when it started:
143         0 = non-interactive shell script
144         1 = interactive
145         2 = -c command
146         3 = wordexp evaluation
147    This is a superset of the information provided by interactive_shell.
148 */
149 int startup_state = 0;
150
151 /* Special debugging helper. */
152 int debugging_login_shell = 0;
153
154 /* The environment that the shell passes to other commands. */
155 char **shell_environment;
156
157 /* Non-zero when we are executing a top-level command. */
158 int executing = 0;
159
160 /* The number of commands executed so far. */
161 int current_command_number = 1;
162
163 /* Non-zero is the recursion depth for commands. */
164 int indirection_level = 0;
165
166 /* The name of this shell, as taken from argv[0]. */
167 char *shell_name = (char *)NULL;
168
169 /* time in seconds when the shell was started */
170 time_t shell_start_time;
171
172 /* Are we running in an emacs shell window? */
173 int running_under_emacs;
174
175 /* The name of the .(shell)rc file. */
176 static char *bashrc_file = "~/.bashrc";
177
178 /* Non-zero means to act more like the Bourne shell on startup. */
179 static int act_like_sh;
180
181 /* Non-zero if this shell is being run by `su'. */
182 static int su_shell;
183
184 /* Non-zero if we have already expanded and sourced $ENV. */
185 static int sourced_env;
186
187 /* Is this shell running setuid? */
188 static int running_setuid;
189
190 /* Values for the long-winded argument names. */
191 static int debugging;                   /* Do debugging things. */
192 static int no_rc;                       /* Don't execute ~/.bashrc */
193 static int no_profile;                  /* Don't execute .profile */
194 static int do_version;                  /* Display interesting version info. */
195 static int make_login_shell;            /* Make this shell be a `-bash' shell. */
196 static int want_initial_help;           /* --help option */
197
198 int debugging_mode = 0;         /* In debugging mode with --debugger */
199 int no_line_editing = 0;        /* Don't do fancy line editing. */
200 int dump_translatable_strings;  /* Dump strings in $"...", don't execute. */
201 int dump_po_strings;            /* Dump strings in $"..." in po format */
202 int wordexp_only = 0;           /* Do word expansion only */
203 int protected_mode = 0;         /* No command substitution with --wordexp */
204
205 #if defined (STRICT_POSIX)
206 int posixly_correct = 1;        /* Non-zero means posix.2 superset. */
207 #else
208 int posixly_correct = 0;        /* Non-zero means posix.2 superset. */
209 #endif
210
211
212 /* Some long-winded argument names.  These are obviously new. */
213 #define Int 1
214 #define Charp 2
215 struct {
216   char *name;
217   int type;
218   int *int_value;
219   char **char_value;
220 } long_args[] = {
221   { "debug", Int, &debugging, (char **)0x0 },
222 #if defined (DEBUGGER)
223   { "debugger", Int, &debugging_mode, (char **)0x0 },
224 #endif
225   { "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
226   { "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
227   { "help", Int, &want_initial_help, (char **)0x0 },
228   { "init-file", Charp, (int *)0x0, &bashrc_file },
229   { "login", Int, &make_login_shell, (char **)0x0 },
230   { "noediting", Int, &no_line_editing, (char **)0x0 },
231   { "noprofile", Int, &no_profile, (char **)0x0 },
232   { "norc", Int, &no_rc, (char **)0x0 },
233   { "posix", Int, &posixly_correct, (char **)0x0 },
234   { "protected", Int, &protected_mode, (char **)0x0 },
235   { "rcfile", Charp, (int *)0x0, &bashrc_file },
236 #if defined (RESTRICTED_SHELL)
237   { "restricted", Int, &restricted, (char **)0x0 },
238 #endif
239   { "verbose", Int, &echo_input_at_read, (char **)0x0 },
240   { "version", Int, &do_version, (char **)0x0 },
241   { "wordexp", Int, &wordexp_only, (char **)0x0 },
242   { (char *)0x0, Int, (int *)0x0, (char **)0x0 }
243 };
244
245 /* These are extern so execute_simple_command can set them, and then
246    longjmp back to main to execute a shell script, instead of calling
247    main () again and resulting in indefinite, possibly fatal, stack
248    growth. */
249 procenv_t subshell_top_level;
250 int subshell_argc;
251 char **subshell_argv;
252 char **subshell_envp;
253
254 #if defined (BUFFERED_INPUT)
255 /* The file descriptor from which the shell is reading input. */
256 int default_buffered_input = -1;
257 #endif
258
259 /* The following two variables are not static so they can show up in $-. */
260 int read_from_stdin;            /* -s flag supplied */
261 int want_pending_command;       /* -c flag supplied */
262
263 /* This variable is not static so it can be bound to $BASH_EXECUTION_STRING */
264 char *command_execution_string; /* argument to -c option */
265
266 int malloc_trace_at_exit = 0;
267
268 static int shell_reinitialized = 0;
269
270 static FILE *default_input;
271
272 static STRING_INT_ALIST *shopt_alist;
273 static int shopt_ind = 0, shopt_len = 0;
274
275 static int parse_long_options __P((char **, int, int));
276 static int parse_shell_options __P((char **, int, int));
277 static int bind_args __P((char **, int, int, int));
278
279 static void start_debugger __P((void));
280
281 static void add_shopt_to_alist __P((char *, int));
282 static void run_shopt_alist __P((void));
283
284 static void execute_env_file __P((char *));
285 static void run_startup_files __P((void));
286 static int open_shell_script __P((char *));
287 static void set_bash_input __P((void));
288 static int run_one_command __P((char *));
289 static int run_wordexp __P((char *));
290
291 static int uidget __P((void));
292
293 static void init_interactive __P((void));
294 static void init_noninteractive __P((void));
295
296 static void set_shell_name __P((char *));
297 static void shell_initialize __P((void));
298 static void shell_reinitialize __P((void));
299
300 static void show_shell_usage __P((FILE *, int));
301
302 #ifdef __CYGWIN__
303 static void
304 _cygwin32_check_tmp ()
305 {
306   struct stat sb;
307
308   if (stat ("/tmp", &sb) < 0)
309     internal_warning (_("could not find /tmp, please create!"));
310   else
311     {
312       if (S_ISDIR (sb.st_mode) == 0)
313         internal_warning (_("/tmp must be a valid directory name"));
314     }
315 }
316 #endif /* __CYGWIN__ */
317
318 #if defined (NO_MAIN_ENV_ARG)
319 /* systems without third argument to main() */
320 int
321 main (argc, argv)
322      int argc;
323      char **argv;
324 #else /* !NO_MAIN_ENV_ARG */
325 int
326 main (argc, argv, env)
327      int argc;
328      char **argv, **env;
329 #endif /* !NO_MAIN_ENV_ARG */
330 {
331   register int i;
332   int code, old_errexit_flag;
333 #if defined (RESTRICTED_SHELL)
334   int saverst;
335 #endif
336   volatile int locally_skip_execution;
337   volatile int arg_index, top_level_arg_index;
338 #ifdef __OPENNT
339   char **env;
340
341   env = environ;
342 #endif /* __OPENNT */
343
344   USE_VAR(argc);
345   USE_VAR(argv);
346   USE_VAR(env);
347   USE_VAR(code);
348   USE_VAR(old_errexit_flag);
349 #if defined (RESTRICTED_SHELL)
350   USE_VAR(saverst);
351 #endif
352
353   /* Catch early SIGINTs. */
354   code = setjmp (top_level);
355   if (code)
356     exit (2);
357
358 #if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
359 #  if 1
360   malloc_set_register (1);
361 #  endif
362 #endif
363
364   check_dev_tty ();
365
366 #ifdef __CYGWIN__
367   _cygwin32_check_tmp ();
368 #endif /* __CYGWIN__ */
369
370   /* Wait forever if we are debugging a login shell. */
371   while (debugging_login_shell) sleep (3);
372
373   set_default_locale ();
374
375   running_setuid = uidget ();
376
377   if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
378     posixly_correct = 1;
379
380 #if defined (USE_GNU_MALLOC_LIBRARY)
381   mcheck (programming_error, (void (*) ())0);
382 #endif /* USE_GNU_MALLOC_LIBRARY */
383
384   if (setjmp (subshell_top_level))
385     {
386       argc = subshell_argc;
387       argv = subshell_argv;
388       env = subshell_envp;
389       sourced_env = 0;
390     }
391
392   shell_reinitialized = 0;
393
394   /* Initialize `local' variables for all `invocations' of main (). */
395   arg_index = 1;
396   if (arg_index > argc)
397     arg_index = argc;
398   command_execution_string = (char *)NULL;
399   want_pending_command = locally_skip_execution = read_from_stdin = 0;
400   default_input = stdin;
401 #if defined (BUFFERED_INPUT)
402   default_buffered_input = -1;
403 #endif
404
405   /* Fix for the `infinite process creation' bug when running shell scripts
406      from startup files on System V. */
407   login_shell = make_login_shell = 0;
408
409   /* If this shell has already been run, then reinitialize it to a
410      vanilla state. */
411   if (shell_initialized || shell_name)
412     {
413       /* Make sure that we do not infinitely recurse as a login shell. */
414       if (*shell_name == '-')
415         shell_name++;
416
417       shell_reinitialize ();
418       if (setjmp (top_level))
419         exit (2);
420     }
421
422   shell_environment = env;
423   set_shell_name (argv[0]);
424   shell_start_time = NOW;       /* NOW now defined in general.h */
425
426   /* Parse argument flags from the input line. */
427
428   /* Find full word arguments first. */
429   arg_index = parse_long_options (argv, arg_index, argc);
430
431   if (want_initial_help)
432     {
433       show_shell_usage (stdout, 1);
434       exit (EXECUTION_SUCCESS);
435     }
436
437   if (do_version)
438     {
439       show_shell_version (1);
440       exit (EXECUTION_SUCCESS);
441     }
442
443   /* All done with full word options; do standard shell option parsing.*/
444   this_command_name = shell_name;       /* for error reporting */
445   arg_index = parse_shell_options (argv, arg_index, argc);
446
447   /* If user supplied the "--login" (or -l) flag, then set and invert
448      LOGIN_SHELL. */
449   if (make_login_shell)
450     {
451       login_shell++;
452       login_shell = -login_shell;
453     }
454
455   set_login_shell (login_shell != 0);
456
457   if (dump_po_strings)
458     dump_translatable_strings = 1;
459
460   if (dump_translatable_strings)
461     read_but_dont_execute = 1;
462
463   if (running_setuid && privileged_mode == 0)
464     disable_priv_mode ();
465
466   /* Need to get the argument to a -c option processed in the
467      above loop.  The next arg is a command to execute, and the
468      following args are $0...$n respectively. */
469   if (want_pending_command)
470     {
471       command_execution_string = argv[arg_index];
472       if (command_execution_string == 0)
473         {
474           report_error (_("%s: option requires an argument"), "-c");
475           exit (EX_BADUSAGE);
476         }
477       arg_index++;
478     }
479   this_command_name = (char *)NULL;
480
481   cmd_init();           /* initialize the command object caches */
482
483   /* First, let the outside world know about our interactive status.
484      A shell is interactive if the `-i' flag was given, or if all of
485      the following conditions are met:
486         no -c command
487         no arguments remaining or the -s flag given
488         standard input is a terminal
489         standard error is a terminal
490      Refer to Posix.2, the description of the `sh' utility. */
491
492   if (forced_interactive ||             /* -i flag */
493       (!command_execution_string &&     /* No -c command and ... */
494        wordexp_only == 0 &&             /* No --wordexp and ... */
495        ((arg_index == argc) ||          /*   no remaining args or... */
496         read_from_stdin) &&             /*   -s flag with args, and */
497        isatty (fileno (stdin)) &&       /* Input is a terminal and */
498        isatty (fileno (stderr))))       /* error output is a terminal. */
499     init_interactive ();
500   else
501     init_noninteractive ();
502
503 #define CLOSE_FDS_AT_LOGIN
504 #if defined (CLOSE_FDS_AT_LOGIN)
505   /*
506    * Some systems have the bad habit of starting login shells with lots of open
507    * file descriptors.  For instance, most systems that have picked up the
508    * pre-4.0 Sun YP code leave a file descriptor open each time you call one
509    * of the getpw* functions, and it's set to be open across execs.  That
510    * means one for login, one for xterm, one for shelltool, etc.
511    */
512   if (login_shell && interactive_shell)
513     {
514       for (i = 3; i < 20; i++)
515         close (i);
516     }
517 #endif /* CLOSE_FDS_AT_LOGIN */
518
519   /* If we're in a strict Posix.2 mode, turn on interactive comments,
520      alias expansion in non-interactive shells, and other Posix.2 things. */
521   if (posixly_correct)
522     {
523       bind_variable ("POSIXLY_CORRECT", "y", 0);
524       sv_strict_posix ("POSIXLY_CORRECT");
525     }
526
527   /* Now we run the shopt_alist and process the options. */
528   if (shopt_alist)
529     run_shopt_alist ();
530
531   /* From here on in, the shell must be a normal functioning shell.
532      Variables from the environment are expected to be set, etc. */
533   shell_initialize ();
534
535   set_default_lang ();
536   set_default_locale_vars ();
537
538   if (interactive_shell)
539     {
540       char *term, *emacs;
541
542       term = get_string_value ("TERM");
543       no_line_editing |= term && (STREQ (term, "emacs"));
544       emacs = get_string_value ("EMACS");
545       running_under_emacs = emacs ? ((strstr (emacs, "term") != 0) ? 2 : 1) : 0;
546 #if 0
547       no_line_editing |= emacs && emacs[0] == 't' && emacs[1] == '\0';
548 #else
549       no_line_editing |= emacs && emacs[0] == 't' && emacs[1] == '\0' && STREQ (term, "dumb");
550 #endif
551       if (running_under_emacs)
552         gnu_error_format = 1;
553     }
554
555   top_level_arg_index = arg_index;
556   old_errexit_flag = exit_immediately_on_error;
557
558   /* Give this shell a place to longjmp to before executing the
559      startup files.  This allows users to press C-c to abort the
560      lengthy startup. */
561   code = setjmp (top_level);
562   if (code)
563     {
564       if (code == EXITPROG || code == ERREXIT)
565         exit_shell (last_command_exit_value);
566       else
567         {
568 #if defined (JOB_CONTROL)
569           /* Reset job control, since run_startup_files turned it off. */
570           set_job_control (interactive_shell);
571 #endif
572           /* Reset value of `set -e', since it's turned off before running
573              the startup files. */
574           exit_immediately_on_error += old_errexit_flag;
575           locally_skip_execution++;
576         }
577     }
578
579   arg_index = top_level_arg_index;
580
581   /* Execute the start-up scripts. */
582
583   if (interactive_shell == 0)
584     {
585       unbind_variable ("PS1");
586       unbind_variable ("PS2");
587       interactive = 0;
588 #if 0
589       /* This has already been done by init_noninteractive */
590       expand_aliases = posixly_correct;
591 #endif
592     }
593   else
594     {
595       change_flag ('i', FLAG_ON);
596       interactive = 1;
597     }
598
599 #if defined (RESTRICTED_SHELL)
600   /* Set restricted_shell based on whether the basename of $0 indicates that
601      the shell should be restricted or if the `-r' option was supplied at
602      startup. */
603   restricted_shell = shell_is_restricted (shell_name);
604
605   /* If the `-r' option is supplied at invocation, make sure that the shell
606      is not in restricted mode when running the startup files. */
607   saverst = restricted;
608   restricted = 0;
609 #endif
610
611   /* The startup files are run with `set -e' temporarily disabled. */
612   if (locally_skip_execution == 0 && running_setuid == 0)
613     {
614       old_errexit_flag = exit_immediately_on_error;
615       exit_immediately_on_error = 0;
616
617       run_startup_files ();
618       exit_immediately_on_error += old_errexit_flag;
619     }
620
621   /* If we are invoked as `sh', turn on Posix mode. */
622   if (act_like_sh)
623     {
624       bind_variable ("POSIXLY_CORRECT", "y", 0);
625       sv_strict_posix ("POSIXLY_CORRECT");
626     }
627
628 #if defined (RESTRICTED_SHELL)
629   /* Turn on the restrictions after executing the startup files.  This
630      means that `bash -r' or `set -r' invoked from a startup file will
631      turn on the restrictions after the startup files are executed. */
632   restricted = saverst || restricted;
633   if (shell_reinitialized == 0)
634     maybe_make_restricted (shell_name);
635 #endif /* RESTRICTED_SHELL */
636
637   if (wordexp_only)
638     {
639       startup_state = 3;
640       last_command_exit_value = run_wordexp (argv[arg_index]);
641       exit_shell (last_command_exit_value);
642     }
643
644   if (command_execution_string)
645     {
646       arg_index = bind_args (argv, arg_index, argc, 0);
647       startup_state = 2;
648
649       if (debugging_mode)
650         start_debugger ();
651
652 #if defined (ONESHOT)
653       executing = 1;
654       run_one_command (command_execution_string);
655       exit_shell (last_command_exit_value);
656 #else /* ONESHOT */
657       with_input_from_string (command_execution_string, "-c");
658       goto read_and_execute;
659 #endif /* !ONESHOT */
660     }
661
662   /* Get possible input filename and set up default_buffered_input or
663      default_input as appropriate. */
664   if (arg_index != argc && read_from_stdin == 0)
665     {
666       open_shell_script (argv[arg_index]);
667       arg_index++;
668     }
669   else if (interactive == 0)
670     /* In this mode, bash is reading a script from stdin, which is a
671        pipe or redirected file. */
672 #if defined (BUFFERED_INPUT)
673     default_buffered_input = fileno (stdin);    /* == 0 */
674 #else
675     setbuf (default_input, (char *)NULL);
676 #endif /* !BUFFERED_INPUT */
677
678   set_bash_input ();
679
680   /* Bind remaining args to $1 ... $n */
681   arg_index = bind_args (argv, arg_index, argc, 1);
682
683   if (debugging_mode && locally_skip_execution == 0 && running_setuid == 0)
684     start_debugger ();
685
686   /* Do the things that should be done only for interactive shells. */
687   if (interactive_shell)
688     {
689       /* Set up for checking for presence of mail. */
690       remember_mail_dates ();
691       reset_mail_timer ();
692
693 #if defined (HISTORY)
694       /* Initialize the interactive history stuff. */
695       bash_initialize_history ();
696       /* Don't load the history from the history file if we've already
697          saved some lines in this session (e.g., by putting `history -s xx'
698          into one of the startup files). */
699       if (shell_initialized == 0 && history_lines_this_session == 0)
700         load_history ();
701 #endif /* HISTORY */
702
703       /* Initialize terminal state for interactive shells after the
704          .bash_profile and .bashrc are interpreted. */
705       get_tty_state ();
706     }
707
708 #if !defined (ONESHOT)
709  read_and_execute:
710 #endif /* !ONESHOT */
711
712   shell_initialized = 1;
713
714   /* Read commands until exit condition. */
715   reader_loop ();
716   exit_shell (last_command_exit_value);
717 }
718
719 static int
720 parse_long_options (argv, arg_start, arg_end)
721      char **argv;
722      int arg_start, arg_end;
723 {
724   int arg_index, longarg, i;
725   char *arg_string;
726
727   arg_index = arg_start;
728   while ((arg_index != arg_end) && (arg_string = argv[arg_index]) &&
729          (*arg_string == '-'))
730     {
731       longarg = 0;
732
733       /* Make --login equivalent to -login. */
734       if (arg_string[1] == '-' && arg_string[2])
735         {
736           longarg = 1;
737           arg_string++;
738         }
739
740       for (i = 0; long_args[i].name; i++)
741         {
742           if (STREQ (arg_string + 1, long_args[i].name))
743             {
744               if (long_args[i].type == Int)
745                 *long_args[i].int_value = 1;
746               else if (argv[++arg_index] == 0)
747                 {
748                   report_error (_("%s: option requires an argument"), long_args[i].name);
749                   exit (EX_BADUSAGE);
750                 }
751               else
752                 *long_args[i].char_value = argv[arg_index];
753
754               break;
755             }
756         }
757       if (long_args[i].name == 0)
758         {
759           if (longarg)
760             {
761               report_error (_("%s: invalid option"), argv[arg_index]);
762               show_shell_usage (stderr, 0);
763               exit (EX_BADUSAGE);
764             }
765           break;                /* No such argument.  Maybe flag arg. */
766         }
767
768       arg_index++;
769     }
770
771   return (arg_index);
772 }
773
774 static int
775 parse_shell_options (argv, arg_start, arg_end)
776      char **argv;
777      int arg_start, arg_end;
778 {
779   int arg_index;
780   int arg_character, on_or_off, next_arg, i;
781   char *o_option, *arg_string;
782
783   arg_index = arg_start;
784   while (arg_index != arg_end && (arg_string = argv[arg_index]) &&
785          (*arg_string == '-' || *arg_string == '+'))
786     {
787       /* There are flag arguments, so parse them. */
788       next_arg = arg_index + 1;
789
790       /* A single `-' signals the end of options.  From the 4.3 BSD sh.
791          An option `--' means the same thing; this is the standard
792          getopt(3) meaning. */
793       if (arg_string[0] == '-' &&
794            (arg_string[1] == '\0' ||
795              (arg_string[1] == '-' && arg_string[2] == '\0')))
796         return (next_arg);
797
798       i = 1;
799       on_or_off = arg_string[0];
800       while (arg_character = arg_string[i++])
801         {
802           switch (arg_character)
803             {
804             case 'c':
805               want_pending_command = 1;
806               break;
807
808             case 'l':
809               make_login_shell = 1;
810               break;
811
812             case 's':
813               read_from_stdin = 1;
814               break;
815
816             case 'o':
817               o_option = argv[next_arg];
818               if (o_option == 0)
819                 {
820                   list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
821                   break;
822                 }
823               if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
824                 exit (EX_BADUSAGE);
825               next_arg++;
826               break;
827
828             case 'O':
829               /* Since some of these can be overridden by the normal
830                  interactive/non-interactive shell initialization or
831                  initializing posix mode, we save the options and process
832                  them after initialization. */
833               o_option = argv[next_arg];
834               if (o_option == 0)
835                 {
836                   shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
837                   break;
838                 }
839               add_shopt_to_alist (o_option, on_or_off);
840               next_arg++;
841               break;
842
843             case 'D':
844               dump_translatable_strings = 1;
845               break;
846
847             default:
848               if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
849                 {
850                   report_error (_("%c%c: invalid option"), on_or_off, arg_character);
851                   show_shell_usage (stderr, 0);
852                   exit (EX_BADUSAGE);
853                 }
854             }
855         }
856       /* Can't do just a simple increment anymore -- what about
857          "bash -abouo emacs ignoreeof -hP"? */
858       arg_index = next_arg;
859     }
860
861   return (arg_index);
862 }
863
864 /* Exit the shell with status S. */
865 void
866 exit_shell (s)
867      int s;
868 {
869   /* Do trap[0] if defined.  Allow it to override the exit status
870      passed to us. */
871   if (signal_is_trapped (0))
872     s = run_exit_trap ();
873
874 #if defined (PROCESS_SUBSTITUTION)
875   unlink_fifo_list ();
876 #endif /* PROCESS_SUBSTITUTION */
877
878 #if defined (HISTORY)
879   if (interactive_shell)
880     maybe_save_shell_history ();
881 #endif /* HISTORY */
882
883 #if defined (JOB_CONTROL)
884   /* If the user has run `shopt -s huponexit', hangup all jobs when we exit
885      an interactive login shell.  ksh does this unconditionally. */
886   if (interactive_shell && login_shell && hup_on_exit)
887     hangup_all_jobs ();
888
889   /* If this shell is interactive, terminate all stopped jobs and
890      restore the original terminal process group.  Don't do this if we're
891      in a subshell and calling exit_shell after, for example, a failed
892      word expansion. */
893   if (subshell_environment == 0)
894     end_job_control ();
895 #endif /* JOB_CONTROL */
896
897   /* Always return the exit status of the last command to our parent. */
898   sh_exit (s);
899 }
900
901 /* A wrapper for exit that (optionally) can do other things, like malloc
902    statistics tracing. */
903 void
904 sh_exit (s)
905      int s;
906 {
907 #if defined (MALLOC_DEBUG) && defined (USING_BASH_MALLOC)
908   if (malloc_trace_at_exit)
909     trace_malloc_stats (get_name_for_error (), (char *)NULL);
910 #endif
911
912   exit (s);
913 }
914
915 /* Source the bash startup files.  If POSIXLY_CORRECT is non-zero, we obey
916    the Posix.2 startup file rules:  $ENV is expanded, and if the file it
917    names exists, that file is sourced.  The Posix.2 rules are in effect
918    for interactive shells only. (section 4.56.5.3) */
919
920 /* Execute ~/.bashrc for most shells.  Never execute it if
921    ACT_LIKE_SH is set, or if NO_RC is set.
922
923    If the executable file "/usr/gnu/src/bash/foo" contains:
924
925    #!/usr/gnu/bin/bash
926    echo hello
927
928    then:
929
930          COMMAND            EXECUTE BASHRC
931          --------------------------------
932          bash -c foo            NO
933          bash foo               NO
934          foo                    NO
935          rsh machine ls         YES (for rsh, which calls `bash -c')
936          rsh machine foo        YES (for shell started by rsh) NO (for foo!)
937          echo ls | bash         NO
938          login                  NO
939          bash                   YES
940 */
941
942 static void
943 execute_env_file (env_file)
944       char *env_file;
945 {
946   char *fn;
947
948   if (env_file && *env_file)
949     {
950       fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
951       if (fn && *fn)
952         maybe_execute_file (fn, 1);
953       FREE (fn);
954     }
955 }
956
957 static void
958 run_startup_files ()
959 {
960 #if defined (JOB_CONTROL)
961   int old_job_control;
962 #endif
963   int sourced_login, run_by_ssh;
964
965   /* get the rshd/sshd case out of the way first. */
966   if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
967       act_like_sh == 0 && command_execution_string)
968     {
969 #ifdef SSH_SOURCE_BASHRC
970       run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
971                    (find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
972 #else
973       run_by_ssh = 0;
974 #endif
975
976       /* If we were run by sshd or we think we were run by rshd, execute
977          ~/.bashrc if we are a top-level shell. */
978       if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
979         {
980 #ifdef SYS_BASHRC
981 #  if defined (__OPENNT)
982           maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
983 #  else
984           maybe_execute_file (SYS_BASHRC, 1);
985 #  endif
986 #endif
987           maybe_execute_file (bashrc_file, 1);
988           return;
989         }
990     }
991
992 #if defined (JOB_CONTROL)
993   /* Startup files should be run without job control enabled. */
994   old_job_control = interactive_shell ? set_job_control (0) : 0;
995 #endif
996
997   sourced_login = 0;
998
999   /* A shell begun with the --login (or -l) flag that is not in posix mode
1000      runs the login shell startup files, no matter whether or not it is
1001      interactive.  If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
1002      startup files if argv[0][0] == '-' as well. */
1003 #if defined (NON_INTERACTIVE_LOGIN_SHELLS)
1004   if (login_shell && posixly_correct == 0)
1005 #else
1006   if (login_shell < 0 && posixly_correct == 0)
1007 #endif
1008     {
1009       /* We don't execute .bashrc for login shells. */
1010       no_rc++;
1011
1012       /* Execute /etc/profile and one of the personal login shell
1013          initialization files. */
1014       if (no_profile == 0)
1015         {
1016           maybe_execute_file (SYS_PROFILE, 1);
1017
1018           if (act_like_sh)      /* sh */
1019             maybe_execute_file ("~/.profile", 1);
1020           else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
1021                    (maybe_execute_file ("~/.bash_login", 1) == 0))      /* bash */
1022             maybe_execute_file ("~/.profile", 1);
1023         }
1024
1025       sourced_login = 1;
1026     }
1027
1028   /* A non-interactive shell not named `sh' and not in posix mode reads and
1029      executes commands from $BASH_ENV.  If `su' starts a shell with `-c cmd'
1030      and `-su' as the name of the shell, we want to read the startup files.
1031      No other non-interactive shells read any startup files. */
1032   if (interactive_shell == 0 && !(su_shell && login_shell))
1033     {
1034       if (posixly_correct == 0 && act_like_sh == 0 && privileged_mode == 0 &&
1035             sourced_env++ == 0)
1036         execute_env_file (get_string_value ("BASH_ENV"));
1037       return;
1038     }
1039
1040   /* Interactive shell or `-su' shell. */
1041   if (posixly_correct == 0)               /* bash, sh */
1042     {
1043       if (login_shell && sourced_login++ == 0)
1044         {
1045           /* We don't execute .bashrc for login shells. */
1046           no_rc++;
1047
1048           /* Execute /etc/profile and one of the personal login shell
1049              initialization files. */
1050           if (no_profile == 0)
1051             {
1052               maybe_execute_file (SYS_PROFILE, 1);
1053
1054               if (act_like_sh)  /* sh */
1055                 maybe_execute_file ("~/.profile", 1);
1056               else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
1057                        (maybe_execute_file ("~/.bash_login", 1) == 0))  /* bash */
1058                 maybe_execute_file ("~/.profile", 1);
1059             }
1060         }
1061
1062       /* bash */
1063       if (act_like_sh == 0 && no_rc == 0)
1064         {
1065 #ifdef SYS_BASHRC
1066 #  if defined (__OPENNT)
1067           maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
1068 #  else
1069           maybe_execute_file (SYS_BASHRC, 1);
1070 #  endif
1071 #endif
1072           maybe_execute_file (bashrc_file, 1);
1073         }
1074       /* sh */
1075       else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
1076         execute_env_file (get_string_value ("ENV"));
1077     }
1078   else          /* bash --posix, sh --posix */
1079     {
1080       /* bash and sh */
1081       if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
1082         execute_env_file (get_string_value ("ENV"));
1083     }
1084
1085 #if defined (JOB_CONTROL)
1086   set_job_control (old_job_control);
1087 #endif
1088 }
1089
1090 #if defined (RESTRICTED_SHELL)
1091 /* Return 1 if the shell should be a restricted one based on NAME or the
1092    value of `restricted'.  Don't actually do anything, just return a
1093    boolean value. */
1094 int
1095 shell_is_restricted (name)
1096      char *name;
1097 {
1098   char *temp;
1099
1100   if (restricted)
1101     return 1;
1102   temp = base_pathname (name);
1103   if (*temp == '-')
1104     temp++;
1105   return (STREQ (temp, RESTRICTED_SHELL_NAME));
1106 }
1107
1108 /* Perhaps make this shell a `restricted' one, based on NAME.  If the
1109    basename of NAME is "rbash", then this shell is restricted.  The
1110    name of the restricted shell is a configurable option, see config.h.
1111    In a restricted shell, PATH, SHELL, ENV, and BASH_ENV are read-only
1112    and non-unsettable.
1113    Do this also if `restricted' is already set to 1; maybe the shell was
1114    started with -r. */
1115 int
1116 maybe_make_restricted (name)
1117      char *name;
1118 {
1119   char *temp;
1120
1121   temp = base_pathname (name);
1122   if (*temp == '-')
1123     temp++;
1124   if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
1125     {
1126       set_var_read_only ("PATH");
1127       set_var_read_only ("SHELL");
1128       set_var_read_only ("ENV");
1129       set_var_read_only ("BASH_ENV");
1130       restricted = 1;
1131     }
1132   return (restricted);
1133 }
1134 #endif /* RESTRICTED_SHELL */
1135
1136 /* Fetch the current set of uids and gids and return 1 if we're running
1137    setuid or setgid. */
1138 static int
1139 uidget ()
1140 {
1141   uid_t u;
1142
1143   u = getuid ();
1144   if (current_user.uid != u)
1145     {
1146       FREE (current_user.user_name);
1147       FREE (current_user.shell);
1148       FREE (current_user.home_dir);
1149       current_user.user_name = current_user.shell = current_user.home_dir = (char *)NULL;
1150     }
1151   current_user.uid = u;
1152   current_user.gid = getgid ();
1153   current_user.euid = geteuid ();
1154   current_user.egid = getegid ();
1155
1156   /* See whether or not we are running setuid or setgid. */
1157   return (current_user.uid != current_user.euid) ||
1158            (current_user.gid != current_user.egid);
1159 }
1160
1161 void
1162 disable_priv_mode ()
1163 {
1164   setuid (current_user.uid);
1165   setgid (current_user.gid);
1166   current_user.euid = current_user.uid;
1167   current_user.egid = current_user.gid;
1168 }
1169
1170 static int
1171 run_wordexp (words)
1172      char *words;
1173 {
1174   int code, nw, nb;
1175   WORD_LIST *wl, *tl, *result;
1176
1177   code = setjmp (top_level);
1178
1179   if (code != NOT_JUMPED)
1180     {
1181       switch (code)
1182         {
1183           /* Some kind of throw to top_level has occured. */
1184         case FORCE_EOF:
1185           return last_command_exit_value = 127;
1186         case ERREXIT:
1187         case EXITPROG:
1188           return last_command_exit_value;
1189         case DISCARD:
1190           return last_command_exit_value = 1;
1191         default:
1192           command_error ("run_wordexp", CMDERR_BADJUMP, code, 0);
1193         }
1194     }
1195
1196   /* Run it through the parser to get a list of words and expand them */
1197   if (words && *words)
1198     {
1199       with_input_from_string (words, "--wordexp");
1200       if (parse_command () != 0)
1201         return (126);
1202       if (global_command == 0)
1203         {
1204           printf ("0\n0\n");
1205           return (0);
1206         }
1207       if (global_command->type != cm_simple)
1208         return (126);
1209       wl = global_command->value.Simple->words;
1210       if (protected_mode)
1211         for (tl = wl; tl; tl = tl->next)
1212           tl->word->flags |= W_NOCOMSUB|W_NOPROCSUB;
1213       result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
1214     }
1215   else
1216     result = (WORD_LIST *)0;
1217
1218   last_command_exit_value = 0;
1219
1220   if (result == 0)
1221     {
1222       printf ("0\n0\n");
1223       return (0);
1224     }
1225
1226   /* Count up the number of words and bytes, and print them.  Don't count
1227      the trailing NUL byte. */
1228   for (nw = nb = 0, wl = result; wl; wl = wl->next)
1229     {
1230       nw++;
1231       nb += strlen (wl->word->word);
1232     }
1233   printf ("%u\n%u\n", nw, nb);
1234   /* Print each word on a separate line.  This will have to be changed when
1235      the interface to glibc is completed. */
1236   for (wl = result; wl; wl = wl->next)
1237     printf ("%s\n", wl->word->word);
1238
1239   return (0);
1240 }
1241
1242 #if defined (ONESHOT)
1243 /* Run one command, given as the argument to the -c option.  Tell
1244    parse_and_execute not to fork for a simple command. */
1245 static int
1246 run_one_command (command)
1247      char *command;
1248 {
1249   int code;
1250
1251   code = setjmp (top_level);
1252
1253   if (code != NOT_JUMPED)
1254     {
1255 #if defined (PROCESS_SUBSTITUTION)
1256       unlink_fifo_list ();
1257 #endif /* PROCESS_SUBSTITUTION */
1258       switch (code)
1259         {
1260           /* Some kind of throw to top_level has occured. */
1261         case FORCE_EOF:
1262           return last_command_exit_value = 127;
1263         case ERREXIT:
1264         case EXITPROG:
1265           return last_command_exit_value;
1266         case DISCARD:
1267           return last_command_exit_value = 1;
1268         default:
1269           command_error ("run_one_command", CMDERR_BADJUMP, code, 0);
1270         }
1271     }
1272    return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
1273 }
1274 #endif /* ONESHOT */
1275
1276 static int
1277 bind_args (argv, arg_start, arg_end, start_index)
1278      char **argv;
1279      int arg_start, arg_end, start_index;
1280 {
1281   register int i;
1282   WORD_LIST *args;
1283
1284   for (i = arg_start, args = (WORD_LIST *)NULL; i < arg_end; i++)
1285     args = make_word_list (make_word (argv[i]), args);
1286   if (args)
1287     {
1288       args = REVERSE_LIST (args, WORD_LIST *);
1289       if (start_index == 0)     /* bind to $0...$n for sh -c command */
1290         {
1291           /* Posix.2 4.56.3 says that the first argument after sh -c command
1292              becomes $0, and the rest of the arguments become $1...$n */
1293           shell_name = savestring (args->word->word);
1294           FREE (dollar_vars[0]);
1295           dollar_vars[0] = savestring (args->word->word);
1296           remember_args (args->next, 1);
1297           push_args (args->next);       /* BASH_ARGV and BASH_ARGC */
1298         }
1299       else                      /* bind to $1...$n for shell script */
1300         {
1301           remember_args (args, 1);
1302           push_args (args);             /* BASH_ARGV and BASH_ARGC */
1303         }
1304
1305       dispose_words (args);
1306     }
1307
1308   return (i);
1309 }
1310
1311 void
1312 unbind_args ()
1313 {
1314   remember_args ((WORD_LIST *)NULL, 1);
1315   pop_args ();                          /* Reset BASH_ARGV and BASH_ARGC */
1316 }
1317
1318 static void
1319 start_debugger ()
1320 {
1321 #if defined (DEBUGGER) && defined (DEBUGGER_START_FILE)
1322   int old_errexit;
1323
1324   old_errexit = exit_immediately_on_error;
1325   exit_immediately_on_error = 0;
1326
1327   maybe_execute_file (DEBUGGER_START_FILE, 1);
1328   function_trace_mode = 1;
1329
1330   exit_immediately_on_error += old_errexit;
1331 #endif
1332 }
1333
1334 static int
1335 open_shell_script (script_name)
1336      char *script_name;
1337 {
1338   int fd, e, fd_is_tty;
1339   char *filename, *path_filename, *t;
1340   char sample[80];
1341   int sample_len;
1342   struct stat sb;
1343 #if defined (ARRAY_VARS)
1344   SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
1345   ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
1346 #endif
1347
1348   filename = savestring (script_name);
1349
1350   fd = open (filename, O_RDONLY);
1351   if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
1352     {
1353       e = errno;
1354       /* If it's not in the current directory, try looking through PATH
1355          for it. */
1356       path_filename = find_path_file (script_name);
1357       if (path_filename)
1358         {
1359           free (filename);
1360           filename = path_filename;
1361           fd = open (filename, O_RDONLY);
1362         }
1363       else
1364         errno = e;
1365     }
1366
1367   if (fd < 0)
1368     {
1369       e = errno;
1370       file_error (filename);
1371       exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
1372     }
1373
1374   free (dollar_vars[0]);
1375   dollar_vars[0] = savestring (script_name);
1376
1377 #if defined (ARRAY_VARS)
1378   GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
1379   GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
1380   GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
1381
1382   array_push (bash_source_a, filename);
1383   if (bash_lineno_a)
1384     {
1385       t = itos (executing_line_number ());
1386       array_push (bash_lineno_a, t);
1387       free (t);
1388     }
1389   array_push (funcname_a, "main");
1390 #endif
1391
1392 #ifdef HAVE_DEV_FD
1393   fd_is_tty = isatty (fd);
1394 #else
1395   fd_is_tty = 0;
1396 #endif
1397
1398   /* Only do this with non-tty file descriptors we can seek on. */
1399   if (fd_is_tty == 0 && (lseek (fd, 0L, 1) != -1))
1400     {
1401       /* Check to see if the `file' in `bash file' is a binary file
1402          according to the same tests done by execute_simple_command (),
1403          and report an error and exit if it is. */
1404       sample_len = read (fd, sample, sizeof (sample));
1405       if (sample_len < 0)
1406         {
1407           e = errno;
1408           if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
1409             internal_error (_("%s: is a directory"), filename);
1410           else
1411             {
1412               errno = e;
1413               file_error (filename);
1414             }
1415           exit (EX_NOEXEC);
1416         }
1417       else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
1418         {
1419           internal_error ("%s: cannot execute binary file", filename);
1420           exit (EX_BINARY_FILE);
1421         }
1422       /* Now rewind the file back to the beginning. */
1423       lseek (fd, 0L, 0);
1424     }
1425
1426   /* Open the script.  But try to move the file descriptor to a randomly
1427      large one, in the hopes that any descriptors used by the script will
1428      not match with ours. */
1429   fd = move_to_high_fd (fd, 0, -1);
1430
1431 #if defined (__CYGWIN__) && defined (O_TEXT)
1432   setmode (fd, O_TEXT);
1433 #endif
1434
1435 #if defined (BUFFERED_INPUT)
1436   default_buffered_input = fd;
1437   SET_CLOSE_ON_EXEC (default_buffered_input);
1438 #else /* !BUFFERED_INPUT */
1439   default_input = fdopen (fd, "r");
1440
1441   if (default_input == 0)
1442     {
1443       file_error (filename);
1444       exit (EX_NOTFOUND);
1445     }
1446
1447   SET_CLOSE_ON_EXEC (fd);
1448   if (fileno (default_input) != fd)
1449     SET_CLOSE_ON_EXEC (fileno (default_input));
1450 #endif /* !BUFFERED_INPUT */
1451
1452   /* Just about the only way for this code to be executed is if something
1453      like `bash -i /dev/stdin' is executed. */
1454   if (interactive_shell && fd_is_tty)
1455     {
1456       dup2 (fd, 0);
1457       close (fd);
1458       fd = 0;
1459 #if defined (BUFFERED_INPUT)
1460       default_buffered_input = 0;
1461 #else
1462       fclose (default_input);
1463       default_input = stdin;
1464 #endif
1465     }
1466   else if (forced_interactive && fd_is_tty == 0)
1467     /* But if a script is called with something like `bash -i scriptname',
1468        we need to do a non-interactive setup here, since we didn't do it
1469        before. */
1470     init_noninteractive ();
1471
1472   free (filename);
1473   return (fd);
1474 }
1475
1476 /* Initialize the input routines for the parser. */
1477 static void
1478 set_bash_input ()
1479 {
1480   /* Make sure the fd from which we are reading input is not in
1481      no-delay mode. */
1482 #if defined (BUFFERED_INPUT)
1483   if (interactive == 0)
1484     sh_unset_nodelay_mode (default_buffered_input);
1485   else
1486 #endif /* !BUFFERED_INPUT */
1487     sh_unset_nodelay_mode (fileno (stdin));
1488
1489   /* with_input_from_stdin really means `with_input_from_readline' */
1490   if (interactive && no_line_editing == 0)
1491     with_input_from_stdin ();
1492 #if defined (BUFFERED_INPUT)
1493   else if (interactive == 0)
1494     with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
1495 #endif /* BUFFERED_INPUT */
1496   else
1497     with_input_from_stream (default_input, dollar_vars[0]);
1498 }
1499
1500 /* Close the current shell script input source and forget about it.  This is
1501    extern so execute_cmd.c:initialize_subshell() can call it.  If CHECK_ZERO
1502    is non-zero, we close default_buffered_input even if it's the standard
1503    input (fd 0). */
1504 void
1505 unset_bash_input (check_zero)
1506      int check_zero;
1507 {
1508 #if defined (BUFFERED_INPUT)
1509   if ((check_zero && default_buffered_input >= 0) ||
1510       (check_zero == 0 && default_buffered_input > 0))
1511     {
1512       close_buffered_fd (default_buffered_input);
1513       default_buffered_input = bash_input.location.buffered_fd = -1;
1514     }
1515 #else /* !BUFFERED_INPUT */
1516   if (default_input)
1517     {
1518       fclose (default_input);
1519       default_input = (FILE *)NULL;
1520     }
1521 #endif /* !BUFFERED_INPUT */
1522 }
1523       
1524
1525 #if !defined (PROGRAM)
1526 #  define PROGRAM "bash"
1527 #endif
1528
1529 static void
1530 set_shell_name (argv0)
1531      char *argv0;
1532 {
1533   /* Here's a hack.  If the name of this shell is "sh", then don't do
1534      any startup files; just try to be more like /bin/sh. */
1535   shell_name = argv0 ? base_pathname (argv0) : PROGRAM;
1536
1537   if (argv0 && *argv0 == '-')
1538     {
1539       if (*shell_name == '-')
1540         shell_name++;
1541       login_shell++;
1542     }
1543
1544   if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
1545     act_like_sh++;
1546   if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
1547     su_shell++;
1548
1549   shell_name = argv0 ? argv0 : PROGRAM;
1550   FREE (dollar_vars[0]);
1551   dollar_vars[0] = savestring (shell_name);
1552
1553   /* A program may start an interactive shell with
1554           "execl ("/bin/bash", "-", NULL)".
1555      If so, default the name of this shell to our name. */
1556   if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
1557     shell_name = PROGRAM;
1558 }
1559
1560 static void
1561 init_interactive ()
1562 {
1563   interactive_shell = startup_state = interactive = 1;
1564   expand_aliases = 1;
1565 }
1566
1567 static void
1568 init_noninteractive ()
1569 {
1570 #if defined (HISTORY)
1571   bash_history_reinit (0);
1572 #endif /* HISTORY */
1573   interactive_shell = startup_state = interactive = 0;
1574   expand_aliases = posixly_correct;     /* XXX - was 0 not posixly_correct */
1575   no_line_editing = 1;
1576 #if defined (JOB_CONTROL)
1577   set_job_control (0);
1578 #endif /* JOB_CONTROL */
1579 }
1580
1581 void
1582 get_current_user_info ()
1583 {
1584   struct passwd *entry;
1585
1586   /* Don't fetch this more than once. */
1587   if (current_user.user_name == 0)
1588     {
1589       entry = getpwuid (current_user.uid);
1590       if (entry)
1591         {
1592           current_user.user_name = savestring (entry->pw_name);
1593           current_user.shell = (entry->pw_shell && entry->pw_shell[0])
1594                                 ? savestring (entry->pw_shell)
1595                                 : savestring ("/bin/sh");
1596           current_user.home_dir = savestring (entry->pw_dir);
1597         }
1598       else
1599         {
1600           current_user.user_name = _("I have no name!");
1601           current_user.user_name = savestring (current_user.user_name);
1602           current_user.shell = savestring ("/bin/sh");
1603           current_user.home_dir = savestring ("/");
1604         }
1605       endpwent ();
1606     }
1607 }
1608
1609 /* Do whatever is necessary to initialize the shell.
1610    Put new initializations in here. */
1611 static void
1612 shell_initialize ()
1613 {
1614   char hostname[256];
1615
1616   /* Line buffer output for stderr and stdout. */
1617   if (shell_initialized == 0)
1618     {
1619       sh_setlinebuf (stderr);
1620       sh_setlinebuf (stdout);
1621     }
1622
1623   /* Sort the array of shell builtins so that the binary search in
1624      find_shell_builtin () works correctly. */
1625   initialize_shell_builtins ();
1626
1627   /* Initialize the trap signal handlers before installing our own
1628      signal handlers.  traps.c:restore_original_signals () is responsible
1629      for restoring the original default signal handlers.  That function
1630      is called when we make a new child. */
1631   initialize_traps ();
1632   initialize_signals (0);
1633
1634   /* It's highly unlikely that this will change. */
1635   if (current_host_name == 0)
1636     {
1637       /* Initialize current_host_name. */
1638       if (gethostname (hostname, 255) < 0)
1639         current_host_name = "??host??";
1640       else
1641         current_host_name = savestring (hostname);
1642     }
1643
1644   /* Initialize the stuff in current_user that comes from the password
1645      file.  We don't need to do this right away if the shell is not
1646      interactive. */
1647   if (interactive_shell)
1648     get_current_user_info ();
1649
1650   /* Initialize our interface to the tilde expander. */
1651   tilde_initialize ();
1652
1653   /* Initialize internal and environment variables.  Don't import shell
1654      functions from the environment if we are running in privileged or
1655      restricted mode or if the shell is running setuid. */
1656 #if defined (RESTRICTED_SHELL)
1657   initialize_shell_variables (shell_environment, privileged_mode||restricted||running_setuid);
1658 #else
1659   initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
1660 #endif
1661
1662   /* Initialize the data structures for storing and running jobs. */
1663   initialize_job_control (0);
1664
1665   /* Initialize input streams to null. */
1666   initialize_bash_input ();
1667
1668   initialize_flags ();
1669
1670   /* Initialize the shell options.  Don't import the shell options
1671      from the environment variable $SHELLOPTS if we are running in
1672      privileged or restricted mode or if the shell is running setuid. */
1673 #if defined (RESTRICTED_SHELL)
1674   initialize_shell_options (privileged_mode||restricted||running_setuid);
1675 #else
1676   initialize_shell_options (privileged_mode||running_setuid);
1677 #endif
1678 }
1679
1680 /* Function called by main () when it appears that the shell has already
1681    had some initialization performed.  This is supposed to reset the world
1682    back to a pristine state, as if we had been exec'ed. */
1683 static void
1684 shell_reinitialize ()
1685 {
1686   /* The default shell prompts. */
1687   primary_prompt = PPROMPT;
1688   secondary_prompt = SPROMPT;
1689
1690   /* Things that get 1. */
1691   current_command_number = 1;
1692
1693   /* We have decided that the ~/.bashrc file should not be executed
1694      for the invocation of each shell script.  If the variable $ENV
1695      (or $BASH_ENV) is set, its value is used as the name of a file
1696      to source. */
1697   no_rc = no_profile = 1;
1698
1699   /* Things that get 0. */
1700   login_shell = make_login_shell = interactive = executing = 0;
1701   debugging = do_version = line_number = last_command_exit_value = 0;
1702   forced_interactive = interactive_shell = subshell_environment = 0;
1703   expand_aliases = 0;
1704
1705 #if defined (HISTORY)
1706   bash_history_reinit (0);
1707 #endif /* HISTORY */
1708
1709 #if defined (RESTRICTED_SHELL)
1710   restricted = 0;
1711 #endif /* RESTRICTED_SHELL */
1712
1713   /* Ensure that the default startup file is used.  (Except that we don't
1714      execute this file for reinitialized shells). */
1715   bashrc_file = "~/.bashrc";
1716
1717   /* Delete all variables and functions.  They will be reinitialized when
1718      the environment is parsed. */
1719   delete_all_contexts (shell_variables);
1720   delete_all_variables (shell_functions);
1721
1722   shell_reinitialized = 1;
1723 }
1724
1725 static void
1726 show_shell_usage (fp, extra)
1727      FILE *fp;
1728      int extra;
1729 {
1730   int i;
1731   char *set_opts, *s, *t;
1732
1733   if (extra)
1734     fprintf (fp, "GNU bash, version %s-(%s)\n", shell_version_string (), MACHTYPE);
1735   fprintf (fp, _("Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n"),
1736              shell_name, shell_name);
1737   fputs (_("GNU long options:\n"), fp);
1738   for (i = 0; long_args[i].name; i++)
1739     fprintf (fp, "\t--%s\n", long_args[i].name);
1740
1741   fputs (_("Shell options:\n"), fp);
1742   fputs (_("\t-irsD or -c command or -O shopt_option\t\t(invocation only)\n"), fp);
1743
1744   for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
1745     if (STREQ (shell_builtins[i].name, "set"))
1746       set_opts = savestring (shell_builtins[i].short_doc);
1747   if (set_opts)
1748     {
1749       s = xstrchr (set_opts, '[');
1750       if (s == 0)
1751         s = set_opts;
1752       while (*++s == '-')
1753         ;
1754       t = xstrchr (s, ']');
1755       if (t)
1756         *t = '\0';
1757       fprintf (fp, _("\t-%s or -o option\n"), s);
1758       free (set_opts);
1759     }
1760
1761   if (extra)
1762     {
1763       fprintf (fp, _("Type `%s -c \"help set\"' for more information about shell options.\n"), shell_name);
1764       fprintf (fp, _("Type `%s -c help' for more information about shell builtin commands.\n"), shell_name);
1765       fprintf (fp, _("Use the `bashbug' command to report bugs.\n"));
1766     }
1767 }
1768
1769 static void
1770 add_shopt_to_alist (opt, on_or_off)
1771      char *opt;
1772      int on_or_off;
1773 {
1774   if (shopt_ind >= shopt_len)
1775     {
1776       shopt_len += 8;
1777       shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
1778     }
1779   shopt_alist[shopt_ind].word = opt;
1780   shopt_alist[shopt_ind].token = on_or_off;
1781   shopt_ind++;
1782 }
1783
1784 static void
1785 run_shopt_alist ()
1786 {
1787   register int i;
1788
1789   for (i = 0; i < shopt_ind; i++)
1790     if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
1791       exit (EX_BADUSAGE);
1792   free (shopt_alist);
1793   shopt_alist = 0;
1794   shopt_ind = shopt_len = 0;
1795 }