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