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