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