1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2010 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
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.
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.
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/>.
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
34 #include "posixstat.h"
37 # include <sys/param.h>
40 #if defined (HAVE_UNISTD_H)
44 #include "posixtime.h"
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 # include <sys/resource.h>
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 # include <sys/times.h>
60 #define NEED_FPURGE_DECL
67 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
72 #include "execute_cmd.h"
79 #if defined (COND_COMMAND)
83 #include "builtins/common.h"
84 #include "builtins/builtext.h" /* list of builtins */
86 #include <glob/strmatch.h>
87 #include <tilde/tilde.h>
89 #if defined (BUFFERED_INPUT)
98 # include "bashhist.h"
101 extern int dollar_dollar_pid;
102 extern int posixly_correct;
103 extern int expand_aliases;
105 extern int breaking, continuing, loop_level;
106 extern int parse_and_execute_level, running_trap, sourcelevel;
107 extern int command_string_index, line_number;
108 extern int dot_found_in_search;
109 extern int already_making_children;
110 extern int tempenv_assign_error;
111 extern char *the_printed_command, *shell_name;
112 extern pid_t last_command_subst_pid;
113 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
114 extern char **subshell_argv, **subshell_envp;
115 extern int subshell_argc;
116 extern time_t shell_start_time;
118 extern char *glob_argv_flags;
121 extern int close __P((int));
123 /* Static functions defined and used in this file. */
124 static void close_pipes __P((int, int));
125 static void do_piping __P((int, int));
126 static void bind_lastarg __P((char *));
127 static int shell_control_structure __P((enum command_type));
128 static void cleanup_redirects __P((REDIRECT *));
130 #if defined (JOB_CONTROL)
131 static int restore_signal_mask __P((sigset_t *));
134 static void async_redirect_stdin __P((void));
136 static int builtin_status __P((int));
138 static int execute_for_command __P((FOR_COM *));
139 #if defined (SELECT_COMMAND)
140 static int displen __P((const char *));
141 static int print_index_and_element __P((int, int, WORD_LIST *));
142 static void indent __P((int, int));
143 static void print_select_list __P((WORD_LIST *, int, int, int));
144 static char *select_query __P((WORD_LIST *, int, char *, int));
145 static int execute_select_command __P((SELECT_COM *));
147 #if defined (DPAREN_ARITHMETIC)
148 static int execute_arith_command __P((ARITH_COM *));
150 #if defined (COND_COMMAND)
151 static int execute_cond_node __P((COND_COM *));
152 static int execute_cond_command __P((COND_COM *));
154 #if defined (COMMAND_TIMING)
155 static int mkfmt __P((char *, int, int, time_t, int));
156 static void print_formatted_time __P((FILE *, char *,
157 time_t, int, time_t, int,
159 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
161 #if defined (ARITH_FOR_COMMAND)
162 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
163 static int execute_arith_for_command __P((ARITH_FOR_COM *));
165 static int execute_case_command __P((CASE_COM *));
166 static int execute_while_command __P((WHILE_COM *));
167 static int execute_until_command __P((WHILE_COM *));
168 static int execute_while_or_until __P((WHILE_COM *, int));
169 static int execute_if_command __P((IF_COM *));
170 static int execute_null_command __P((REDIRECT *, int, int, int));
171 static void fix_assignment_words __P((WORD_LIST *));
172 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
173 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
174 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
175 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
177 REDIRECT *, struct fd_bitmap *, int));
178 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
184 static int execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
185 int, int, int, struct fd_bitmap *, int));
187 static char *getinterp __P((char *, int, int *));
188 static void initialize_subshell __P((void));
189 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
190 #if defined (COPROCESS_SUPPORT)
191 static int execute_coproc __P((COMMAND *, int, int, struct fd_bitmap *));
194 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
196 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
198 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
200 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
201 so that reader_loop can set it to zero before executing a command. */
204 /* The name of the command that is currently being executed.
205 `test' needs this, for example. */
206 char *this_command_name;
208 /* The printed representation of the currently-executing command (same as
209 the_printed_command), except when a trap is being executed. Useful for
210 a debugger to know where exactly the program is currently executing. */
211 char *the_printed_command_except_trap;
213 /* For catching RETURN in a function. */
214 int return_catch_flag;
215 int return_catch_value;
216 procenv_t return_catch;
218 /* The value returned by the last synchronous command. */
219 int last_command_exit_value;
221 /* Whether or not the last command (corresponding to last_command_exit_value)
222 was terminated by a signal, and, if so, which one. */
223 int last_command_exit_signal;
225 /* The list of redirections to perform which will undo the redirections
226 that I made in the shell. */
227 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
229 /* The list of redirections to perform which will undo the internal
230 redirections performed by the `exec' builtin. These are redirections
231 that must be undone even when exec discards redirection_undo_list. */
232 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
234 /* When greater than zero, value is the `level' of builtins we are
235 currently executing (e.g. `eval echo a' would have it set to 2). */
236 int executing_builtin = 0;
238 /* Non-zero if we are executing a command list (a;b;c, etc.) */
239 int executing_list = 0;
241 /* Non-zero if failing commands in a command substitution should not exit the
242 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
243 commands run in command substitutions by parse_and_execute. */
244 int comsub_ignore_return = 0;
246 /* Non-zero if we have just forked and are currently running in a subshell
248 int subshell_environment;
250 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
251 int subshell_level = 0;
253 /* Currently-executing shell function. */
254 SHELL_VAR *this_shell_function;
256 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
257 int match_ignore_case = 0;
259 int executing_command_builtin = 0;
261 struct stat SB; /* used for debugging */
263 static int special_builtin_failed;
265 static COMMAND *currently_executing_command;
267 /* The line number that the currently executing function starts on. */
268 static int function_line_number;
270 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
271 number containing the function name. Used by executing_line_number to
272 report the correct line number. Kind of a hack. */
273 static int showing_function_line;
275 static int line_number_for_err_trap;
277 /* A sort of function nesting level counter */
279 int funcnest_max = 0; /* XXX - bash-4.2 */
281 int lastpipe_opt = 0;
283 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
285 #define FD_BITMAP_DEFAULT_SIZE 32
287 /* Functions to allocate and deallocate the structures used to pass
288 information from the shell to its children about file descriptors
294 struct fd_bitmap *ret;
296 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
302 ret->bitmap = (char *)xmalloc (size);
303 memset (ret->bitmap, '\0', size);
306 ret->bitmap = (char *)NULL;
311 dispose_fd_bitmap (fdbp)
312 struct fd_bitmap *fdbp;
319 close_fd_bitmap (fdbp)
320 struct fd_bitmap *fdbp;
326 for (i = 0; i < fdbp->size; i++)
335 /* Return the line number of the currently executing command. */
337 executing_line_number ()
339 if (executing && showing_function_line == 0 &&
340 (variable_context == 0 || interactive_shell == 0) &&
341 currently_executing_command)
343 #if defined (COND_COMMAND)
344 if (currently_executing_command->type == cm_cond)
345 return currently_executing_command->value.Cond->line;
347 #if defined (DPAREN_ARITHMETIC)
348 else if (currently_executing_command->type == cm_arith)
349 return currently_executing_command->value.Arith->line;
351 #if defined (ARITH_FOR_COMMAND)
352 else if (currently_executing_command->type == cm_arith_for)
353 return currently_executing_command->value.ArithFor->line;
362 /* Execute the command passed in COMMAND. COMMAND is exactly what
363 read_command () places into GLOBAL_COMMAND. See "command.h" for the
364 details of the command structure.
366 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
367 return values. Executing a command with nothing in it returns
368 EXECUTION_SUCCESS. */
370 execute_command (command)
373 struct fd_bitmap *bitmap;
376 current_fds_to_close = (struct fd_bitmap *)NULL;
377 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
378 begin_unwind_frame ("execute-command");
379 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
381 /* Just do the command, but not asynchronously. */
382 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
384 dispose_fd_bitmap (bitmap);
385 discard_unwind_frame ("execute-command");
387 #if defined (PROCESS_SUBSTITUTION)
388 /* don't unlink fifos if we're in a shell function; wait until the function
390 if (variable_context == 0)
392 #endif /* PROCESS_SUBSTITUTION */
398 /* Return 1 if TYPE is a shell control structure type. */
400 shell_control_structure (type)
401 enum command_type type;
405 #if defined (ARITH_FOR_COMMAND)
408 #if defined (SELECT_COMMAND)
411 #if defined (DPAREN_ARITHMETIC)
414 #if defined (COND_COMMAND)
423 case cm_function_def:
431 /* A function to use to unwind_protect the redirection undo list
434 cleanup_redirects (list)
437 do_redirections (list, RX_ACTIVE);
438 dispose_redirects (list);
442 /* Function to unwind_protect the redirections for functions and builtins. */
444 cleanup_func_redirects (list)
447 do_redirections (list, RX_ACTIVE);
452 dispose_exec_redirects ()
454 if (exec_redirection_undo_list)
456 dispose_redirects (exec_redirection_undo_list);
457 exec_redirection_undo_list = (REDIRECT *)NULL;
461 #if defined (JOB_CONTROL)
462 /* A function to restore the signal mask to its proper value when the shell
463 is interrupted or errors occur while creating a pipeline. */
465 restore_signal_mask (set)
468 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
470 #endif /* JOB_CONTROL */
473 /* A debugging function that can be called from gdb, for instance. */
478 int f, fd_table_size;
480 fd_table_size = getdtablesize ();
482 fprintf (stderr, "pid %ld open files:", (long)getpid ());
483 for (i = 3; i < fd_table_size; i++)
485 if ((f = fcntl (i, F_GETFD, 0)) != -1)
486 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
488 fprintf (stderr, "\n");
493 async_redirect_stdin ()
497 fd = open ("/dev/null", O_RDONLY);
504 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
507 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
509 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
510 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
511 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
512 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
513 from and where it goes. They can have the value of NO_PIPE, which means
515 FDS_TO_CLOSE is a list of file descriptors to close once the child has
516 been forked. This list often contains the unusable sides of pipes, etc.
518 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
519 return values. Executing a command with nothing in it returns
520 EXECUTION_SUCCESS. */
522 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
526 int pipe_in, pipe_out;
527 struct fd_bitmap *fds_to_close;
529 int exec_result, user_subshell, invert, ignore_return, was_error_trap;
530 REDIRECT *my_undo_list, *exec_undo_list;
531 volatile int last_pid;
532 volatile int save_line_number;
535 if (command == 0 || breaking || continuing || read_but_dont_execute)
536 return (EXECUTION_SUCCESS);
538 if (breaking || continuing)
539 return (last_command_exit_value);
540 if (command == 0 || read_but_dont_execute)
541 return (EXECUTION_SUCCESS);
545 run_pending_traps ();
548 if (running_trap == 0)
550 currently_executing_command = command;
552 invert = (command->flags & CMD_INVERT_RETURN) != 0;
554 /* If we're inverting the return value and `set -e' has been executed,
555 we don't want a failing command to inadvertently cause the shell
557 if (exit_immediately_on_error && invert) /* XXX */
558 command->flags |= CMD_IGNORE_RETURN; /* XXX */
560 exec_result = EXECUTION_SUCCESS;
562 /* If a command was being explicitly run in a subshell, or if it is
563 a shell control-structure, and it has a pipe, then we do the command
565 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
566 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
568 #if defined (COPROCESS_SUPPORT)
569 if (command->type == cm_coproc)
570 return (execute_coproc (command, pipe_in, pipe_out, fds_to_close));
573 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
575 if (command->type == cm_subshell ||
576 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
577 (shell_control_structure (command->type) &&
578 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
582 /* Fork a subshell, turn off the subshell bit, turn off job
583 control and call execute_command () on the command again. */
584 line_number_for_err_trap = line_number;
585 paren_pid = make_child (savestring (make_command_string (command)),
588 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
592 close_pipes (pipe_in, pipe_out);
594 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
597 /* If we are part of a pipeline, and not the end of the pipeline,
598 then we should simply return and let the last command in the
599 pipe be waited for. If we are not in a pipeline, or are the
600 last command in the pipeline, then we wait for the subshell
601 and return its exit status as usual. */
602 if (pipe_out != NO_PIPE)
603 return (EXECUTION_SUCCESS);
605 stop_pipeline (asynchronous, (COMMAND *)NULL);
607 if (asynchronous == 0)
609 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
610 invert = (command->flags & CMD_INVERT_RETURN) != 0;
611 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
613 exec_result = wait_for (paren_pid);
615 /* If we have to, invert the return value. */
617 exec_result = ((exec_result == EXECUTION_SUCCESS)
619 : EXECUTION_SUCCESS);
621 last_command_exit_value = exec_result;
622 if (user_subshell && was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
624 save_line_number = line_number;
625 line_number = line_number_for_err_trap;
627 line_number = save_line_number;
630 if (user_subshell && ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
632 run_pending_traps ();
633 jump_to_top_level (ERREXIT);
636 return (last_command_exit_value);
640 DESCRIBE_PID (paren_pid);
642 run_pending_traps ();
644 return (EXECUTION_SUCCESS);
649 #if defined (COMMAND_TIMING)
650 if (command->flags & CMD_TIME_PIPELINE)
654 command->flags |= CMD_FORCE_SUBSHELL;
655 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
659 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
661 if (running_trap == 0)
663 currently_executing_command = (COMMAND *)NULL;
665 return (exec_result);
667 #endif /* COMMAND_TIMING */
669 if (shell_control_structure (command->type) && command->redirects)
670 stdin_redir = stdin_redirects (command->redirects);
672 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
674 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
676 cleanup_redirects (redirection_undo_list);
677 redirection_undo_list = (REDIRECT *)NULL;
678 dispose_exec_redirects ();
679 return (last_command_exit_value = EXECUTION_FAILURE);
682 if (redirection_undo_list)
684 /* XXX - why copy here? */
685 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
686 dispose_redirects (redirection_undo_list);
687 redirection_undo_list = (REDIRECT *)NULL;
690 my_undo_list = (REDIRECT *)NULL;
692 if (exec_redirection_undo_list)
694 /* XXX - why copy here? */
695 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
696 dispose_redirects (exec_redirection_undo_list);
697 exec_redirection_undo_list = (REDIRECT *)NULL;
700 exec_undo_list = (REDIRECT *)NULL;
702 if (my_undo_list || exec_undo_list)
703 begin_unwind_frame ("loop_redirections");
706 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
709 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
711 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
715 switch (command->type)
719 save_line_number = line_number;
720 /* We can't rely on variables retaining their values across a
721 call to execute_simple_command if a longjmp occurs as the
722 result of a `return' builtin. This is true for sure with gcc. */
723 #if defined (RECYCLES_PIDS)
724 last_made_pid = NO_PID;
726 last_pid = last_made_pid;
727 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
729 if (ignore_return && command->value.Simple)
730 command->value.Simple->flags |= CMD_IGNORE_RETURN;
731 if (command->flags & CMD_STDIN_REDIR)
732 command->value.Simple->flags |= CMD_STDIN_REDIR;
734 line_number_for_err_trap = line_number = command->value.Simple->line;
736 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
737 asynchronous, fds_to_close);
738 line_number = save_line_number;
740 /* The temporary environment should be used for only the simple
741 command immediately following its definition. */
742 dispose_used_env_vars ();
744 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
745 /* Reclaim memory allocated with alloca () on machines which
746 may be using the alloca emulation code. */
748 #endif /* (ultrix && mips) || C_ALLOCA */
750 /* If we forked to do the command, then we must wait_for ()
753 /* XXX - this is something to watch out for if there are problems
754 when the shell is compiled without job control. */
755 if (already_making_children && pipe_out == NO_PIPE &&
756 last_made_pid != last_pid)
758 stop_pipeline (asynchronous, (COMMAND *)NULL);
762 DESCRIBE_PID (last_made_pid);
765 #if !defined (JOB_CONTROL)
766 /* Do not wait for asynchronous processes started from
768 if (last_made_pid != last_asynchronous_pid)
770 /* When executing a shell function that executes other
771 commands, this causes the last simple command in
772 the function to be waited for twice. This also causes
773 subshells forked to execute builtin commands (e.g., in
774 pipelines) to be waited for twice. */
775 exec_result = wait_for (last_made_pid);
779 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
780 only the failure of a simple command. */
781 if (was_error_trap && ignore_return == 0 && invert == 0 && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)
783 last_command_exit_value = exec_result;
784 line_number = line_number_for_err_trap;
786 line_number = save_line_number;
789 if (ignore_return == 0 && invert == 0 &&
790 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
791 (exit_immediately_on_error && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)))
793 last_command_exit_value = exec_result;
794 run_pending_traps ();
795 jump_to_top_level (ERREXIT);
802 command->value.For->flags |= CMD_IGNORE_RETURN;
803 exec_result = execute_for_command (command->value.For);
806 #if defined (ARITH_FOR_COMMAND)
809 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
810 exec_result = execute_arith_for_command (command->value.ArithFor);
814 #if defined (SELECT_COMMAND)
817 command->value.Select->flags |= CMD_IGNORE_RETURN;
818 exec_result = execute_select_command (command->value.Select);
824 command->value.Case->flags |= CMD_IGNORE_RETURN;
825 exec_result = execute_case_command (command->value.Case);
830 command->value.While->flags |= CMD_IGNORE_RETURN;
831 exec_result = execute_while_command (command->value.While);
836 command->value.While->flags |= CMD_IGNORE_RETURN;
837 exec_result = execute_until_command (command->value.While);
842 command->value.If->flags |= CMD_IGNORE_RETURN;
843 exec_result = execute_if_command (command->value.If);
848 /* This code can be executed from either of two paths: an explicit
849 '{}' command, or via a function call. If we are executed via a
850 function call, we have already taken care of the function being
851 executed in the background (down there in execute_simple_command ()),
852 and this command should *not* be marked as asynchronous. If we
853 are executing a regular '{}' group command, and asynchronous == 1,
854 we must want to execute the whole command in the background, so we
855 need a subshell, and we want the stuff executed in that subshell
856 (this group command) to be executed in the foreground of that
857 subshell (i.e. there will not be *another* subshell forked).
859 What we do is to force a subshell if asynchronous, and then call
860 execute_command_internal again with asynchronous still set to 1,
861 but with the original group command, so the printed command will
864 The code above that handles forking off subshells will note that
865 both subshell and async are on, and turn off async in the child
866 after forking the subshell (but leave async set in the parent, so
867 the normal call to describe_pid is made). This turning off
868 async is *crucial*; if it is not done, this will fall into an
869 infinite loop of executions through this spot in subshell after
870 subshell until the process limit is exhausted. */
874 command->flags |= CMD_FORCE_SUBSHELL;
876 execute_command_internal (command, 1, pipe_in, pipe_out,
881 if (ignore_return && command->value.Group->command)
882 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
884 execute_command_internal (command->value.Group->command,
885 asynchronous, pipe_in, pipe_out,
891 exec_result = execute_connection (command, asynchronous,
892 pipe_in, pipe_out, fds_to_close);
895 #if defined (DPAREN_ARITHMETIC)
897 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
899 command->value.Arith->flags |= CMD_IGNORE_RETURN;
900 line_number_for_err_trap = save_line_number = line_number;
901 exec_result = execute_arith_command (command->value.Arith);
902 line_number = save_line_number;
904 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
906 last_command_exit_value = exec_result;
907 save_line_number = line_number;
908 line_number = line_number_for_err_trap;
910 line_number = save_line_number;
913 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
915 last_command_exit_value = exec_result;
916 run_pending_traps ();
917 jump_to_top_level (ERREXIT);
923 #if defined (COND_COMMAND)
925 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
927 command->value.Cond->flags |= CMD_IGNORE_RETURN;
929 line_number_for_err_trap = save_line_number = line_number;
930 exec_result = execute_cond_command (command->value.Cond);
931 line_number = save_line_number;
933 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
935 last_command_exit_value = exec_result;
936 save_line_number = line_number;
937 line_number = line_number_for_err_trap;
939 line_number = save_line_number;
942 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
944 last_command_exit_value = exec_result;
945 run_pending_traps ();
946 jump_to_top_level (ERREXIT);
952 case cm_function_def:
953 exec_result = execute_intern_function (command->value.Function_def->name,
954 command->value.Function_def->command);
958 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
963 do_redirections (my_undo_list, RX_ACTIVE);
964 dispose_redirects (my_undo_list);
968 dispose_redirects (exec_undo_list);
970 if (my_undo_list || exec_undo_list)
971 discard_unwind_frame ("loop_redirections");
973 /* Invert the return value if we have to */
975 exec_result = (exec_result == EXECUTION_SUCCESS)
979 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
980 /* This is where we set PIPESTATUS from the exit status of the appropriate
981 compound commands (the ones that look enough like simple commands to
982 cause confusion). We might be able to optimize by not doing this if
983 subshell_environment != 0. */
984 switch (command->type)
986 # if defined (DPAREN_ARITHMETIC)
989 # if defined (COND_COMMAND)
992 set_pipestatus_from_exit (exec_result);
997 last_command_exit_value = exec_result;
998 run_pending_traps ();
1000 if (running_trap == 0)
1002 currently_executing_command = (COMMAND *)NULL;
1003 return (last_command_exit_value);
1006 #if defined (COMMAND_TIMING)
1008 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1009 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
1010 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
1011 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
1014 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1015 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1017 static const int precs[] = { 0, 100, 10, 1 };
1019 /* Expand one `%'-prefixed escape sequence from a time format string. */
1021 mkfmt (buf, prec, lng, sec, sec_fraction)
1028 char abuf[INT_STRLEN_BOUND(time_t) + 1];
1032 abuf[sizeof(abuf) - 1] = '\0';
1034 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1039 aind = sizeof(abuf) - 2;
1041 abuf[aind--] = (min % 10) + '0';
1045 buf[ind++] = abuf[aind++];
1049 /* Now add the seconds. */
1050 aind = sizeof (abuf) - 2;
1052 abuf[aind--] = (sec % 10) + '0';
1056 buf[ind++] = abuf[aind++];
1058 /* We want to add a decimal point and PREC places after it if PREC is
1059 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1064 for (aind = 1; aind <= prec; aind++)
1066 buf[ind++] = (sec_fraction / precs[aind]) + '0';
1067 sec_fraction %= precs[aind];
1078 /* Interpret the format string FORMAT, interpolating the following escape
1082 where the optional `prec' is a precision, meaning the number of
1083 characters after the decimal point, the optional `l' means to format
1084 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1085 and the last character is one of
1087 R number of seconds of `real' time
1088 U number of seconds of `user' time
1089 S number of seconds of `system' time
1091 An occurrence of `%%' in the format string is translated to a `%'. The
1092 result is printed to FP, a pointer to a FILE. The other variables are
1093 the seconds and thousandths of a second of real, user, and system time,
1096 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1107 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1112 len = strlen (format);
1113 ssize = (len + 64) - (len % 64);
1114 str = (char *)xmalloc (ssize);
1117 for (s = format; *s; s++)
1119 if (*s != '%' || s[1] == '\0')
1121 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1124 else if (s[1] == '%')
1127 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1130 else if (s[1] == 'P')
1134 /* clamp CPU usage at 100% */
1139 sum_frac = (cpu % 100) * 10;
1140 len = mkfmt (ts, 2, 0, sum, sum_frac);
1141 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1142 strcpy (str + sindex, ts);
1147 prec = 3; /* default is three places past the decimal point. */
1148 lng = 0; /* default is to not use minutes or append `s' */
1150 if (DIGIT (*s)) /* `precision' */
1153 if (prec > 3) prec = 3;
1155 if (*s == 'l') /* `length extender' */
1160 if (*s == 'R' || *s == 'E')
1161 len = mkfmt (ts, prec, lng, rs, rsf);
1163 len = mkfmt (ts, prec, lng, us, usf);
1165 len = mkfmt (ts, prec, lng, ss, ssf);
1168 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1172 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1173 strcpy (str + sindex, ts);
1179 fprintf (fp, "%s\n", str);
1186 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1188 int asynchronous, pipe_in, pipe_out;
1189 struct fd_bitmap *fds_to_close;
1191 int rv, posix_time, old_flags, nullcmd;
1197 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1198 struct timeval real, user, sys;
1199 struct timeval before, after;
1200 # if defined (HAVE_STRUCT_TIMEZONE)
1201 struct timezone dtz; /* posix doesn't define this */
1203 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1205 # if defined (HAVE_TIMES)
1206 clock_t tbefore, tafter, real, user, sys;
1207 struct tms before, after;
1211 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1212 # if defined (HAVE_STRUCT_TIMEZONE)
1213 gettimeofday (&before, &dtz);
1215 gettimeofday (&before, (void *)NULL);
1216 # endif /* !HAVE_STRUCT_TIMEZONE */
1217 getrusage (RUSAGE_SELF, &selfb);
1218 getrusage (RUSAGE_CHILDREN, &kidsb);
1220 # if defined (HAVE_TIMES)
1221 tbefore = times (&before);
1225 posix_time = (command->flags & CMD_TIME_POSIX);
1227 nullcmd = (command == 0) || (command->type == cm_simple && command->value.Simple->words == 0 && command->value.Simple->redirects == 0);
1228 if (posixly_correct && nullcmd)
1230 #if defined (HAVE_GETRUSAGE)
1231 selfb.ru_utime.tv_sec = kidsb.ru_utime.tv_sec = selfb.ru_stime.tv_sec = kidsb.ru_stime.tv_sec = 0;
1232 selfb.ru_utime.tv_usec = kidsb.ru_utime.tv_usec = selfb.ru_stime.tv_usec = kidsb.ru_stime.tv_usec = 0;
1233 before.tv_sec = shell_start_time;
1236 before.tms_utime = before.tms_stime = before.tms_cutime = before.tms_cstime = 0;
1237 tbefore = shell_start_time;
1241 old_flags = command->flags;
1242 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1243 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1244 command->flags = old_flags;
1247 rsf = usf = ssf = cpu = 0;
1249 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1250 # if defined (HAVE_STRUCT_TIMEZONE)
1251 gettimeofday (&after, &dtz);
1253 gettimeofday (&after, (void *)NULL);
1254 # endif /* !HAVE_STRUCT_TIMEZONE */
1255 getrusage (RUSAGE_SELF, &selfa);
1256 getrusage (RUSAGE_CHILDREN, &kidsa);
1258 difftimeval (&real, &before, &after);
1259 timeval_to_secs (&real, &rs, &rsf);
1261 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1262 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1263 timeval_to_secs (&user, &us, &usf);
1265 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1266 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1267 timeval_to_secs (&sys, &ss, &ssf);
1269 cpu = timeval_to_cpu (&real, &user, &sys);
1271 # if defined (HAVE_TIMES)
1272 tafter = times (&after);
1274 real = tafter - tbefore;
1275 clock_t_to_secs (real, &rs, &rsf);
1277 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1278 clock_t_to_secs (user, &us, &usf);
1280 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1281 clock_t_to_secs (sys, &ss, &ssf);
1283 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1287 rsf = usf = ssf = cpu = 0;
1292 time_format = POSIX_TIMEFORMAT;
1293 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1295 if (posixly_correct && nullcmd)
1296 time_format = "user\t%2lU\nsys\t%2lS";
1298 time_format = BASH_TIMEFORMAT;
1300 if (time_format && *time_format)
1301 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1305 #endif /* COMMAND_TIMING */
1307 /* Execute a command that's supposed to be in a subshell. This must be
1308 called after make_child and we must be running in the child process.
1309 The caller will return or exit() immediately with the value this returns. */
1311 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1314 int pipe_in, pipe_out;
1315 struct fd_bitmap *fds_to_close;
1317 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1318 int ois, user_coproc;
1320 volatile COMMAND *tcom;
1322 USE_VAR(user_subshell);
1323 USE_VAR(user_coproc);
1326 USE_VAR(asynchronous);
1329 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1330 pipe_in == NO_PIPE &&
1331 stdin_redirects (command->redirects) == 0);
1333 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1334 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1335 user_coproc = command->type == cm_coproc;
1337 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1339 /* If a command is asynchronous in a subshell (like ( foo ) & or
1340 the special case of an asynchronous GROUP command where the
1341 the subshell bit is turned on down in case cm_group: below),
1342 turn off `asynchronous', so that two subshells aren't spawned.
1343 XXX - asynchronous used to be set to 0 in this block, but that
1344 means that setup_async_signals was never run. Now it's set to
1345 0 after subshell_environment is set appropriately and setup_async_signals
1348 This seems semantically correct to me. For example,
1349 ( foo ) & seems to say ``do the command `foo' in a subshell
1350 environment, but don't wait for that subshell to finish'',
1351 and "{ foo ; bar ; } &" seems to me to be like functions or
1352 builtins in the background, which executed in a subshell
1353 environment. I just don't see the need to fork two subshells. */
1355 /* Don't fork again, we are already in a subshell. A `doubly
1356 async' shell is not interactive, however. */
1359 #if defined (JOB_CONTROL)
1360 /* If a construct like ( exec xxx yyy ) & is given while job
1361 control is active, we want to prevent exec from putting the
1362 subshell back into the original process group, carefully
1363 undoing all the work we just did in make_child. */
1365 #endif /* JOB_CONTROL */
1366 ois = interactive_shell;
1367 interactive_shell = 0;
1368 /* This test is to prevent alias expansion by interactive shells that
1369 run `(command) &' but to allow scripts that have enabled alias
1370 expansion with `shopt -s expand_alias' to continue to expand
1372 if (ois != interactive_shell)
1376 /* Subshells are neither login nor interactive. */
1377 login_shell = interactive = 0;
1380 subshell_environment = SUBSHELL_PAREN;
1383 subshell_environment = 0; /* XXX */
1385 subshell_environment |= SUBSHELL_ASYNC;
1386 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1387 subshell_environment |= SUBSHELL_PIPE;
1389 subshell_environment |= SUBSHELL_COPROC;
1392 reset_terminating_signals (); /* in sig.c */
1393 /* Cancel traps, in trap.c. */
1394 /* Reset the signal handlers in the child, but don't free the
1395 trap strings. Set a flag noting that we have to free the
1396 trap strings if we run trap to change a signal disposition. */
1397 reset_signal_handlers ();
1398 subshell_environment |= SUBSHELL_RESETTRAP;
1400 /* Make sure restore_original_signals doesn't undo the work done by
1401 make_child to ensure that asynchronous children are immune to SIGINT
1402 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1406 setup_async_signals ();
1410 #if defined (JOB_CONTROL)
1411 set_sigchld_handler ();
1412 #endif /* JOB_CONTROL */
1414 set_sigint_handler ();
1416 #if defined (JOB_CONTROL)
1417 /* Delete all traces that there were any jobs running. This is
1418 only for subshells. */
1419 without_job_control ();
1420 #endif /* JOB_CONTROL */
1423 close_fd_bitmap (fds_to_close);
1425 do_piping (pipe_in, pipe_out);
1427 #if defined (COPROCESS_SUPPORT)
1431 /* If this is a user subshell, set a flag if stdin was redirected.
1432 This is used later to decide whether to redirect fd 0 to
1433 /dev/null for async commands in the subshell. This adds more
1434 sh compatibility, but I'm not sure it's the right thing to do. */
1437 stdin_redir = stdin_redirects (command->redirects);
1438 restore_default_signal (0);
1441 /* If this is an asynchronous command (command &), we want to
1442 redirect the standard input from /dev/null in the absence of
1443 any specific redirection involving stdin. */
1444 if (should_redir_stdin && stdin_redir == 0)
1445 async_redirect_stdin ();
1447 /* Do redirections, then dispose of them before recursive call. */
1448 if (command->redirects)
1450 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1451 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1453 dispose_redirects (command->redirects);
1454 command->redirects = (REDIRECT *)NULL;
1457 if (command->type == cm_subshell)
1458 tcom = command->value.Subshell->command;
1459 else if (user_coproc)
1460 tcom = command->value.Coproc->command;
1464 if (command->flags & CMD_TIME_PIPELINE)
1465 tcom->flags |= CMD_TIME_PIPELINE;
1466 if (command->flags & CMD_TIME_POSIX)
1467 tcom->flags |= CMD_TIME_POSIX;
1469 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1470 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1471 tcom->flags |= CMD_IGNORE_RETURN;
1473 /* If this is a simple command, tell execute_disk_command that it
1474 might be able to get away without forking and simply exec.
1475 This means things like ( sleep 10 ) will only cause one fork.
1476 If we're timing the command or inverting its return value, however,
1477 we cannot do this optimization. */
1478 if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1479 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1480 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1482 tcom->flags |= CMD_NO_FORK;
1483 if (tcom->type == cm_simple)
1484 tcom->value.Simple->flags |= CMD_NO_FORK;
1487 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1488 tcom->flags &= ~CMD_INVERT_RETURN;
1490 result = setjmp (top_level);
1492 /* If we're inside a function while executing this subshell, we
1493 need to handle a possible `return'. */
1495 if (return_catch_flag)
1496 function_value = setjmp (return_catch);
1498 /* If we're going to exit the shell, we don't want to invert the return
1500 if (result == EXITPROG)
1501 invert = 0, return_code = last_command_exit_value;
1503 return_code = EXECUTION_FAILURE;
1504 else if (function_value)
1505 return_code = return_catch_value;
1507 return_code = execute_command_internal (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1509 /* If we are asked to, invert the return value. */
1511 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1512 : EXECUTION_SUCCESS;
1514 /* If we were explicitly placed in a subshell with (), we need
1515 to do the `shell cleanup' things, such as running traps[0]. */
1516 if (user_subshell && signal_is_trapped (0))
1518 last_command_exit_value = return_code;
1519 return_code = run_exit_trap ();
1523 return (return_code);
1527 #if defined (COPROCESS_SUPPORT)
1528 #define COPROC_MAX 16
1530 typedef struct cpelement
1532 struct cpelement *next;
1533 struct coproc *coproc;
1537 typedef struct cplist
1539 struct cpelement *head;
1540 struct cpelement *tail;
1545 static struct cpelement *cpe_alloc __P((struct coproc *));
1546 static void cpe_dispose __P((struct cpelement *));
1547 static struct cpelement *cpl_add __P((struct coproc *));
1548 static struct cpelement *cpl_delete __P((pid_t));
1549 static void cpl_reap __P((void));
1550 static void cpl_flush __P((void));
1551 static struct cpelement *cpl_search __P((pid_t));
1552 static struct cpelement *cpl_searchbyname __P((char *));
1553 static void cpl_prune __P((void));
1555 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0, 0, 0 };
1557 cplist_t coproc_list = {0, 0, 0};
1559 /* Functions to manage the list of coprocs */
1561 static struct cpelement *
1565 struct cpelement *cpe;
1567 cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1569 cpe->next = (struct cpelement *)0;
1575 struct cpelement *cpe;
1580 static struct cpelement *
1584 struct cpelement *cpe;
1586 cpe = cpe_alloc (cp);
1588 if (coproc_list.head == 0)
1590 coproc_list.head = coproc_list.tail = cpe;
1591 coproc_list.ncoproc = 0; /* just to make sure */
1595 coproc_list.tail->next = cpe;
1596 coproc_list.tail = cpe;
1598 coproc_list.ncoproc++;
1603 static struct cpelement *
1607 struct cpelement *prev, *p;
1609 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1610 if (p->coproc->c_pid == pid)
1612 prev->next = p->next; /* remove from list */
1617 return 0; /* not found */
1620 itrace("cpl_delete: deleting %d", pid);
1623 /* Housekeeping in the border cases. */
1624 if (p == coproc_list.head)
1625 coproc_list.head = coproc_list.head->next;
1626 else if (p == coproc_list.tail)
1627 coproc_list.tail = prev;
1629 coproc_list.ncoproc--;
1630 if (coproc_list.ncoproc == 0)
1631 coproc_list.head = coproc_list.tail = 0;
1632 else if (coproc_list.ncoproc == 1)
1633 coproc_list.tail = coproc_list.head; /* just to make sure */
1641 struct cpelement *prev, *p;
1643 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1644 if (p->coproc->c_flags & COPROC_DEAD)
1646 prev->next = p->next; /* remove from list */
1648 /* Housekeeping in the border cases. */
1649 if (p == coproc_list.head)
1650 coproc_list.head = coproc_list.head->next;
1651 else if (p == coproc_list.tail)
1652 coproc_list.tail = prev;
1654 coproc_list.ncoproc--;
1655 if (coproc_list.ncoproc == 0)
1656 coproc_list.head = coproc_list.tail = 0;
1657 else if (coproc_list.ncoproc == 1)
1658 coproc_list.tail = coproc_list.head; /* just to make sure */
1661 itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1664 coproc_dispose (p->coproc);
1669 /* Clear out the list of saved statuses */
1673 struct cpelement *cpe, *p;
1675 for (cpe = coproc_list.head; cpe; )
1680 coproc_dispose (p->coproc);
1684 coproc_list.head = coproc_list.tail = 0;
1685 coproc_list.ncoproc = 0;
1688 /* Search for PID in the list of coprocs; return the cpelement struct if
1689 found. If not found, return NULL. */
1690 static struct cpelement *
1694 struct cpelement *cp;
1696 for (cp = coproc_list.head ; cp; cp = cp->next)
1697 if (cp->coproc->c_pid == pid)
1699 return (struct cpelement *)NULL;
1702 /* Search for the coproc named NAME in the list of coprocs; return the
1703 cpelement struct if found. If not found, return NULL. */
1704 static struct cpelement *
1705 cpl_searchbyname (name)
1708 struct cpelement *cp;
1710 for (cp = coproc_list.head ; cp; cp = cp->next)
1711 if (STREQ (cp->coproc->c_name, name))
1713 return (struct cpelement *)NULL;
1720 struct cpelement *cp;
1722 while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1724 cp = coproc_list.head;
1725 coproc_list.head = coproc_list.head->next;
1726 coproc_dispose (cp->coproc);
1728 coproc_list.ncoproc--;
1733 /* These currently use a single global "shell coproc" but are written in a
1734 way to not preclude additional coprocs later (using the list management
1738 getcoprocbypid (pid)
1741 return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1745 getcoprocbyname (name)
1748 return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1757 cp->c_rfd = cp->c_wfd = -1;
1758 cp->c_rsave = cp->c_wsave = -1;
1759 cp->c_flags = cp->c_status = 0;
1763 coproc_alloc (name, pid)
1769 cp = &sh_coproc; /* XXX */
1772 cp->c_name = savestring (name);
1785 coproc_unsetvars (cp);
1791 /* Placeholder for now. */
1795 coproc_dispose (&sh_coproc);
1812 cp->c_rsave = cp->c_wsave = -1;
1818 coproc_close (&sh_coproc);
1827 if (cp && (cp->c_flags & COPROC_DEAD))
1828 coproc_dispose (cp);
1832 coproc_rclose (cp, fd)
1836 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1844 coproc_wclose (cp, fd)
1848 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1856 coproc_checkfd (cp, fd)
1863 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1864 update = cp->c_rfd = -1;
1865 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1866 update = cp->c_wfd = -1;
1868 coproc_setvars (cp);
1875 coproc_checkfd (&sh_coproc, fd);
1879 coproc_fdclose (cp, fd)
1883 coproc_rclose (cp, fd);
1884 coproc_wclose (cp, fd);
1885 coproc_setvars (cp);
1892 cp->c_rsave = cp->c_rfd;
1893 cp->c_wsave = cp->c_wfd;
1897 coproc_fdrestore (cp)
1900 cp->c_rfd = cp->c_rsave;
1901 cp->c_wfd = cp->c_wsave;
1905 coproc_pidchk (pid, status)
1910 cp = getcoprocbypid (pid);
1913 itrace("coproc_pidchk: pid %d has died", pid);
1917 cp->c_status = status;
1918 cp->c_flags |= COPROC_DEAD;
1919 cp->c_flags &= ~COPROC_RUNNING;
1921 coproc_dispose (cp);
1933 #if defined (ARRAY_VARS)
1937 if (cp->c_name == 0)
1940 l = strlen (cp->c_name);
1941 namevar = xmalloc (l + 16);
1943 #if defined (ARRAY_VARS)
1944 v = find_variable (cp->c_name);
1946 v = make_new_array_variable (cp->c_name);
1947 if (array_p (v) == 0)
1948 v = convert_var_to_array (v);
1950 t = itos (cp->c_rfd);
1952 v = bind_array_variable (cp->c_name, ind, t, 0);
1955 t = itos (cp->c_wfd);
1957 bind_array_variable (cp->c_name, ind, t, 0);
1960 sprintf (namevar, "%s_READ", cp->c_name);
1961 t = itos (cp->c_rfd);
1962 bind_variable (namevar, t, 0);
1964 sprintf (namevar, "%s_WRITE", cp->c_name);
1965 t = itos (cp->c_wfd);
1966 bind_variable (namevar, t, 0);
1970 sprintf (namevar, "%s_PID", cp->c_name);
1971 t = itos (cp->c_pid);
1972 bind_variable (namevar, t, 0);
1979 coproc_unsetvars (cp)
1985 if (cp->c_name == 0)
1988 l = strlen (cp->c_name);
1989 namevar = xmalloc (l + 16);
1991 sprintf (namevar, "%s_PID", cp->c_name);
1992 unbind_variable (namevar);
1994 #if defined (ARRAY_VARS)
1995 unbind_variable (cp->c_name);
1997 sprintf (namevar, "%s_READ", cp->c_name);
1998 unbind_variable (namevar);
1999 sprintf (namevar, "%s_WRITE", cp->c_name);
2000 unbind_variable (namevar);
2007 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
2009 int pipe_in, pipe_out;
2010 struct fd_bitmap *fds_to_close;
2012 int rpipe[2], wpipe[2], estat;
2017 /* XXX -- will require changes to handle multiple coprocs */
2018 if (sh_coproc.c_pid != NO_PID)
2021 internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc.c_pid, sh_coproc.c_name);
2022 return (last_command_exit_value = EXECUTION_FAILURE);
2024 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc.c_pid, sh_coproc.c_name);
2027 coproc_init (&sh_coproc);
2029 command_string_index = 0;
2030 tcmd = make_command_string (command);
2032 sh_openpipe ((int *)&rpipe); /* 0 = parent read, 1 = child write */
2033 sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2035 coproc_pid = make_child (savestring (tcmd), 1);
2036 if (coproc_pid == 0)
2041 estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2052 cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2053 cp->c_rfd = rpipe[0];
2054 cp->c_wfd = wpipe[1];
2056 SET_CLOSE_ON_EXEC (cp->c_rfd);
2057 SET_CLOSE_ON_EXEC (cp->c_wfd);
2059 coproc_setvars (cp);
2062 itrace ("execute_coproc: [%d] %s", coproc_pid, the_printed_command);
2065 close_pipes (pipe_in, pipe_out);
2066 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2067 unlink_fifo_list ();
2069 stop_pipeline (1, (COMMAND *)NULL);
2070 DESCRIBE_PID (coproc_pid);
2071 run_pending_traps ();
2073 return (EXECUTION_SUCCESS);
2085 /* Catch-all cleanup function for lastpipe code for unwind-protects */
2087 lastpipe_cleanup (s)
2090 unfreeze_jobs_list ();
2094 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2096 int asynchronous, pipe_in, pipe_out;
2097 struct fd_bitmap *fds_to_close;
2099 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2100 int lstdin, lastpipe_flag, lastpipe_jid;
2102 struct fd_bitmap *fd_bitmap;
2105 #if defined (JOB_CONTROL)
2107 BLOCK_CHILD (set, oset);
2108 #endif /* JOB_CONTROL */
2110 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2115 while (cmd && cmd->type == cm_connection &&
2116 cmd->value.Connection && cmd->value.Connection->connector == '|')
2118 /* Make a pipeline between the two commands. */
2119 if (pipe (fildes) < 0)
2121 sys_error (_("pipe error"));
2122 #if defined (JOB_CONTROL)
2123 terminate_current_pipeline ();
2124 kill_current_pipeline ();
2125 UNBLOCK_CHILD (oset);
2126 #endif /* JOB_CONTROL */
2127 last_command_exit_value = EXECUTION_FAILURE;
2128 /* The unwind-protects installed below will take care
2129 of closing all of the open file descriptors. */
2130 throw_to_top_level ();
2131 return (EXECUTION_FAILURE); /* XXX */
2134 /* Here is a problem: with the new file close-on-exec
2135 code, the read end of the pipe (fildes[0]) stays open
2136 in the first process, so that process will never get a
2137 SIGPIPE. There is no way to signal the first process
2138 that it should close fildes[0] after forking, so it
2139 remains open. No SIGPIPE is ever sent because there
2140 is still a file descriptor open for reading connected
2141 to the pipe. We take care of that here. This passes
2142 around a bitmap of file descriptors that must be
2143 closed after making a child process in execute_simple_command. */
2145 /* We need fd_bitmap to be at least as big as fildes[0].
2146 If fildes[0] is less than fds_to_close->size, then
2147 use fds_to_close->size. */
2148 new_bitmap_size = (fildes[0] < fds_to_close->size)
2149 ? fds_to_close->size
2152 fd_bitmap = new_fd_bitmap (new_bitmap_size);
2154 /* Now copy the old information into the new bitmap. */
2155 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2157 /* And mark the pipe file descriptors to be closed. */
2158 fd_bitmap->bitmap[fildes[0]] = 1;
2160 /* In case there are pipe or out-of-processes errors, we
2161 want all these file descriptors to be closed when
2162 unwind-protects are run, and the storage used for the
2163 bitmaps freed up. */
2164 begin_unwind_frame ("pipe-file-descriptors");
2165 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2166 add_unwind_protect (close_fd_bitmap, fd_bitmap);
2168 add_unwind_protect (close, prev);
2169 dummyfd = fildes[1];
2170 add_unwind_protect (close, dummyfd);
2172 #if defined (JOB_CONTROL)
2173 add_unwind_protect (restore_signal_mask, &oset);
2174 #endif /* JOB_CONTROL */
2176 if (ignore_return && cmd->value.Connection->first)
2177 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2178 execute_command_internal (cmd->value.Connection->first, asynchronous,
2179 prev, fildes[1], fd_bitmap);
2187 dispose_fd_bitmap (fd_bitmap);
2188 discard_unwind_frame ("pipe-file-descriptors");
2190 cmd = cmd->value.Connection->second;
2193 lastpid = last_made_pid;
2195 /* Now execute the rightmost command in the pipeline. */
2196 if (ignore_return && cmd)
2197 cmd->flags |= CMD_IGNORE_RETURN;
2199 #if defined (JOB_CONTROL)
2201 begin_unwind_frame ("lastpipe-exec");
2203 /* If the `lastpipe' option is set with shopt, and job control is not
2204 enabled, execute the last element of non-async pipelines in the
2205 current shell environment. */
2206 if (lastpipe_opt && job_control == 0 && asynchronous == 0 && pipe_out == NO_PIPE && prev > 0)
2208 lstdin = move_to_high_fd (0, 0, 255);
2211 do_piping (prev, pipe_out);
2213 add_unwind_protect (restore_stdin, lstdin);
2215 freeze_jobs_list ();
2216 lastpipe_jid = stop_pipeline (0, (COMMAND *)NULL); /* XXX */
2217 add_unwind_protect (lastpipe_cleanup, lastpipe_jid);
2220 cmd->flags |= CMD_LASTPIPE;
2223 add_unwind_protect (close, prev);
2226 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2228 #if defined (JOB_CONTROL)
2230 restore_stdin (lstdin);
2236 #if defined (JOB_CONTROL)
2237 UNBLOCK_CHILD (oset);
2244 #if defined (JOB_CONTROL)
2245 append_process (savestring (the_printed_command), dollar_dollar_pid, exec_result, lastpipe_jid);
2247 lstdin = wait_for (lastpid);
2248 #if defined (JOB_CONTROL)
2249 exec_result = job_exit_status (lastpipe_jid);
2251 unfreeze_jobs_list ();
2254 discard_unwind_frame ("lastpipe-exec");
2256 return (exec_result);
2260 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2262 int asynchronous, pipe_in, pipe_out;
2263 struct fd_bitmap *fds_to_close;
2265 COMMAND *tc, *second;
2266 int ignore_return, exec_result, was_error_trap, invert;
2267 volatile int save_line_number;
2269 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2271 switch (command->value.Connection->connector)
2273 /* Do the first command asynchronously. */
2275 tc = command->value.Connection->first;
2277 return (EXECUTION_SUCCESS);
2280 tc->flags |= CMD_IGNORE_RETURN;
2281 tc->flags |= CMD_AMPERSAND;
2283 /* If this shell was compiled without job control support,
2284 if we are currently in a subshell via `( xxx )', or if job
2285 control is not active then the standard input for an
2286 asynchronous command is forced to /dev/null. */
2287 #if defined (JOB_CONTROL)
2288 if ((subshell_environment || !job_control) && !stdin_redir)
2291 #endif /* JOB_CONTROL */
2292 tc->flags |= CMD_STDIN_REDIR;
2294 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2297 if (tc->flags & CMD_STDIN_REDIR)
2298 tc->flags &= ~CMD_STDIN_REDIR;
2300 second = command->value.Connection->second;
2304 second->flags |= CMD_IGNORE_RETURN;
2306 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2311 /* Just call execute command on both sides. */
2315 if (command->value.Connection->first)
2316 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2317 if (command->value.Connection->second)
2318 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2322 execute_command (command->value.Connection->first);
2324 exec_result = execute_command_internal (command->value.Connection->second,
2325 asynchronous, pipe_in, pipe_out,
2331 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2332 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2333 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2335 line_number_for_err_trap = line_number;
2336 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2338 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2340 last_command_exit_value = exec_result;
2341 save_line_number = line_number;
2342 line_number = line_number_for_err_trap;
2344 line_number = save_line_number;
2347 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2349 last_command_exit_value = exec_result;
2350 run_pending_traps ();
2351 jump_to_top_level (ERREXIT);
2360 /* If we have something like `a && b &' or `a || b &', run the
2361 && or || stuff in a subshell. Force a subshell and just call
2362 execute_command_internal again. Leave asynchronous on
2363 so that we get a report from the parent shell about the
2365 command->flags |= CMD_FORCE_SUBSHELL;
2366 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2370 /* Execute the first command. If the result of that is successful
2371 and the connector is AND_AND, or the result is not successful
2372 and the connector is OR_OR, then execute the second command,
2373 otherwise return. */
2376 if (command->value.Connection->first)
2377 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2379 exec_result = execute_command (command->value.Connection->first);
2381 if (((command->value.Connection->connector == AND_AND) &&
2382 (exec_result == EXECUTION_SUCCESS)) ||
2383 ((command->value.Connection->connector == OR_OR) &&
2384 (exec_result != EXECUTION_SUCCESS)))
2386 if (ignore_return && command->value.Connection->second)
2387 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2389 exec_result = execute_command (command->value.Connection->second);
2395 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2396 jump_to_top_level (DISCARD);
2397 exec_result = EXECUTION_FAILURE;
2406 if (!interactive_shell) \
2407 reap_dead_jobs (); \
2411 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2414 execute_for_command (for_command)
2415 FOR_COM *for_command;
2417 register WORD_LIST *releaser, *list;
2420 int retval, save_line_number;
2422 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2425 save_line_number = line_number;
2426 if (check_identifier (for_command->name, 1) == 0)
2428 if (posixly_correct && interactive_shell == 0)
2430 last_command_exit_value = EX_BADUSAGE;
2431 jump_to_top_level (ERREXIT);
2433 return (EXECUTION_FAILURE);
2437 identifier = for_command->name->word;
2439 list = releaser = expand_words_no_vars (for_command->map_list);
2441 begin_unwind_frame ("for");
2442 add_unwind_protect (dispose_words, releaser);
2445 if (lexical_scoping)
2447 old_value = copy_variable (find_variable (identifier));
2449 add_unwind_protect (dispose_variable, old_value);
2453 if (for_command->flags & CMD_IGNORE_RETURN)
2454 for_command->action->flags |= CMD_IGNORE_RETURN;
2456 for (retval = EXECUTION_SUCCESS; list; list = list->next)
2460 line_number = for_command->line;
2462 /* Remember what this command looks like, for debugger. */
2463 command_string_index = 0;
2464 print_for_command_head (for_command);
2466 if (echo_command_at_execute)
2467 xtrace_print_for_command_head (for_command);
2469 /* Save this command unless it's a trap command and we're not running
2472 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2474 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2477 FREE (the_printed_command_except_trap);
2478 the_printed_command_except_trap = savestring (the_printed_command);
2481 retval = run_debug_trap ();
2482 #if defined (DEBUGGER)
2483 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2484 skip the command. */
2485 if (debugging_mode && retval != EXECUTION_SUCCESS)
2489 this_command_name = (char *)NULL;
2490 v = bind_variable (identifier, list->word->word, 0);
2491 if (readonly_p (v) || noassign_p (v))
2493 line_number = save_line_number;
2494 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2496 last_command_exit_value = EXECUTION_FAILURE;
2497 jump_to_top_level (FORCE_EOF);
2501 dispose_words (releaser);
2502 discard_unwind_frame ("for");
2504 return (EXECUTION_FAILURE);
2507 retval = execute_command (for_command->action);
2526 line_number = save_line_number;
2529 if (lexical_scoping)
2532 unbind_variable (identifier);
2535 SHELL_VAR *new_value;
2537 new_value = bind_variable (identifier, value_cell(old_value), 0);
2538 new_value->attributes = old_value->attributes;
2539 dispose_variable (old_value);
2544 dispose_words (releaser);
2545 discard_unwind_frame ("for");
2549 #if defined (ARITH_FOR_COMMAND)
2550 /* Execute an arithmetic for command. The syntax is
2552 for (( init ; step ; test ))
2557 The execution should be exactly equivalent to
2560 while eval \(\( test \)\) ; do
2566 eval_arith_for_expr (l, okp)
2574 new = expand_words_no_vars (l);
2577 if (echo_command_at_execute)
2578 xtrace_print_arith_cmd (new);
2579 this_command_name = "(("; /* )) for expression error messages */
2581 command_string_index = 0;
2582 print_arith_command (new);
2583 if (signal_in_progress (DEBUG_TRAP) == 0)
2585 FREE (the_printed_command_except_trap);
2586 the_printed_command_except_trap = savestring (the_printed_command);
2589 r = run_debug_trap ();
2590 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2591 skip the command. */
2592 #if defined (DEBUGGER)
2593 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
2594 expresult = evalexp (new->word->word, okp);
2602 expresult = evalexp (new->word->word, okp);
2604 dispose_words (new);
2616 execute_arith_for_command (arith_for_command)
2617 ARITH_FOR_COM *arith_for_command;
2620 int expok, body_status, arith_lineno, save_lineno;
2622 body_status = EXECUTION_SUCCESS;
2624 save_lineno = line_number;
2626 if (arith_for_command->flags & CMD_IGNORE_RETURN)
2627 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
2629 this_command_name = "(("; /* )) for expression error messages */
2631 /* save the starting line number of the command so we can reset
2632 line_number before executing each expression -- for $LINENO
2633 and the DEBUG trap. */
2634 line_number = arith_lineno = arith_for_command->line;
2635 if (variable_context && interactive_shell)
2636 line_number -= function_line_number;
2638 /* Evaluate the initialization expression. */
2639 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
2642 line_number = save_lineno;
2643 return (EXECUTION_FAILURE);
2648 /* Evaluate the test expression. */
2649 line_number = arith_lineno;
2650 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
2651 line_number = save_lineno;
2655 body_status = EXECUTION_FAILURE;
2662 /* Execute the body of the arithmetic for command. */
2664 body_status = execute_command (arith_for_command->action);
2667 /* Handle any `break' or `continue' commands executed by the body. */
2681 /* Evaluate the step expression. */
2682 line_number = arith_lineno;
2683 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
2684 line_number = save_lineno;
2688 body_status = EXECUTION_FAILURE;
2694 line_number = save_lineno;
2696 return (body_status);
2700 #if defined (SELECT_COMMAND)
2701 static int LINES, COLS, tabsize;
2703 #define RP_SPACE ") "
2704 #define RP_SPACE_LEN 2
2706 /* XXX - does not handle numbers > 1000000 at all. */
2707 #define NUMBER_LEN(s) \
2711 : ((s < 10000) ? 4 \
2712 : ((s < 100000) ? 5 \
2719 #if defined (HANDLE_MULTIBYTE)
2724 slen = mbstowcs (wcstr, s, 0);
2727 wcstr = (wchar_t *)xmalloc (sizeof (wchar_t) * (slen + 1));
2728 mbstowcs (wcstr, s, slen + 1);
2729 wclen = wcswidth (wcstr, slen);
2731 return ((int)wclen);
2733 return (STRLEN (s));
2738 print_index_and_element (len, ind, list)
2742 register WORD_LIST *l;
2747 for (i = ind, l = list; l && --i; l = l->next)
2749 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
2750 return (displen (l->word->word));
2759 if ((to / tabsize) > (from / tabsize))
2761 putc ('\t', stderr);
2762 from += tabsize - from % tabsize;
2773 print_select_list (list, list_len, max_elem_len, indices_len)
2775 int list_len, max_elem_len, indices_len;
2777 int ind, row, elem_len, pos, cols, rows;
2778 int first_column_indices_len, other_indices_len;
2782 putc ('\n', stderr);
2786 cols = max_elem_len ? COLS / max_elem_len : 1;
2789 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
2790 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
2798 first_column_indices_len = NUMBER_LEN (rows);
2799 other_indices_len = indices_len;
2801 for (row = 0; row < rows; row++)
2807 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
2808 elem_len = print_index_and_element (indices_len, ind + 1, list);
2809 elem_len += indices_len + RP_SPACE_LEN;
2811 if (ind >= list_len)
2813 indent (pos + elem_len, pos + max_elem_len);
2814 pos += max_elem_len;
2816 putc ('\n', stderr);
2820 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2821 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2822 If the number is between 1 and LIST_LEN, return that selection. If EOF
2823 is read, return a null string. If a blank line is entered, or an invalid
2824 number is entered, the loop is executed again. */
2826 select_query (list, list_len, prompt, print_menu)
2832 int max_elem_len, indices_len, len;
2835 char *repl_string, *t;
2838 t = get_string_value ("LINES");
2839 LINES = (t && *t) ? atoi (t) : 24;
2841 t = get_string_value ("COLUMNS");
2842 COLS = (t && *t) ? atoi (t) : 80;
2845 t = get_string_value ("TABSIZE");
2846 tabsize = (t && *t) ? atoi (t) : 8;
2854 for (l = list; l; l = l->next)
2856 len = displen (l->word->word);
2857 if (len > max_elem_len)
2860 indices_len = NUMBER_LEN (list_len);
2861 max_elem_len += indices_len + RP_SPACE_LEN + 2;
2866 print_select_list (list, list_len, max_elem_len, indices_len);
2867 fprintf (stderr, "%s", prompt);
2871 if (read_builtin ((WORD_LIST *)NULL) != EXECUTION_SUCCESS)
2874 return ((char *)NULL);
2876 repl_string = get_string_value ("REPLY");
2877 if (*repl_string == 0)
2882 if (legal_number (repl_string, &reply) == 0)
2884 if (reply < 1 || reply > list_len)
2887 for (l = list; l && --reply; l = l->next)
2889 return (l->word->word);
2893 /* Execute a SELECT command. The syntax is:
2894 SELECT word IN list DO command_list DONE
2895 Only `break' or `return' in command_list will terminate
2898 execute_select_command (select_command)
2899 SELECT_COM *select_command;
2901 WORD_LIST *releaser, *list;
2903 char *identifier, *ps3_prompt, *selection;
2904 int retval, list_len, show_menu, save_line_number;
2906 if (check_identifier (select_command->name, 1) == 0)
2907 return (EXECUTION_FAILURE);
2909 save_line_number = line_number;
2910 line_number = select_command->line;
2912 command_string_index = 0;
2913 print_select_command_head (select_command);
2915 if (echo_command_at_execute)
2916 xtrace_print_select_command_head (select_command);
2919 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2921 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2924 FREE (the_printed_command_except_trap);
2925 the_printed_command_except_trap = savestring (the_printed_command);
2928 retval = run_debug_trap ();
2929 #if defined (DEBUGGER)
2930 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2931 skip the command. */
2932 if (debugging_mode && retval != EXECUTION_SUCCESS)
2933 return (EXECUTION_SUCCESS);
2937 identifier = select_command->name->word;
2939 /* command and arithmetic substitution, parameter and variable expansion,
2940 word splitting, pathname expansion, and quote removal. */
2941 list = releaser = expand_words_no_vars (select_command->map_list);
2942 list_len = list_length (list);
2943 if (list == 0 || list_len == 0)
2946 dispose_words (list);
2947 line_number = save_line_number;
2948 return (EXECUTION_SUCCESS);
2951 begin_unwind_frame ("select");
2952 add_unwind_protect (dispose_words, releaser);
2954 if (select_command->flags & CMD_IGNORE_RETURN)
2955 select_command->action->flags |= CMD_IGNORE_RETURN;
2957 retval = EXECUTION_SUCCESS;
2962 line_number = select_command->line;
2963 ps3_prompt = get_string_value ("PS3");
2964 if (ps3_prompt == 0)
2968 selection = select_query (list, list_len, ps3_prompt, show_menu);
2972 /* select_query returns EXECUTION_FAILURE if the read builtin
2973 fails, so we want to return failure in this case. */
2974 retval = EXECUTION_FAILURE;
2978 v = bind_variable (identifier, selection, 0);
2979 if (readonly_p (v) || noassign_p (v))
2981 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2983 last_command_exit_value = EXECUTION_FAILURE;
2984 jump_to_top_level (FORCE_EOF);
2988 dispose_words (releaser);
2989 discard_unwind_frame ("select");
2991 line_number = save_line_number;
2992 return (EXECUTION_FAILURE);
2996 retval = execute_command (select_command->action);
3014 #if defined (KSH_COMPATIBLE_SELECT)
3016 selection = get_string_value ("REPLY");
3017 if (selection && *selection == '\0')
3023 line_number = save_line_number;
3025 dispose_words (releaser);
3026 discard_unwind_frame ("select");
3029 #endif /* SELECT_COMMAND */
3031 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
3032 The pattern_list is a linked list of pattern clauses; each clause contains
3033 some patterns to compare word_desc against, and an associated command to
3036 execute_case_command (case_command)
3037 CASE_COM *case_command;
3039 register WORD_LIST *list;
3040 WORD_LIST *wlist, *es;
3041 PATTERN_LIST *clauses;
3042 char *word, *pattern;
3043 int retval, match, ignore_return, save_line_number;
3045 save_line_number = line_number;
3046 line_number = case_command->line;
3048 command_string_index = 0;
3049 print_case_command_head (case_command);
3051 if (echo_command_at_execute)
3052 xtrace_print_case_command_head (case_command);
3055 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3057 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3060 FREE (the_printed_command_except_trap);
3061 the_printed_command_except_trap = savestring (the_printed_command);
3064 retval = run_debug_trap();
3065 #if defined (DEBUGGER)
3066 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3067 skip the command. */
3068 if (debugging_mode && retval != EXECUTION_SUCCESS)
3070 line_number = save_line_number;
3071 return (EXECUTION_SUCCESS);
3075 wlist = expand_word_unsplit (case_command->word, 0);
3076 word = wlist ? string_list (wlist) : savestring ("");
3077 dispose_words (wlist);
3079 retval = EXECUTION_SUCCESS;
3080 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
3082 begin_unwind_frame ("case");
3083 add_unwind_protect ((Function *)xfree, word);
3085 #define EXIT_CASE() goto exit_case_command
3087 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
3090 for (list = clauses->patterns; list; list = list->next)
3092 es = expand_word_leave_quoted (list->word, 0);
3094 if (es && es->word && es->word->word && *(es->word->word))
3095 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
3098 pattern = (char *)xmalloc (1);
3102 /* Since the pattern does not undergo quote removal (as per
3103 Posix.2, section 3.9.4.3), the strmatch () call must be able
3104 to recognize backslashes as escape characters. */
3105 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
3114 if (clauses->action && ignore_return)
3115 clauses->action->flags |= CMD_IGNORE_RETURN;
3116 retval = execute_command (clauses->action);
3118 while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3119 if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3131 discard_unwind_frame ("case");
3132 line_number = save_line_number;
3139 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3140 Repeatedly execute action while executing test produces
3141 EXECUTION_SUCCESS. */
3143 execute_while_command (while_command)
3144 WHILE_COM *while_command;
3146 return (execute_while_or_until (while_command, CMD_WHILE));
3149 /* UNTIL is just like WHILE except that the test result is negated. */
3151 execute_until_command (while_command)
3152 WHILE_COM *while_command;
3154 return (execute_while_or_until (while_command, CMD_UNTIL));
3157 /* The body for both while and until. The only difference between the
3158 two is that the test value is treated differently. TYPE is
3159 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3160 be EXECUTION_SUCCESS if no commands in the body are executed, and
3161 the status of the last command executed in the body otherwise. */
3163 execute_while_or_until (while_command, type)
3164 WHILE_COM *while_command;
3167 int return_value, body_status;
3169 body_status = EXECUTION_SUCCESS;
3172 while_command->test->flags |= CMD_IGNORE_RETURN;
3173 if (while_command->flags & CMD_IGNORE_RETURN)
3174 while_command->action->flags |= CMD_IGNORE_RETURN;
3178 return_value = execute_command (while_command->test);
3181 /* Need to handle `break' in the test when we would break out of the
3182 loop. The job control code will set `breaking' to loop_level
3183 when a job in a loop is stopped with SIGTSTP. If the stopped job
3184 is in the loop test, `breaking' will not be reset unless we do
3185 this, and the shell will cease to execute commands. */
3186 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3192 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3200 body_status = execute_command (while_command->action);
3218 return (body_status);
3221 /* IF test THEN command [ELSE command].
3222 IF also allows ELIF in the place of ELSE IF, but
3223 the parser makes *that* stupidity transparent. */
3225 execute_if_command (if_command)
3228 int return_value, save_line_number;
3230 save_line_number = line_number;
3231 if_command->test->flags |= CMD_IGNORE_RETURN;
3232 return_value = execute_command (if_command->test);
3233 line_number = save_line_number;
3235 if (return_value == EXECUTION_SUCCESS)
3239 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3240 if_command->true_case->flags |= CMD_IGNORE_RETURN;
3242 return (execute_command (if_command->true_case));
3248 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3249 if_command->false_case->flags |= CMD_IGNORE_RETURN;
3251 return (execute_command (if_command->false_case));
3255 #if defined (DPAREN_ARITHMETIC)
3257 execute_arith_command (arith_command)
3258 ARITH_COM *arith_command;
3260 int expok, save_line_number, retval;
3267 save_line_number = line_number;
3268 this_command_name = "(("; /* )) */
3269 line_number = arith_command->line;
3270 /* If we're in a function, update the line number information. */
3271 if (variable_context && interactive_shell)
3272 line_number -= function_line_number;
3274 command_string_index = 0;
3275 print_arith_command (arith_command->exp);
3277 if (signal_in_progress (DEBUG_TRAP) == 0)
3279 FREE (the_printed_command_except_trap);
3280 the_printed_command_except_trap = savestring (the_printed_command);
3283 /* Run the debug trap before each arithmetic command, but do it after we
3284 update the line number information and before we expand the various
3285 words in the expression. */
3286 retval = run_debug_trap ();
3287 #if defined (DEBUGGER)
3288 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3289 skip the command. */
3290 if (debugging_mode && retval != EXECUTION_SUCCESS)
3292 line_number = save_line_number;
3293 return (EXECUTION_SUCCESS);
3297 new = expand_words_no_vars (arith_command->exp);
3299 /* If we're tracing, make a new word list with `((' at the front and `))'
3300 at the back and print it. */
3301 if (echo_command_at_execute)
3302 xtrace_print_arith_cmd (new);
3306 exp = new->next ? string_list (new) : new->word->word;
3307 expresult = evalexp (exp, &expok);
3308 line_number = save_line_number;
3309 if (exp != new->word->word)
3311 dispose_words (new);
3320 return (EXECUTION_FAILURE);
3322 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3324 #endif /* DPAREN_ARITHMETIC */
3326 #if defined (COND_COMMAND)
3328 static char * const nullstr = "";
3331 execute_cond_node (cond)
3334 int result, invert, patmatch, rmatch, mflags, ignore;
3337 invert = (cond->flags & CMD_INVERT_RETURN);
3338 ignore = (cond->flags & CMD_IGNORE_RETURN);
3342 cond->left->flags |= CMD_IGNORE_RETURN;
3344 cond->right->flags |= CMD_IGNORE_RETURN;
3347 if (cond->type == COND_EXPR)
3348 result = execute_cond_node (cond->left);
3349 else if (cond->type == COND_OR)
3351 result = execute_cond_node (cond->left);
3352 if (result != EXECUTION_SUCCESS)
3353 result = execute_cond_node (cond->right);
3355 else if (cond->type == COND_AND)
3357 result = execute_cond_node (cond->left);
3358 if (result == EXECUTION_SUCCESS)
3359 result = execute_cond_node (cond->right);
3361 else if (cond->type == COND_UNARY)
3364 comsub_ignore_return++;
3365 arg1 = cond_expand_word (cond->left->op, 0);
3367 comsub_ignore_return--;
3370 if (echo_command_at_execute)
3371 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3372 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3373 if (arg1 != nullstr)
3376 else if (cond->type == COND_BINARY)
3379 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3380 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
3381 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3382 #if defined (COND_REGEXP)
3383 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3384 cond->op->word[2] == '\0');
3388 comsub_ignore_return++;
3389 arg1 = cond_expand_word (cond->left->op, 0);
3391 comsub_ignore_return--;
3395 comsub_ignore_return++;
3396 arg2 = cond_expand_word (cond->right->op,
3397 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3399 comsub_ignore_return--;
3403 if (echo_command_at_execute)
3404 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3406 #if defined (COND_REGEXP)
3409 mflags = SHMAT_PWARN;
3410 #if defined (ARRAY_VARS)
3411 mflags |= SHMAT_SUBEXP;
3414 result = sh_regmatch (arg1, arg2, mflags);
3417 #endif /* COND_REGEXP */
3422 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3424 : EXECUTION_FAILURE;
3427 if (arg1 != nullstr)
3429 if (arg2 != nullstr)
3434 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3435 jump_to_top_level (DISCARD);
3436 result = EXECUTION_FAILURE;
3440 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3446 execute_cond_command (cond_command)
3447 COND_COM *cond_command;
3449 int retval, save_line_number;
3451 retval = EXECUTION_SUCCESS;
3452 save_line_number = line_number;
3454 this_command_name = "[[";
3455 line_number = cond_command->line;
3456 /* If we're in a function, update the line number information. */
3457 if (variable_context && interactive_shell)
3458 line_number -= function_line_number;
3459 command_string_index = 0;
3460 print_cond_command (cond_command);
3462 if (signal_in_progress (DEBUG_TRAP) == 0)
3464 FREE (the_printed_command_except_trap);
3465 the_printed_command_except_trap = savestring (the_printed_command);
3468 /* Run the debug trap before each conditional command, but do it after we
3469 update the line number information. */
3470 retval = run_debug_trap ();
3471 #if defined (DEBUGGER)
3472 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3473 skip the command. */
3474 if (debugging_mode && retval != EXECUTION_SUCCESS)
3476 line_number = save_line_number;
3477 return (EXECUTION_SUCCESS);
3482 debug_print_cond_command (cond_command);
3485 last_command_exit_value = retval = execute_cond_node (cond_command);
3486 line_number = save_line_number;
3489 #endif /* COND_COMMAND */
3499 var = bind_variable ("_", arg, 0);
3500 VUNSETATTR (var, att_exported);
3503 /* Execute a null command. Fork a subshell if the command uses pipes or is
3504 to be run asynchronously. This handles all the side effects that are
3505 supposed to take place. */
3507 execute_null_command (redirects, pipe_in, pipe_out, async)
3508 REDIRECT *redirects;
3509 int pipe_in, pipe_out, async;
3515 for (forcefork = 0, rd = redirects; rd; rd = rd->next)
3516 forcefork += rd->rflags & REDIR_VARASSIGN;
3518 if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
3520 /* We have a null command, but we really want a subshell to take
3521 care of it. Just fork, do piping and redirections, and exit. */
3522 if (make_child ((char *)NULL, async) == 0)
3524 /* Cancel traps, in trap.c. */
3525 restore_original_signals (); /* XXX */
3527 do_piping (pipe_in, pipe_out);
3529 #if defined (COPROCESS_SUPPORT)
3533 subshell_environment = 0;
3535 subshell_environment |= SUBSHELL_ASYNC;
3536 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3537 subshell_environment |= SUBSHELL_PIPE;
3539 if (do_redirections (redirects, RX_ACTIVE) == 0)
3540 exit (EXECUTION_SUCCESS);
3542 exit (EXECUTION_FAILURE);
3546 close_pipes (pipe_in, pipe_out);
3547 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3548 unlink_fifo_list ();
3550 return (EXECUTION_SUCCESS);
3555 /* Even if there aren't any command names, pretend to do the
3556 redirections that are specified. The user expects the side
3557 effects to take place. If the redirections fail, then return
3558 failure. Otherwise, if a command substitution took place while
3559 expanding the command or a redirection, return the value of that
3560 substitution. Otherwise, return EXECUTION_SUCCESS. */
3562 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
3563 cleanup_redirects (redirection_undo_list);
3564 redirection_undo_list = (REDIRECT *)NULL;
3567 return (EXECUTION_FAILURE);
3568 else if (last_command_subst_pid != NO_PID)
3569 return (last_command_exit_value);
3571 return (EXECUTION_SUCCESS);
3575 /* This is a hack to suppress word splitting for assignment statements
3576 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3578 fix_assignment_words (words)
3591 for (w = words; w; w = w->next)
3592 if (w->word->flags & W_ASSIGNMENT)
3596 b = builtin_address_internal (words->word->word, 0);
3597 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3599 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3600 words->word->flags |= W_ASSNBLTIN;
3602 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
3603 #if defined (ARRAY_VARS)
3605 w->word->flags |= W_ASSIGNASSOC;
3608 #if defined (ARRAY_VARS)
3609 /* Note that we saw an associative array option to a builtin that takes
3610 assignment statements. This is a bit of a kludge. */
3611 else if (w->word->word[0] == '-' && strchr (w->word->word, 'A'))
3615 b = builtin_address_internal (words->word->word, 0);
3616 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3618 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3619 words->word->flags |= W_ASSNBLTIN;
3621 if (words->word->flags & W_ASSNBLTIN)
3627 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3628 to PATHNAME, is a directory. Used by the autocd code below. */
3630 is_dirname (pathname)
3634 temp = search_for_command (pathname);
3635 return (temp ? file_isdir (temp) : file_isdir (pathname));
3638 /* The meaty part of all the executions. We have to start hacking the
3639 real execution of commands here. Fork a process, set things up,
3640 execute the command. */
3642 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
3643 SIMPLE_COM *simple_command;
3644 int pipe_in, pipe_out, async;
3645 struct fd_bitmap *fds_to_close;
3647 WORD_LIST *words, *lastword;
3648 char *command_line, *lastarg, *temp;
3649 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
3650 pid_t old_last_async_pid;
3651 sh_builtin_func_t *builtin;
3653 volatile int old_builtin, old_command_builtin;
3655 result = EXECUTION_SUCCESS;
3656 special_builtin_failed = builtin_is_special = 0;
3657 command_line = (char *)0;
3659 /* If we're in a function, update the line number information. */
3660 if (variable_context && interactive_shell && sourcelevel == 0)
3661 line_number -= function_line_number;
3663 /* Remember what this command line looks like at invocation. */
3664 command_string_index = 0;
3665 print_simple_command (simple_command);
3668 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3670 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3673 FREE (the_printed_command_except_trap);
3674 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
3677 /* Run the debug trap before each simple command, but do it after we
3678 update the line number information. */
3679 result = run_debug_trap ();
3680 #if defined (DEBUGGER)
3681 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3682 skip the command. */
3683 if (debugging_mode && result != EXECUTION_SUCCESS)
3684 return (EXECUTION_SUCCESS);
3688 simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
3690 last_command_subst_pid = NO_PID;
3691 old_last_async_pid = last_asynchronous_pid;
3693 already_forked = dofork = 0;
3695 /* If we're in a pipeline or run in the background, set DOFORK so we
3696 make the child early, before word expansion. This keeps assignment
3697 statements from affecting the parent shell's environment when they
3699 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
3701 /* Something like `%2 &' should restart job 2 in the background, not cause
3702 the shell to fork here. */
3703 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
3704 simple_command->words && simple_command->words->word &&
3705 simple_command->words->word->word &&
3706 (simple_command->words->word->word[0] == '%'))
3711 /* Do this now, because execute_disk_command will do it anyway in the
3712 vast majority of cases. */
3713 maybe_make_export_env ();
3715 /* Don't let a DEBUG trap overwrite the command string to be saved with
3716 the process/job associated with this child. */
3717 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
3720 simple_command->flags |= CMD_NO_FORK;
3722 subshell_environment = SUBSHELL_FORK;
3723 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3724 subshell_environment |= SUBSHELL_PIPE;
3726 subshell_environment |= SUBSHELL_ASYNC;
3728 /* We need to do this before piping to handle some really
3729 pathological cases where one of the pipe file descriptors
3732 close_fd_bitmap (fds_to_close);
3734 do_piping (pipe_in, pipe_out);
3735 pipe_in = pipe_out = NO_PIPE;
3736 #if defined (COPROCESS_SUPPORT)
3740 last_asynchronous_pid = old_last_async_pid;
3744 /* Don't let simple commands that aren't the last command in a
3745 pipeline change $? for the rest of the pipeline (or at all). */
3746 if (pipe_out != NO_PIPE)
3747 result = last_command_exit_value;
3748 close_pipes (pipe_in, pipe_out);
3749 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3750 unlink_fifo_list ();
3752 command_line = (char *)NULL; /* don't free this. */
3753 bind_lastarg ((char *)NULL);
3758 /* If we are re-running this as the result of executing the `command'
3759 builtin, do not expand the command words a second time. */
3760 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
3762 current_fds_to_close = fds_to_close;
3763 fix_assignment_words (simple_command->words);
3764 /* Pass the ignore return flag down to command substitutions */
3765 if (simple_command->flags & CMD_IGNORE_RETURN) /* XXX */
3766 comsub_ignore_return++;
3767 words = expand_words (simple_command->words);
3768 if (simple_command->flags & CMD_IGNORE_RETURN)
3769 comsub_ignore_return--;
3770 current_fds_to_close = (struct fd_bitmap *)NULL;
3773 words = copy_word_list (simple_command->words);
3775 /* It is possible for WORDS not to have anything left in it.
3776 Perhaps all the words consisted of `$foo', and there was
3777 no variable `$foo'. */
3780 this_command_name = 0;
3781 result = execute_null_command (simple_command->redirects,
3783 already_forked ? 0 : async);
3788 bind_lastarg ((char *)NULL);
3789 set_pipestatus_from_exit (result);
3794 lastarg = (char *)NULL;
3796 begin_unwind_frame ("simple-command");
3798 if (echo_command_at_execute)
3799 xtrace_print_word_list (words, 1);
3801 builtin = (sh_builtin_func_t *)NULL;
3802 func = (SHELL_VAR *)NULL;
3803 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
3805 /* Posix.2 says special builtins are found before functions. We
3806 don't set builtin_is_special anywhere other than here, because
3807 this path is followed only when the `command' builtin is *not*
3808 being used, and we don't want to exit the shell if a special
3809 builtin executed with `command builtin' fails. `command' is not
3810 a special builtin. */
3811 if (posixly_correct)
3813 builtin = find_special_builtin (words->word->word);
3815 builtin_is_special = 1;
3818 func = find_function (words->word->word);
3821 /* In POSIX mode, assignment errors in the temporary environment cause a
3822 non-interactive shell to exit. */
3823 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
3825 last_command_exit_value = EXECUTION_FAILURE;
3826 jump_to_top_level (ERREXIT);
3829 add_unwind_protect (dispose_words, words);
3832 /* Bind the last word in this command to "$_" after execution. */
3833 for (lastword = words; lastword->next; lastword = lastword->next)
3835 lastarg = lastword->word->word;
3837 #if defined (JOB_CONTROL)
3838 /* Is this command a job control related thing? */
3839 if (words->word->word[0] == '%' && already_forked == 0)
3841 this_command_name = async ? "bg" : "fg";
3842 last_shell_builtin = this_shell_builtin;
3843 this_shell_builtin = builtin_address (this_command_name);
3844 result = (*this_shell_builtin) (words);
3848 /* One other possiblilty. The user may want to resume an existing job.
3849 If they do, find out whether this word is a candidate for a running
3851 if (job_control && already_forked == 0 && async == 0 &&
3852 !first_word_quoted &&
3854 words->word->word[0] &&
3855 !simple_command->redirects &&
3856 pipe_in == NO_PIPE &&
3857 pipe_out == NO_PIPE &&
3858 (temp = get_string_value ("auto_resume")))
3860 int job, jflags, started_status;
3862 jflags = JM_STOPPED|JM_FIRSTMATCH;
3863 if (STREQ (temp, "exact"))
3865 else if (STREQ (temp, "substring"))
3866 jflags |= JM_SUBSTRING;
3868 jflags |= JM_PREFIX;
3869 job = get_job_by_name (words->word->word, jflags);
3872 run_unwind_frame ("simple-command");
3873 this_command_name = "fg";
3874 last_shell_builtin = this_shell_builtin;
3875 this_shell_builtin = builtin_address ("fg");
3877 started_status = start_job (job, 1);
3878 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
3881 #endif /* JOB_CONTROL */
3884 /* Remember the name of this command globally. */
3885 this_command_name = words->word->word;
3889 /* This command could be a shell builtin or a user-defined function.
3890 We have already found special builtins by this time, so we do not
3891 set builtin_is_special. If this is a function or builtin, and we
3892 have pipes, then fork a subshell in here. Otherwise, just execute
3893 the command directly. */
3894 if (func == 0 && builtin == 0)
3895 builtin = find_shell_builtin (this_command_name);
3897 last_shell_builtin = this_shell_builtin;
3898 this_shell_builtin = builtin;
3900 if (builtin || func)
3904 old_builtin = executing_builtin;
3905 old_command_builtin = executing_command_builtin;
3906 unwind_protect_int (executing_builtin); /* modified in execute_builtin */
3907 unwind_protect_int (executing_command_builtin); /* ditto */
3911 /* reset_terminating_signals (); */ /* XXX */
3912 /* Reset the signal handlers in the child, but don't free the
3913 trap strings. Set a flag noting that we have to free the
3914 trap strings if we run trap to change a signal disposition. */
3915 reset_signal_handlers ();
3916 subshell_environment |= SUBSHELL_RESETTRAP;
3920 if ((simple_command->flags & CMD_STDIN_REDIR) &&
3921 pipe_in == NO_PIPE &&
3922 (stdin_redirects (simple_command->redirects) == 0))
3923 async_redirect_stdin ();
3924 setup_async_signals ();
3928 execute_subshell_builtin_or_function
3929 (words, simple_command->redirects, builtin, func,
3930 pipe_in, pipe_out, async, fds_to_close,
3931 simple_command->flags);
3936 result = execute_builtin_or_function
3937 (words, builtin, func, simple_command->redirects, fds_to_close,
3938 simple_command->flags);
3941 if (result > EX_SHERRBASE)
3943 result = builtin_status (result);
3944 if (builtin_is_special)
3945 special_builtin_failed = 1;
3947 /* In POSIX mode, if there are assignment statements preceding
3948 a special builtin, they persist after the builtin
3950 if (posixly_correct && builtin_is_special && temporary_env)
3951 merge_temporary_env ();
3955 if (result == EX_USAGE)
3956 result = EX_BADUSAGE;
3957 else if (result > EX_SHERRBASE)
3958 result = EXECUTION_FAILURE;
3961 set_pipestatus_from_exit (result);
3967 if (autocd && interactive && words->word && is_dirname (words->word->word))
3969 words = make_word_list (make_word ("cd"), words);
3970 xtrace_print_word_list (words, 0);
3974 if (command_line == 0)
3975 command_line = savestring (the_printed_command_except_trap);
3977 #if defined (PROCESS_SUBSTITUTION)
3978 if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
3979 simple_command->flags &= ~CMD_NO_FORK;
3982 result = execute_disk_command (words, simple_command->redirects, command_line,
3983 pipe_in, pipe_out, async, fds_to_close,
3984 simple_command->flags);
3987 bind_lastarg (lastarg);
3988 FREE (command_line);
3989 dispose_words (words);
3992 executing_builtin = old_builtin;
3993 executing_command_builtin = old_command_builtin;
3995 discard_unwind_frame ("simple-command");
3996 this_command_name = (char *)NULL; /* points to freed memory now */
4000 /* Translate the special builtin exit statuses. We don't really need a
4001 function for this; it's a placeholder for future work. */
4003 builtin_status (result)
4017 r = EXECUTION_FAILURE;
4020 r = EXECUTION_SUCCESS;
4027 execute_builtin (builtin, words, flags, subshell)
4028 sh_builtin_func_t *builtin;
4030 int flags, subshell;
4032 int old_e_flag, result, eval_unwind;
4037 /* XXX -- added 12/11 */
4038 terminate_immediately++;
4042 old_e_flag = exit_immediately_on_error;
4043 /* The eval builtin calls parse_and_execute, which does not know about
4044 the setting of flags, and always calls the execution functions with
4045 flags that will exit the shell on an error if -e is set. If the
4046 eval builtin is being called, and we're supposed to ignore the exit
4047 value of the command, we turn the -e flag off ourselves and disable
4048 the ERR trap, then restore them when the command completes. This is
4049 also a problem (as below) for the command and source/. builtins. */
4050 if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
4051 (builtin == eval_builtin || builtin == command_builtin || builtin == source_builtin))
4053 begin_unwind_frame ("eval_builtin");
4054 unwind_protect_int (exit_immediately_on_error);
4055 error_trap = TRAP_STRING (ERROR_TRAP);
4058 error_trap = savestring (error_trap);
4059 add_unwind_protect (xfree, error_trap);
4060 add_unwind_protect (set_error_trap, error_trap);
4061 restore_default_signal (ERROR_TRAP);
4063 exit_immediately_on_error = 0;
4069 /* The temporary environment for a builtin is supposed to apply to
4070 all commands executed by that builtin. Currently, this is a
4071 problem only with the `unset', `source' and `eval' builtins. */
4073 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
4078 begin_unwind_frame ("builtin_env");
4082 push_scope (VC_BLTNENV, temporary_env);
4084 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
4085 temporary_env = (HASH_TABLE *)NULL;
4089 /* `return' does a longjmp() back to a saved environment in execute_function.
4090 If a variable assignment list preceded the command, and the shell is
4091 running in POSIX mode, we need to merge that into the shell_variables
4092 table, since `return' is a POSIX special builtin. */
4093 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4095 begin_unwind_frame ("return_temp_env");
4096 add_unwind_protect (merge_temporary_env, (char *)NULL);
4099 executing_builtin++;
4100 executing_command_builtin |= builtin == command_builtin;
4101 result = ((*builtin) (words->next));
4103 /* This shouldn't happen, but in case `return' comes back instead of
4104 longjmp'ing, we need to unwind. */
4105 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4106 discard_unwind_frame ("return_temp_env");
4108 if (subshell == 0 && isbltinenv)
4109 run_unwind_frame ("builtin_env");
4113 exit_immediately_on_error += old_e_flag;
4116 set_error_trap (error_trap);
4119 discard_unwind_frame ("eval_builtin");
4123 /* XXX -- added 12/11 */
4124 terminate_immediately--;
4131 execute_function (var, words, flags, fds_to_close, async, subshell)
4135 struct fd_bitmap *fds_to_close;
4136 int async, subshell;
4138 int return_val, result;
4139 COMMAND *tc, *fc, *save_current;
4140 char *debug_trap, *error_trap, *return_trap;
4141 #if defined (ARRAY_VARS)
4142 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
4144 volatile ARRAY *bash_source_a;
4145 volatile ARRAY *bash_lineno_a;
4147 FUNCTION_DEF *shell_fn;
4152 if (funcnest_max > 0 && funcnest >= funcnest_max)
4154 internal_error ("%s: maximum function nesting level exceeded (%d)", var->name, funcnest);
4155 funcnest = 0; /* XXX - should we reset it somewhere else? */
4156 jump_to_top_level (DISCARD);
4159 #if defined (ARRAY_VARS)
4160 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4161 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4162 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4165 tc = (COMMAND *)copy_command (function_cell (var));
4166 if (tc && (flags & CMD_IGNORE_RETURN))
4167 tc->flags |= CMD_IGNORE_RETURN;
4171 begin_unwind_frame ("function_calling");
4172 push_context (var->name, subshell, temporary_env);
4173 add_unwind_protect (pop_context, (char *)NULL);
4174 unwind_protect_int (line_number);
4175 unwind_protect_int (return_catch_flag);
4176 unwind_protect_jmp_buf (return_catch);
4177 add_unwind_protect (dispose_command, (char *)tc);
4178 unwind_protect_pointer (this_shell_function);
4179 unwind_protect_int (loop_level);
4180 unwind_protect_int (funcnest);
4183 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
4185 temporary_env = (HASH_TABLE *)NULL;
4187 this_shell_function = var;
4188 make_funcname_visible (1);
4190 debug_trap = TRAP_STRING(DEBUG_TRAP);
4191 error_trap = TRAP_STRING(ERROR_TRAP);
4192 return_trap = TRAP_STRING(RETURN_TRAP);
4194 /* The order of the unwind protects for debug_trap, error_trap and
4195 return_trap is important here! unwind-protect commands are run
4196 in reverse order of registration. If this causes problems, take
4197 out the xfree unwind-protect calls and live with the small memory leak. */
4199 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4200 if the function has the trace attribute set, it inherits the DEBUG trap */
4201 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4205 debug_trap = savestring (debug_trap);
4206 add_unwind_protect (xfree, debug_trap);
4207 add_unwind_protect (set_debug_trap, debug_trap);
4209 restore_default_signal (DEBUG_TRAP);
4212 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4213 if (error_trap && error_trace_mode == 0)
4217 error_trap = savestring (error_trap);
4218 add_unwind_protect (xfree, error_trap);
4219 add_unwind_protect (set_error_trap, error_trap);
4221 restore_default_signal (ERROR_TRAP);
4224 /* Shell functions inherit the RETURN trap if function tracing is on
4225 globally or on individually for this function. */
4227 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4229 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
4234 return_trap = savestring (return_trap);
4235 add_unwind_protect (xfree, return_trap);
4236 add_unwind_protect (set_return_trap, return_trap);
4238 restore_default_signal (RETURN_TRAP);
4242 #if defined (ARRAY_VARS)
4243 /* This is quite similar to the code in shell.c and elsewhere. */
4244 shell_fn = find_function_def (this_shell_function->name);
4245 sfile = shell_fn ? shell_fn->source_file : "";
4246 array_push (funcname_a, this_shell_function->name);
4248 array_push (bash_source_a, sfile);
4249 t = itos (executing_line_number ());
4250 array_push (bash_lineno_a, t);
4254 /* The temporary environment for a function is supposed to apply to
4255 all commands executed within the function body. */
4257 remember_args (words->next, 1);
4259 /* Update BASH_ARGV and BASH_ARGC */
4261 push_args (words->next);
4263 /* Number of the line on which the function body starts. */
4264 line_number = function_line_number = tc->line;
4266 #if defined (JOB_CONTROL)
4268 stop_pipeline (async, (COMMAND *)NULL);
4273 return_catch_flag++;
4274 return_val = setjmp (return_catch);
4278 result = return_catch_value;
4279 /* Run the RETURN trap in the function's context. */
4280 save_current = currently_executing_command;
4282 currently_executing_command = save_current;
4286 /* Run the debug trap here so we can trap at the start of a function's
4287 execution rather than the execution of the body's first command. */
4288 showing_function_line = 1;
4289 save_current = currently_executing_command;
4290 result = run_debug_trap ();
4291 #if defined (DEBUGGER)
4292 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4293 skip the command. */
4294 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
4296 showing_function_line = 0;
4297 currently_executing_command = save_current;
4298 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4300 /* Run the RETURN trap in the function's context */
4301 save_current = currently_executing_command;
4303 currently_executing_command = save_current;
4306 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4308 save_current = currently_executing_command;
4310 currently_executing_command = save_current;
4312 showing_function_line = 0;
4315 /* Restore BASH_ARGC and BASH_ARGV */
4320 run_unwind_frame ("function_calling");
4322 #if defined (ARRAY_VARS)
4323 /* These two variables cannot be unset, and cannot be affected by the
4325 array_pop (bash_source_a);
4326 array_pop (bash_lineno_a);
4328 /* FUNCNAME can be unset, and so can potentially be changed by the
4330 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4331 if (nfv == funcname_v)
4332 array_pop (funcname_a);
4335 if (variable_context == 0 || this_shell_function == 0)
4337 make_funcname_visible (0);
4338 #if defined (PROCESS_SUBSTITUTION)
4339 unlink_fifo_list ();
4346 /* A convenience routine for use by other parts of the shell to execute
4347 a particular shell function. */
4349 execute_shell_function (var, words)
4354 struct fd_bitmap *bitmap;
4356 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
4357 begin_unwind_frame ("execute-shell-function");
4358 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
4360 ret = execute_function (var, words, 0, bitmap, 0, 0);
4362 dispose_fd_bitmap (bitmap);
4363 discard_unwind_frame ("execute-shell-function");
4368 /* Execute a shell builtin or function in a subshell environment. This
4369 routine does not return; it only calls exit(). If BUILTIN is non-null,
4370 it points to a function to call to execute a shell builtin; otherwise
4371 VAR points at the body of a function to execute. WORDS is the arguments
4372 to the command, REDIRECTS specifies redirections to perform before the
4373 command is executed. */
4375 execute_subshell_builtin_or_function (words, redirects, builtin, var,
4376 pipe_in, pipe_out, async, fds_to_close,
4379 REDIRECT *redirects;
4380 sh_builtin_func_t *builtin;
4382 int pipe_in, pipe_out, async;
4383 struct fd_bitmap *fds_to_close;
4386 int result, r, funcvalue;
4387 #if defined (JOB_CONTROL)
4390 jobs_hack = (builtin == jobs_builtin) &&
4391 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
4394 /* A subshell is neither a login shell nor interactive. */
4395 login_shell = interactive = 0;
4398 subshell_environment |= SUBSHELL_ASYNC;
4399 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4400 subshell_environment |= SUBSHELL_PIPE;
4402 maybe_make_export_env (); /* XXX - is this needed? */
4404 #if defined (JOB_CONTROL)
4405 /* Eradicate all traces of job control after we fork the subshell, so
4406 all jobs begun by this subshell are in the same process group as
4407 the shell itself. */
4409 /* Allow the output of `jobs' to be piped. */
4411 kill_current_pipeline ();
4413 without_job_control ();
4415 set_sigchld_handler ();
4416 #endif /* JOB_CONTROL */
4418 set_sigint_handler ();
4421 close_fd_bitmap (fds_to_close);
4423 do_piping (pipe_in, pipe_out);
4425 if (do_redirections (redirects, RX_ACTIVE) != 0)
4426 exit (EXECUTION_FAILURE);
4430 /* Give builtins a place to jump back to on failure,
4431 so we don't go back up to main(). */
4432 result = setjmp (top_level);
4434 /* Give the return builtin a place to jump to when executed in a subshell
4437 if (return_catch_flag && builtin == return_builtin)
4438 funcvalue = setjmp (return_catch);
4440 if (result == EXITPROG)
4441 exit (last_command_exit_value);
4443 exit (EXECUTION_FAILURE);
4445 exit (return_catch_value);
4448 r = execute_builtin (builtin, words, flags, 1);
4457 r = execute_function (var, words, flags, fds_to_close, async, 1);
4463 /* Execute a builtin or function in the current shell context. If BUILTIN
4464 is non-null, it is the builtin command to execute, otherwise VAR points
4465 to the body of a function. WORDS are the command's arguments, REDIRECTS
4466 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4467 file descriptors to close.
4469 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4470 not undone before this function returns. */
4472 execute_builtin_or_function (words, builtin, var, redirects,
4473 fds_to_close, flags)
4475 sh_builtin_func_t *builtin;
4477 REDIRECT *redirects;
4478 struct fd_bitmap *fds_to_close;
4482 REDIRECT *saved_undo_list;
4483 #if defined (PROCESS_SUBSTITUTION)
4484 int ofifo, nfifo, osize;
4489 #if defined (PROCESS_SUBSTITUTION)
4490 ofifo = num_fifos ();
4491 ofifo_list = copy_fifo_list (&osize);
4494 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
4496 cleanup_redirects (redirection_undo_list);
4497 redirection_undo_list = (REDIRECT *)NULL;
4498 dispose_exec_redirects ();
4499 #if defined (PROCESS_SUBSTITUTION)
4502 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
4505 saved_undo_list = redirection_undo_list;
4507 /* Calling the "exec" builtin changes redirections forever. */
4508 if (builtin == exec_builtin)
4510 dispose_redirects (saved_undo_list);
4511 saved_undo_list = exec_redirection_undo_list;
4512 exec_redirection_undo_list = (REDIRECT *)NULL;
4515 dispose_exec_redirects ();
4517 if (saved_undo_list)
4519 begin_unwind_frame ("saved redirects");
4520 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
4523 redirection_undo_list = (REDIRECT *)NULL;
4526 result = execute_builtin (builtin, words, flags, 0);
4528 result = execute_function (var, words, flags, fds_to_close, 0, 0);
4530 /* We do this before undoing the effects of any redirections. */
4533 if (ferror (stdout))
4536 /* If we are executing the `command' builtin, but this_shell_builtin is
4537 set to `exec_builtin', we know that we have something like
4538 `command exec [redirection]', since otherwise `exec' would have
4539 overwritten the shell and we wouldn't get here. In this case, we
4540 want to behave as if the `command' builtin had not been specified
4541 and preserve the redirections. */
4542 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
4547 if (saved_undo_list)
4549 dispose_redirects (saved_undo_list);
4552 redirection_undo_list = exec_redirection_undo_list;
4553 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
4555 discard_unwind_frame ("saved redirects");
4558 if (saved_undo_list)
4560 redirection_undo_list = saved_undo_list;
4561 discard_unwind_frame ("saved redirects");
4564 if (redirection_undo_list)
4566 cleanup_redirects (redirection_undo_list);
4567 redirection_undo_list = (REDIRECT *)NULL;
4570 #if defined (PROCESS_SUBSTITUTION)
4571 /* Close any FIFOs created by this builtin or function. */
4572 nfifo = num_fifos ();
4574 close_new_fifos (ofifo_list, osize);
4582 setup_async_signals ()
4584 #if defined (__BEOS__)
4585 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
4588 #if defined (JOB_CONTROL)
4589 if (job_control == 0)
4592 set_signal_handler (SIGINT, SIG_IGN);
4593 set_signal_ignored (SIGINT);
4594 set_signal_handler (SIGQUIT, SIG_IGN);
4595 set_signal_ignored (SIGQUIT);
4599 /* Execute a simple command that is hopefully defined in a disk file
4604 3) look up the command
4607 6) If the execve failed, see if the file has executable mode set.
4608 If so, and it isn't a directory, then execute its contents as
4611 Note that the filename hashing stuff has to take place up here,
4612 in the parent. This is probably why the Bourne style shells
4613 don't handle it, since that would require them to go through
4614 this gnarly hair, for no good reason.
4616 NOTE: callers expect this to fork or exit(). */
4618 /* Name of a shell function to call when a command name is not found. */
4619 #ifndef NOTFOUND_HOOK
4620 # define NOTFOUND_HOOK "command_not_found_handle"
4624 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
4625 async, fds_to_close, cmdflags)
4627 REDIRECT *redirects;
4629 int pipe_in, pipe_out, async;
4630 struct fd_bitmap *fds_to_close;
4633 char *pathname, *command, **args;
4639 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
4640 pathname = words->word->word;
4642 result = EXECUTION_SUCCESS;
4643 #if defined (RESTRICTED_SHELL)
4644 command = (char *)NULL;
4645 if (restricted && mbschr (pathname, '/'))
4647 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4649 result = last_command_exit_value = EXECUTION_FAILURE;
4651 /* If we're not going to fork below, we must already be in a child
4652 process or a context in which it's safe to call exit(2). */
4653 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4654 exit (last_command_exit_value);
4658 #endif /* RESTRICTED_SHELL */
4660 command = search_for_command (pathname);
4664 maybe_make_export_env ();
4665 put_command_name_into_env (command);
4668 /* We have to make the child before we check for the non-existence
4669 of COMMAND, since we want the error messages to be redirected. */
4670 /* If we can get away without forking and there are no pipes to deal with,
4671 don't bother to fork, just directly exec the command. */
4672 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4675 pid = make_child (savestring (command_line), async);
4679 int old_interactive;
4682 /* This has been disabled for the time being. */
4683 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4684 if (posixly_correct == 0)
4685 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
4689 reset_terminating_signals (); /* XXX */
4690 /* Cancel traps, in trap.c. */
4691 restore_original_signals ();
4693 /* restore_original_signals may have undone the work done
4694 by make_child to ensure that SIGINT and SIGQUIT are ignored
4695 in asynchronous children. */
4698 if ((cmdflags & CMD_STDIN_REDIR) &&
4699 pipe_in == NO_PIPE &&
4700 (stdin_redirects (redirects) == 0))
4701 async_redirect_stdin ();
4702 setup_async_signals ();
4705 /* This functionality is now provided by close-on-exec of the
4706 file descriptors manipulated by redirection and piping.
4707 Some file descriptors still need to be closed in all children
4708 because of the way bash does pipes; fds_to_close is a
4709 bitmap of all such file descriptors. */
4711 close_fd_bitmap (fds_to_close);
4713 do_piping (pipe_in, pipe_out);
4715 old_interactive = interactive;
4719 subshell_environment = SUBSHELL_FORK;
4721 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
4723 #if defined (PROCESS_SUBSTITUTION)
4724 /* Try to remove named pipes that may have been created as the
4725 result of redirections. */
4726 unlink_fifo_list ();
4727 #endif /* PROCESS_SUBSTITUTION */
4728 exit (EXECUTION_FAILURE);
4732 interactive = old_interactive;
4736 hookf = find_function (NOTFOUND_HOOK);
4739 /* Make sure filenames are displayed using printable characters */
4740 if (ansic_shouldquote (pathname))
4741 pathname = ansic_quote (pathname, 0, NULL);
4742 internal_error (_("%s: command not found"), pathname);
4743 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
4746 wl = make_word_list (make_word (NOTFOUND_HOOK), words);
4747 exit (execute_shell_function (hookf, wl));
4750 /* Execve expects the command name to be in args[0]. So we
4751 leave it there, in the same format that the user used to
4753 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
4754 exit (shell_execve (command, args, export_env));
4759 /* Make sure that the pipes are closed in the parent. */
4760 close_pipes (pipe_in, pipe_out);
4761 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4762 if (variable_context == 0)
4763 unlink_fifo_list ();
4770 /* CPP defines to decide whether a particular index into the #! line
4771 corresponds to a valid interpreter name or argument character, or
4772 whitespace. The MSDOS define is to allow \r to be treated the same
4775 #if !defined (MSDOS)
4776 # define STRINGCHAR(ind) \
4777 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4778 # define WHITECHAR(ind) \
4779 (ind < sample_len && whitespace (sample[ind]))
4781 # define STRINGCHAR(ind) \
4782 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4783 # define WHITECHAR(ind) \
4784 (ind < sample_len && whitespace (sample[ind]))
4788 getinterp (sample, sample_len, endp)
4790 int sample_len, *endp;
4796 /* Find the name of the interpreter to exec. */
4797 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
4800 for (start = i; STRINGCHAR(i); i++)
4803 execname = substring (sample, start, i);
4810 #if !defined (HAVE_HASH_BANG_EXEC)
4811 /* If the operating system on which we're running does not handle
4812 the #! executable format, then help out. SAMPLE is the text read
4813 from the file, SAMPLE_LEN characters. COMMAND is the name of
4814 the script; it and ARGS, the arguments given by the user, will
4815 become arguments to the specified interpreter. ENV is the environment
4816 to pass to the interpreter.
4818 The word immediately following the #! is the interpreter to execute.
4819 A single argument to the interpreter is allowed. */
4822 execute_shell_script (sample, sample_len, command, args, env)
4828 char *execname, *firstarg;
4829 int i, start, size_increment, larry;
4831 /* Find the name of the interpreter to exec. */
4832 execname = getinterp (sample, sample_len, &i);
4835 /* Now the argument, if any. */
4836 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
4839 /* If there is more text on the line, then it is an argument for the
4844 for (start = i; STRINGCHAR(i); i++)
4846 firstarg = substring ((char *)sample, start, i);
4850 larry = strvec_len (args) + size_increment;
4851 args = strvec_resize (args, larry + 1);
4853 for (i = larry - 1; i; i--)
4854 args[i] = args[i - size_increment];
4865 args[larry] = (char *)NULL;
4867 return (shell_execve (execname, args, env));
4872 #endif /* !HAVE_HASH_BANG_EXEC */
4875 initialize_subshell ()
4878 /* Forget about any aliases that we knew of. We are in a subshell. */
4879 delete_all_aliases ();
4882 #if defined (HISTORY)
4883 /* Forget about the history lines we have read. This is a non-interactive
4885 history_lines_this_session = 0;
4888 #if defined (JOB_CONTROL)
4889 /* Forget about the way job control was working. We are in a subshell. */
4890 without_job_control ();
4891 set_sigchld_handler ();
4893 #endif /* JOB_CONTROL */
4895 /* Reset the values of the shell flags and options. */
4896 reset_shell_flags ();
4897 reset_shell_options ();
4898 reset_shopt_options ();
4900 /* Zero out builtin_env, since this could be a shell script run from a
4901 sourced file with a temporary environment supplied to the `source/.'
4902 builtin. Such variables are not supposed to be exported (empirical
4903 testing with sh and ksh). Just throw it away; don't worry about a
4905 if (vc_isbltnenv (shell_variables))
4906 shell_variables = shell_variables->down;
4908 clear_unwind_protect_list (0);
4909 /* XXX -- are there other things we should be resetting here? */
4910 parse_and_execute_level = 0; /* nothing left to restore it */
4912 /* We're no longer inside a shell function. */
4913 variable_context = return_catch_flag = funcnest = 0;
4915 executing_list = 0; /* XXX */
4917 /* If we're not interactive, close the file descriptor from which we're
4918 reading the current shell script. */
4919 if (interactive_shell == 0)
4920 unset_bash_input (0);
4923 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4924 # define SETOSTYPE(x) __setostype(x)
4926 # define SETOSTYPE(x)
4929 #define READ_SAMPLE_BUF(file, buf, len) \
4932 fd = open(file, O_RDONLY); \
4935 len = read (fd, buf, 80); \
4943 /* Call execve (), handling interpreting shell scripts, and handling
4946 shell_execve (command, args, env)
4954 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
4955 execve (command, args, env);
4956 i = errno; /* error from execve() */
4960 /* If we get to this point, then start checking out the file.
4961 Maybe it is something we can hack ourselves. */
4964 if (file_isdir (command))
4965 #if defined (EISDIR)
4966 internal_error (_("%s: %s"), command, strerror (EISDIR));
4968 internal_error (_("%s: is a directory"), command);
4970 else if (executable_file (command) == 0)
4973 file_error (command);
4975 /* errors not involving the path argument to execve. */
4976 else if (i == E2BIG || i == ENOMEM)
4979 file_error (command);
4983 /* The file has the execute bits set, but the kernel refuses to
4984 run it for some reason. See why. */
4985 #if defined (HAVE_HASH_BANG_EXEC)
4986 READ_SAMPLE_BUF (command, sample, sample_len);
4987 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4992 interp = getinterp (sample, sample_len, (int *)NULL);
4993 ilen = strlen (interp);
4995 if (interp[ilen - 1] == '\r')
4997 interp = xrealloc (interp, ilen + 2);
4998 interp[ilen - 1] = '^';
5000 interp[ilen + 1] = '\0';
5002 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
5008 file_error (command);
5010 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
5013 /* This file is executable.
5014 If it begins with #!, then help out people with losing operating
5015 systems. Otherwise, check to see if it is a binary file by seeing
5016 if the contents of the first line (or up to 80 characters) are in the
5017 ASCII set. If it's a text file, execute the contents as shell commands,
5018 otherwise return 126 (EX_BINARY_FILE). */
5019 READ_SAMPLE_BUF (command, sample, sample_len);
5021 if (sample_len == 0)
5022 return (EXECUTION_SUCCESS);
5024 /* Is this supposed to be an executable script?
5025 If so, the format of the line is "#! interpreter [argument]".
5026 A single argument is allowed. The BSD kernel restricts
5027 the length of the entire line to 32 characters (32 bytes
5028 being the size of the BSD exec header), but we allow 80
5032 #if !defined (HAVE_HASH_BANG_EXEC)
5033 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5034 return (execute_shell_script (sample, sample_len, command, args, env));
5037 if (check_binary_file (sample, sample_len))
5039 internal_error (_("%s: cannot execute binary file"), command);
5040 return (EX_BINARY_FILE);
5044 /* We have committed to attempting to execute the contents of this file
5045 as shell commands. */
5047 initialize_subshell ();
5049 set_sigint_handler ();
5051 /* Insert the name of this shell into the argument list. */
5052 larray = strvec_len (args) + 1;
5053 args = strvec_resize (args, larray + 1);
5055 for (i = larray - 1; i; i--)
5056 args[i] = args[i - 1];
5058 args[0] = shell_name;
5060 args[larray] = (char *)NULL;
5062 if (args[0][0] == '-')
5065 #if defined (RESTRICTED_SHELL)
5067 change_flag ('r', FLAG_OFF);
5072 /* Can't free subshell_argv[0]; that is shell_name. */
5073 for (i = 1; i < subshell_argc; i++)
5074 free (subshell_argv[i]);
5075 free (subshell_argv);
5078 dispose_command (currently_executing_command); /* XXX */
5079 currently_executing_command = (COMMAND *)NULL;
5081 subshell_argc = larray;
5082 subshell_argv = args;
5083 subshell_envp = env;
5085 unbind_args (); /* remove the positional parameters */
5087 longjmp (subshell_top_level, 1);
5092 execute_intern_function (name, function)
5098 if (check_identifier (name, posixly_correct) == 0)
5100 if (posixly_correct && interactive_shell == 0)
5102 last_command_exit_value = EX_BADUSAGE;
5103 jump_to_top_level (ERREXIT);
5105 return (EXECUTION_FAILURE);
5108 var = find_function (name->word);
5109 if (var && (readonly_p (var) || noassign_p (var)))
5111 if (readonly_p (var))
5112 internal_error (_("%s: readonly function"), var->name);
5113 return (EXECUTION_FAILURE);
5116 bind_function (name->word, function);
5117 return (EXECUTION_SUCCESS);
5120 #if defined (INCLUDE_UNUSED)
5121 #if defined (PROCESS_SUBSTITUTION)
5125 register int i, fd_table_size;
5127 fd_table_size = getdtablesize ();
5128 if (fd_table_size > 256) /* clamp to a reasonable value */
5129 fd_table_size = 256;
5131 for (i = 3; i < fd_table_size; i++)
5134 #endif /* PROCESS_SUBSTITUTION */
5138 close_pipes (in, out)
5148 dup_error (oldd, newd)
5151 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
5154 /* Redirect input and output to be from and to the specified pipes.
5155 NO_PIPE and REDIRECT_BOTH are handled correctly. */
5157 do_piping (pipe_in, pipe_out)
5158 int pipe_in, pipe_out;
5160 if (pipe_in != NO_PIPE)
5162 if (dup2 (pipe_in, 0) < 0)
5163 dup_error (pipe_in, 0);
5167 /* Let stdio know the fd may have changed from text to binary mode. */
5168 freopen (NULL, "r", stdin);
5169 #endif /* __CYGWIN__ */
5171 if (pipe_out != NO_PIPE)
5173 if (pipe_out != REDIRECT_BOTH)
5175 if (dup2 (pipe_out, 1) < 0)
5176 dup_error (pipe_out, 1);
5177 if (pipe_out == 0 || pipe_out > 1)
5182 if (dup2 (1, 2) < 0)
5186 /* Let stdio know the fd may have changed from text to binary mode, and
5187 make sure to preserve stdout line buffering. */
5188 freopen (NULL, "w", stdout);
5189 sh_setlinebuf (stdout);
5190 #endif /* __CYGWIN__ */