forked from bminor/bash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.cc
1879 lines (1635 loc) · 54.4 KB
/
shell.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* shell.cc -- GNU's idea of the POSIX shell specification. */
/* Copyright (C) 1987-2019 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Bash is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Bash. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Birthdate:
Sunday, January 10th, 1988.
Initial author: Brian Fox
*/
#include "config.h"
#include "shell.hh"
#include "conftypes.hh"
#if !defined(HAVE_GETPW_DECLS)
extern struct passwd *getpwuid ();
#endif /* !HAVE_GETPW_DECLS */
#if defined(NO_MAIN_ENV_ARG)
/* systems without third argument to main() */
int
main (int argc, char **argv)
{
try
{
bash::the_shell = new bash::Shell ();
bash::the_shell->start (argc, argv, bash::environ);
}
catch (const std::exception &e)
{
report_error (_ ("unhandled exception: %s"), e.what ());
exit (2);
}
}
#else /* !NO_MAIN_ENV_ARG */
int
main (int argc, char **argv, char **env)
{
try
{
bash::the_shell = new bash::Shell ();
bash::the_shell->start_shell (argc, argv, env);
}
catch (const std::exception &e)
{
fprintf (stderr, _ ("unhandled exception: %s"), e.what ());
exit (2);
}
}
#endif /* !NO_MAIN_ENV_ARG */
// Start of the bash namespace
namespace bash
{
void
Shell::init_long_args ()
{
long_args.push_back (LongArg ("debug", &debugging));
#if defined(DEBUGGER)
long_args.push_back (LongArg ("debugger", &debugging_mode));
#endif
long_args.push_back (LongArg ("dump-po-strings", &dump_po_strings));
long_args.push_back (LongArg ("dump-strings", &dump_translatable_strings));
long_args.push_back (LongArg ("help", &want_initial_help));
long_args.push_back (LongArg ("init-file", &bashrc_file));
long_args.push_back (LongArg ("login", &make_login_shell));
long_args.push_back (LongArg ("noediting", &no_line_editing));
long_args.push_back (LongArg ("noprofile", &no_profile));
long_args.push_back (LongArg ("norc", &no_rc));
long_args.push_back (LongArg ("posix", &posixly_correct));
long_args.push_back (LongArg ("pretty-print", &pretty_print_mode));
#if defined(WORDEXP_OPTION)
long_args.push_back (LongArg ("protected", &protected_mode));
#endif
long_args.push_back (LongArg ("rcfile", &bashrc_file));
#if defined(RESTRICTED_SHELL)
long_args.push_back (LongArg ("restricted", &restricted));
#endif
long_args.push_back (LongArg ("verbose", &verbose_flag));
long_args.push_back (LongArg ("version", &do_version));
#if defined(WORDEXP_OPTION)
long_args.push_back (LongArg ("wordexp", &wordexp_only));
#endif
}
#ifdef __CYGWIN__
void
Shell::_cygwin32_check_tmp ()
{
struct stat sb;
if (stat ("/tmp", &sb) < 0)
internal_warning (_ ("could not find /tmp, please create!"));
else
{
if (S_ISDIR (sb.st_mode) == 0)
internal_warning (_ ("/tmp must be a valid directory name"));
}
}
#endif /* __CYGWIN__ */
// Initialize the simple shell variables to default values.
SimpleState::SimpleState ()
: shell_tty (-1), shell_pgrp (NO_PID), terminal_pgrp (NO_PID),
original_pgrp (NO_PID), last_made_pid (NO_PID),
last_asynchronous_pid (NO_PID), current_command_number (1),
#if defined(BUFFERED_INPUT)
default_buffered_input (-1),
#endif
rseed (1), rseed32 (1073741823), last_command_subst_pid (NO_PID),
current_command_subst_pid (NO_PID), eof_encountered_limit (10),
word_top (-1), indentation_amount (4), xtrace_fd (-1), xattrfd (-1),
sh_opterr (true), sh_optopt ('?'), array_needs_making (true),
#if defined(JOB_CONTROL)
job_control (true),
#endif
check_window_size (CHECKWINSIZE_DEFAULT), hashing_enabled (1),
#if defined(BANG_HISTORY)
history_expansion (HISTEXPAND_DEFAULT),
#endif
interactive_comments (1),
#if defined(RESTRICTED_SHELL)
save_restricted (-1),
#endif
#if defined(BRACE_EXPANSION)
brace_expansion (1),
#endif
extended_quote (1), promptvars (1),
#ifdef HAVE_DEV_FD
have_devfd (HAVE_DEV_FD),
#endif
#if !defined(READLINE)
no_line_editing (1), /* can't have line editing without readline */
#endif
#if defined(STRICT_POSIX)
posixly_correct (1)
#else
posixly_correct (0)
#endif
{
// XXX - remove this if Linux doesn't need this path
#if defined(PGRP_PIPE)
// initialize the array here for strict C++03 compatibility
pgrp_pipe[0] = -1;
pgrp_pipe[1] = -1;
#endif
// manual init for C++03 compatibility
getopt_errstr[0] = '-';
getopt_errstr[1] = '\0';
getopt_errstr[2] = '\0';
}
Shell::Shell ()
: SimpleState (), bashrc_file (const_cast<char *> (DEFAULT_BASHRC)),
primary_prompt (PPROMPT), secondary_prompt (SPROMPT), source (0),
redir (0), old_winch (SIG_DFL), execignore ("EXECIGNORE"),
fignore ("FIGNORE"), globignore ("GLOBIGNORE"), histignore ("HISTIGNORE")
{
// alloc this 4K read buffer from the heap to keep the class size small
zread_lbuf = new char[ZBUFSIZ];
init_long_args ();
posix_vars[0] = &interactive_comments;
posix_vars[1] = &source_uses_path;
posix_vars[2] = &expand_aliases;
posix_vars[3] = &inherit_errexit;
posix_vars[4] = &print_shift_error;
init_token_lists ();
}
// Virtual destructor for Shell.
Shell::~Shell () noexcept { delete[] zread_lbuf; }
// Everything happens when we call this method.
// Renamed from "start" to avoid accidentally appearing to be
// a local variable named "start".
void
Shell::start_shell (int argc, char **argv, char **env)
{
early_init ();
for (;;)
{
try
{
run_shell (argc, argv, env);
}
catch (const subshell_child_start &)
{
argc = subshell_argc;
argv = subshell_argv;
env = subshell_envp;
sourced_env = false;
}
}
}
void
Shell::early_init ()
{
xtrace_init ();
#ifdef __CYGWIN__
_cygwin32_check_tmp ();
#endif /* __CYGWIN__ */
/* Wait forever if we are debugging a login shell. */
while (debugging_login_shell)
sleep (3);
set_default_locale ();
running_setuid = uidget ();
if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
posixly_correct = true;
}
void
Shell::run_shell (int argc, char **argv, char **env)
{
#if defined(RESTRICTED_SHELL)
int saverst;
#endif
bool locally_skip_execution;
shell_reinitialized = false;
/* Initialize `local' variables for all `invocations' of main (). */
int arg_index = 1;
if (arg_index > argc)
arg_index = argc;
command_execution_string = nullptr;
shell_script_filename = nullptr;
want_pending_command = locally_skip_execution = read_from_stdin = false;
default_input = stdin;
#if defined(BUFFERED_INPUT)
default_buffered_input = -1;
#endif
/* Fix for the `infinite process creation' bug when running shell scripts
from startup files on System V. */
login_shell = make_login_shell = 0;
/* If this shell has already been run, then reinitialize it to a
vanilla state. */
if (shell_initialized || shell_name)
{
/* Make sure that we do not infinitely recurse as a login shell. */
if (*shell_name == '-')
shell_name++;
shell_reinitialize ();
}
shell_environment = env;
set_shell_name (argv[0]);
gettimeofday (&shellstart, nullptr);
shell_start_time = shellstart.tv_sec;
/* Parse argument flags from the input line. */
/* Find full word arguments first. */
arg_index = parse_long_options (argv, arg_index, argc);
if (want_initial_help)
{
show_shell_usage (stdout, true);
exit (EXECUTION_SUCCESS);
}
if (do_version)
{
show_shell_version (1);
exit (EXECUTION_SUCCESS);
}
echo_input_at_read = verbose_flag; /* --verbose given */
/* All done with full word options; do standard shell option parsing.*/
this_command_name = shell_name; /* for error reporting */
arg_index = parse_shell_options (argv, arg_index, argc);
/* If user supplied the "--login" (or -l) flag, then set and invert
LOGIN_SHELL. */
if (make_login_shell)
{
login_shell++;
login_shell = -login_shell;
}
set_login_shell ("login_shell", login_shell != 0);
if (dump_po_strings)
dump_translatable_strings = true;
if (dump_translatable_strings)
read_but_dont_execute = 1;
if (running_setuid && privileged_mode == 0)
disable_priv_mode ();
/* Need to get the argument to a -c option processed in the
above loop. The next arg is a command to execute, and the
following args are $0...$n respectively. */
if (want_pending_command)
{
command_execution_string = argv[arg_index];
if (command_execution_string == nullptr)
{
report_error (_ ("%s: option requires an argument"), "-c");
exit (EX_BADUSAGE);
}
arg_index++;
}
this_command_name.clear ();
/* First, let the outside world know about our interactive status.
A shell is interactive if the `-i' flag was given, or if all of
the following conditions are met:
no -c command
no arguments remaining or the -s flag given
standard input is a terminal
standard error is a terminal
Refer to Posix.2, the description of the `sh' utility. */
if (forced_interactive || // -i flag or
(!command_execution_string && // No -c command and ...
!wordexp_only && // No --wordexp and ...
((arg_index == argc) || // no remaining args or...
read_from_stdin)
&& // -s flag with args, and
isatty (fileno (stdin)) && // Input is a terminal and
isatty (fileno (stderr)))) // error output is a terminal.
init_interactive ();
else
init_noninteractive ();
/* If we're in a strict Posix.2 mode, turn on interactive comments,
alias expansion in non-interactive shells, and other Posix.2 things.
*/
if (posixly_correct)
{
bind_variable ("POSIXLY_CORRECT", "y");
sv_strict_posix ("POSIXLY_CORRECT");
}
/* Now we run the shopt_alist and process the options. */
if (!shopt_alist.empty ())
run_shopt_alist ();
/* From here on in, the shell must be a normal functioning shell.
Variables from the environment are expected to be set, etc. */
shell_initialize ();
set_default_lang ();
set_default_locale_vars ();
/*
* M-x term -> TERM=eterm-color INSIDE_EMACS='251,term:0.96' (eterm)
* M-x shell -> TERM='dumb' INSIDE_EMACS='25.1,comint' (no line editing)
*
* Older versions of Emacs may set EMACS to 't' or to something like
* '22.1 (term:0.96)' instead of (or in addition to) setting
* INSIDE_EMACS. They may set TERM to 'eterm' instead of 'eterm-color'.
* They may have a now-obsolete command that sets neither EMACS nor
* INSIDE_EMACS: M-x terminal -> TERM='emacs-em7955' (line editing)
*/
if (interactive_shell)
{
bool emacs_term, in_emacs;
const string *term = get_string_value ("TERM");
const string *emacs = get_string_value ("EMACS");
const string *inside_emacs = get_string_value ("INSIDE_EMACS");
if (inside_emacs)
{
emacs_term = inside_emacs->find (",term:") != string::npos;
in_emacs = true;
}
else if (emacs)
{
/* Infer whether we are in an older Emacs. */
emacs_term = emacs->find (" (term:") != string::npos;
in_emacs = emacs_term || *emacs == "t";
}
else
in_emacs = emacs_term = false;
/* Not sure any emacs terminal emulator sets TERM=emacs any more */
if (term)
{
no_line_editing |= *term == "emacs";
no_line_editing |= in_emacs && *term == "dumb";
/* running_under_emacs == 2 for `eterm' */
running_under_emacs = in_emacs || term->find ("emacs") == 0;
running_under_emacs += emacs_term && term->find ("eterm") == 0;
}
if (running_under_emacs)
gnu_error_format = 1;
}
int top_level_arg_index = arg_index;
// Note: Infer says this write is a dead store, but the variable is
// used in the catch block, so I think it's necessary to initialize it.
char old_errexit_flag = exit_immediately_on_error;
/* Give this shell a place to catch exceptions before executing the
startup files. This allows users to press C-c to abort the
lengthy startup, which retries with locally_skip_execution set. */
for (;;)
{
try
{
arg_index = top_level_arg_index;
/* Execute the start-up scripts. */
if (!interactive_shell)
{
unbind_variable ("PS1");
unbind_variable ("PS2");
interactive = false;
#if 0
/* This has already been done by init_noninteractive */
expand_aliases = posixly_correct;
#endif
}
else
{
change_flag ('i', FLAG_ON);
interactive = true;
}
#if defined(RESTRICTED_SHELL)
/* Set restricted_shell based on whether the basename of $0 indicates
that the shell should be restricted or if the `-r' option was
supplied at startup. */
restricted_shell = shell_is_restricted (shell_name);
/* If the `-r' option is supplied at invocation, make sure that the
shell is not in restricted mode when running the startup files. */
saverst = restricted;
restricted = 0;
#endif
/* Set positional parameters before running startup files.
top_level_arg_index holds the index of the current argument before
setting the positional parameters, so any changes performed in the
startup files won't affect later option processing. */
if (wordexp_only)
; /* nothing yet */
else if (command_execution_string)
(void)bind_args (argv, arg_index, argc, 0); /* $0 ... $n */
else if (arg_index != argc && read_from_stdin == 0)
{
shell_script_filename = argv[arg_index++];
(void)bind_args (argv, arg_index, argc, 1); /* $1 ... $n */
}
else
(void)bind_args (argv, arg_index, argc, 1); /* $1 ... $n */
/* The startup files are run with `set -e' temporarily disabled. */
if (!locally_skip_execution && !running_setuid)
{
old_errexit_flag = exit_immediately_on_error;
exit_immediately_on_error = 0;
run_startup_files ();
exit_immediately_on_error += old_errexit_flag;
}
/* If we are invoked as `sh', turn on Posix mode. */
if (act_like_sh)
{
bind_variable ("POSIXLY_CORRECT", "y");
sv_strict_posix ("POSIXLY_CORRECT");
}
#if defined(RESTRICTED_SHELL)
/* Turn on the restrictions after executing the startup files. This
means that `bash -r' or `set -r' invoked from a startup file will
turn on the restrictions after the startup files are executed. */
restricted = saverst || restricted;
if (!shell_reinitialized)
maybe_make_restricted (shell_name);
#endif /* RESTRICTED_SHELL */
#if defined(WORDEXP_OPTION)
if (wordexp_only)
{
startup_state = 3;
last_command_exit_value
= run_wordexp (argv[top_level_arg_index]);
exit_shell (last_command_exit_value);
}
#endif
if (command_execution_string)
{
startup_state = 2;
if (debugging_mode)
start_debugger ();
#if defined(ONESHOT)
executing = true;
run_one_command (command_execution_string);
exit_shell (last_command_exit_value);
#else /* ONESHOT */
with_input_from_string (command_execution_string, "-c");
goto read_and_execute;
#endif /* !ONESHOT */
}
/* Get possible input filename and set up default_buffered_input or
default_input as appropriate. */
if (shell_script_filename)
open_shell_script (shell_script_filename);
else if (!interactive)
{
/* In this mode, bash is reading a script from stdin, which is a
pipe or redirected file. */
#if defined(BUFFERED_INPUT)
default_buffered_input = fileno (stdin); /* == 0 */
#else
setbuf (default_input, nullptr);
#endif /* !BUFFERED_INPUT */
read_from_stdin = true;
}
else if (top_level_arg_index
== argc) /* arg index before startup files */
/* "If there are no operands and the -c option is not specified,
the -s option shall be assumed." */
read_from_stdin = true;
set_bash_input ();
if (debugging_mode && locally_skip_execution == 0
&& running_setuid == 0
&& (reading_shell_script || interactive_shell == 0))
start_debugger ();
/* Do the things that should be done only for interactive shells. */
if (interactive_shell)
{
/* Set up for checking for presence of mail. */
reset_mail_timer ();
init_mail_dates ();
#if defined(HISTORY)
/* Initialize the interactive history stuff. */
bash_initialize_history ();
/* Don't load the history from the history file if we've already
saved some lines in this session (e.g., by putting `history -s
xx' into one of the startup files). */
if (!shell_initialized && history_lines_this_session == 0)
load_history ();
#endif /* HISTORY */
/* Initialize terminal state for interactive shells after the
.bash_profile and .bashrc are interpreted. */
get_tty_state ();
}
#if !defined(ONESHOT)
read_and_execute:
#endif /* !ONESHOT */
shell_initialized = true;
if (pretty_print_mode && interactive_shell)
{
internal_warning (
_ ("pretty-printing mode ignored in interactive shells"));
pretty_print_mode = false;
}
if (pretty_print_mode)
exit_shell (pretty_print_loop ());
/* Read commands until exit condition. */
reader_loop ();
exit_shell (last_command_exit_value);
}
catch (const bash_exception &e)
{
if (e.type == EXITPROG || e.type == ERREXIT)
exit_shell (last_command_exit_value);
else
{
#if defined(JOB_CONTROL)
/* Reset job control, since run_startup_files turned it off. */
set_job_control (interactive_shell);
#endif
/* Reset value of `set -e', since it's turned off before running
the startup files. */
exit_immediately_on_error += old_errexit_flag;
locally_skip_execution = true;
}
}
}
}
int
Shell::parse_long_options (char **argv, int arg_start, int arg_end)
{
int arg_index, longarg;
char *arg_string;
arg_index = arg_start;
while ((arg_index != arg_end) && (arg_string = argv[arg_index])
&& (*arg_string == '-'))
{
longarg = 0;
/* Make --login equivalent to -login. */
if (arg_string[1] == '-' && arg_string[2])
{
longarg = 1;
arg_string++;
}
vector<LongArg>::const_iterator it;
string_view this_arg (arg_string + 1); // skip '-'
bool found = false;
for (it = long_args.begin (); it != long_args.end (); ++it)
{
if (this_arg == (*it).name)
{
if ((*it).type == Bool)
*(*it).value.bool_ptr = true;
else if ((*it).type == Flag)
*(*it).value.flag_ptr = 1;
else if (argv[++arg_index] == nullptr)
{
string name_cstr (to_string ((*it).name));
report_error (_ ("%s: option requires an argument"),
name_cstr.c_str ());
exit (EX_BADUSAGE);
}
else
*(*it).value.char_ptr = argv[arg_index];
found = true;
break;
}
}
if (!found)
{
if (longarg)
{
report_error (_ ("%s: invalid option"), argv[arg_index]);
show_shell_usage (stderr, false);
exit (EX_BADUSAGE);
}
break; /* No such argument. Maybe flag arg. */
}
arg_index++;
}
return arg_index;
}
int
Shell::parse_shell_options (char **argv, int arg_start, int arg_end)
{
char *arg_string;
int arg_index = arg_start;
while (arg_index != arg_end && (arg_string = argv[arg_index])
&& (*arg_string == '-' || *arg_string == '+'))
{
/* There are flag arguments, so parse them. */
int next_arg = arg_index + 1;
/* A single `-' signals the end of options. From the 4.3 BSD sh.
An option `--' means the same thing; this is the standard
getopt(3) meaning. */
if (arg_string[0] == '-'
&& (arg_string[1] == '\0'
|| (arg_string[1] == '-' && arg_string[2] == '\0')))
return next_arg;
int i = 1;
char arg_character;
char *o_option;
char on_or_off = arg_string[0];
while ((arg_character = arg_string[i++]))
{
switch (arg_character)
{
case 'c':
want_pending_command = true;
break;
case 'l':
make_login_shell = true;
break;
case 's':
read_from_stdin = true;
break;
case 'o':
o_option = argv[next_arg];
if (o_option == nullptr)
{
set_option_defaults ();
list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
reset_option_defaults ();
break;
}
if (set_minus_o_option (on_or_off, o_option)
!= EXECUTION_SUCCESS)
exit (EX_BADUSAGE);
next_arg++;
break;
case 'O':
/* Since some of these can be overridden by the normal
interactive/non-interactive shell initialization or
initializing posix mode, we save the options and process
them after initialization. */
o_option = argv[next_arg];
if (o_option == nullptr)
{
shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
break;
}
add_shopt_to_alist (o_option, on_or_off);
next_arg++;
break;
case 'D':
dump_translatable_strings = true;
break;
default:
if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
{
report_error (_ ("%c%c: invalid option"), on_or_off,
arg_character);
show_shell_usage (stderr, false);
exit (EX_BADUSAGE);
}
}
}
/* Can't do just a simple increment anymore -- what about
"bash -abouo emacs ignoreeof -hP"? */
arg_index = next_arg;
}
return arg_index;
}
/* Exit the shell with status S. */
void
Shell::exit_shell (int s)
{
fflush (stdout); /* XXX */
fflush (stderr);
/* Clean up the terminal if we are in a state where it's been modified. */
#if defined(READLINE)
if (RL_ISSTATE (RL_STATE_TERMPREPPED) && rl_deprep_term_function)
(*(dynamic_cast<Readline *> (this)).*rl_deprep_term_function) ();
#endif
if (read_tty_modified ())
read_tty_cleanup ();
/* Do trap[0] if defined. Allow it to override the exit status
passed to us. */
if (signal_is_trapped (0))
s = run_exit_trap ();
#if defined(PROCESS_SUBSTITUTION)
unlink_all_fifos ();
#endif /* PROCESS_SUBSTITUTION */
#if defined(HISTORY)
if (remember_on_history)
maybe_save_shell_history ();
#endif /* HISTORY */
#if defined(COPROCESS_SUPPORT)
coproc_flush ();
#endif
#if defined(JOB_CONTROL)
/* If the user has run `shopt -s huponexit', hangup all jobs when we exit
an interactive login shell. ksh does this unconditionally. */
if (interactive_shell && login_shell && hup_on_exit)
hangup_all_jobs ();
/* If this shell is interactive, or job control is active, terminate all
stopped jobs and restore the original terminal process group. Don't do
this if we're in a subshell and calling exit_shell after, for example,
a failed word expansion. We want to do this even if the shell is not
interactive because we set the terminal's process group when job control
is enabled regardless of the interactive status. */
if (subshell_environment == 0)
end_job_control ();
#endif /* JOB_CONTROL */
/* Always return the exit status of the last command to our parent. */
sh_exit (s);
}
/* Exit a subshell, which includes calling the exit trap. We don't want to
do any more cleanup, since a subshell is created as an exact copy of its
parent. */
void
Shell::subshell_exit (int s)
{
fflush (stdout);
fflush (stderr);
/* Do trap[0] if defined. Allow it to override the exit status
passed to us. */
if (signal_is_trapped (0))
s = run_exit_trap ();
sh_exit (s);
}
/* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
the Posix.2 startup file rules: $ENV is expanded, and if the file it
names exists, that file is sourced. The Posix.2 rules are in effect
for interactive shells only. (section 4.56.5.3) */
/* Execute ~/.bashrc for most shells. Never execute it if
ACT_LIKE_SH is set, or if NO_RC is set.
If the executable file "/usr/gnu/src/bash/foo" contains:
#!/usr/gnu/bin/bash
echo hello
then:
COMMAND EXECUTE BASHRC
--------------------------------
bash -c foo NO
bash foo NO
foo NO
rsh machine ls YES (for rsh, which calls `bash -c')
rsh machine foo YES (for shell started by rsh) NO (for foo!)
echo ls | bash NO
login NO
bash YES
*/
void
Shell::execute_env_file (const char *env_file)
{
if (env_file && *env_file)
{
string fn (expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES));
if (!fn.empty ())
maybe_execute_file (fn.c_str (), true);
}
}
void
Shell::run_startup_files ()
{
#if defined(JOB_CONTROL)
bool old_job_control;
#endif
bool sourced_login, run_by_ssh;
/* get the rshd/sshd case out of the way first. */
if (!interactive_shell && !no_rc && (login_shell == 0) && !act_like_sh
&& command_execution_string)
{
#ifdef SSH_SOURCE_BASHRC
run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0)
|| (find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
#else
run_by_ssh = false;
#endif
/* If we were run by sshd or we think we were run by rshd, execute
~/.bashrc if we are a top-level shell. */
if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
{
#ifdef SYS_BASHRC
maybe_execute_file (SYS_BASHRC, 1);
#endif
maybe_execute_file (bashrc_file, 1);
return;
}
}
#if defined(JOB_CONTROL)
/* Startup files should be run without job control enabled. */
old_job_control = interactive_shell ? set_job_control (false) : false;
#endif
sourced_login = false;
/* A shell begun with the --login (or -l) flag that is not in posix mode
runs the login shell startup files, no matter whether or not it is
interactive. If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
startup files if argv[0][0] == '-' as well. */
#if defined(NON_INTERACTIVE_LOGIN_SHELLS)
if (login_shell && !posixly_correct)
#else
if (login_shell < 0 && !posixly_correct)
#endif
{
/* We don't execute .bashrc for login shells. */
no_rc = true;
/* Execute /etc/profile and one of the personal login shell
initialization files. */
if (!no_profile)
{
maybe_execute_file (SYS_PROFILE, true);
if (act_like_sh) /* sh */
maybe_execute_file ("~/.profile", true);
else if ((maybe_execute_file ("~/.bash_profile", true) == 0)
&& (maybe_execute_file ("~/.bash_login", true)
== 0)) /* bash */
maybe_execute_file ("~/.profile", true);
}
sourced_login = true;
}
/* A non-interactive shell not named `sh' and not in posix mode reads and
executes commands from $BASH_ENV. If `su' starts a shell with `-c cmd'
and `-su' as the name of the shell, we want to read the startup files.
No other non-interactive shells read any startup files. */
if (!interactive_shell && !(su_shell && login_shell))
{
if (!posixly_correct && !act_like_sh && !privileged_mode && !sourced_env)
{
sourced_env = true;
const string *bash_env = get_string_value ("BASH_ENV");
if (bash_env)
execute_env_file (bash_env->c_str ());
}
return;
}
/* Interactive shell or `-su' shell. */
if (!posixly_correct) /* bash, sh */
{
if (login_shell && !sourced_login)
{
// sourced_login = true; // not referenced again
/* We don't execute .bashrc for login shells. */
no_rc = true;
/* Execute /etc/profile and one of the personal login shell
initialization files. */
if (!no_profile)
{
maybe_execute_file (SYS_PROFILE, true);
if (act_like_sh) /* sh */
maybe_execute_file ("~/.profile", true);
else if ((maybe_execute_file ("~/.bash_profile", true) == 0)
&& (maybe_execute_file ("~/.bash_login", true)
== 0)) /* bash */
maybe_execute_file ("~/.profile", true);