1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2013 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"
36 #if defined (HAVE_SYS_PARAM_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 job_control; /* XXX */
123 extern int close __P((int));
125 /* Static functions defined and used in this file. */
126 static void close_pipes __P((int, int));
127 static void do_piping __P((int, int));
128 static void bind_lastarg __P((char *));
129 static int shell_control_structure __P((enum command_type));
130 static void cleanup_redirects __P((REDIRECT *));
132 #if defined (JOB_CONTROL)
133 static int restore_signal_mask __P((sigset_t *));
136 static void async_redirect_stdin __P((void));
138 static int builtin_status __P((int));
140 static int execute_for_command __P((FOR_COM *));
141 #if defined (SELECT_COMMAND)
142 static int displen __P((const char *));
143 static int print_index_and_element __P((int, int, WORD_LIST *));
144 static void indent __P((int, int));
145 static void print_select_list __P((WORD_LIST *, int, int, int));
146 static char *select_query __P((WORD_LIST *, int, char *, int));
147 static int execute_select_command __P((SELECT_COM *));
149 #if defined (DPAREN_ARITHMETIC)
150 static int execute_arith_command __P((ARITH_COM *));
152 #if defined (COND_COMMAND)
153 static int execute_cond_node __P((COND_COM *));
154 static int execute_cond_command __P((COND_COM *));
156 #if defined (COMMAND_TIMING)
157 static int mkfmt __P((char *, int, int, time_t, int));
158 static void print_formatted_time __P((FILE *, char *,
159 time_t, int, time_t, int,
161 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
163 #if defined (ARITH_FOR_COMMAND)
164 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
165 static int execute_arith_for_command __P((ARITH_FOR_COM *));
167 static int execute_case_command __P((CASE_COM *));
168 static int execute_while_command __P((WHILE_COM *));
169 static int execute_until_command __P((WHILE_COM *));
170 static int execute_while_or_until __P((WHILE_COM *, int));
171 static int execute_if_command __P((IF_COM *));
172 static int execute_null_command __P((REDIRECT *, int, int, int));
173 static void fix_assignment_words __P((WORD_LIST *));
174 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
175 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
176 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
177 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
179 REDIRECT *, struct fd_bitmap *, int));
180 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
186 static int execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
187 int, int, int, struct fd_bitmap *, int));
189 static char *getinterp __P((char *, int, int *));
190 static void initialize_subshell __P((void));
191 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
192 #if defined (COPROCESS_SUPPORT)
193 static int execute_coproc __P((COMMAND *, int, int, struct fd_bitmap *));
196 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
198 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
200 static int execute_intern_function __P((WORD_DESC *, FUNCTION_DEF *));
202 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
203 so that reader_loop can set it to zero before executing a command. */
206 /* The name of the command that is currently being executed.
207 `test' needs this, for example. */
208 char *this_command_name;
210 /* The printed representation of the currently-executing command (same as
211 the_printed_command), except when a trap is being executed. Useful for
212 a debugger to know where exactly the program is currently executing. */
213 char *the_printed_command_except_trap;
215 /* For catching RETURN in a function. */
216 int return_catch_flag;
217 int return_catch_value;
218 procenv_t return_catch;
220 /* The value returned by the last synchronous command. */
221 int last_command_exit_value;
223 /* Whether or not the last command (corresponding to last_command_exit_value)
224 was terminated by a signal, and, if so, which one. */
225 int last_command_exit_signal;
227 /* Are we currently ignoring the -e option for the duration of a builtin's
229 int builtin_ignoring_errexit = 0;
231 /* The list of redirections to perform which will undo the redirections
232 that I made in the shell. */
233 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
235 /* The list of redirections to perform which will undo the internal
236 redirections performed by the `exec' builtin. These are redirections
237 that must be undone even when exec discards redirection_undo_list. */
238 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
240 /* When greater than zero, value is the `level' of builtins we are
241 currently executing (e.g. `eval echo a' would have it set to 2). */
242 int executing_builtin = 0;
244 /* Non-zero if we are executing a command list (a;b;c, etc.) */
245 int executing_list = 0;
247 /* Non-zero if failing commands in a command substitution should not exit the
248 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
249 commands run in command substitutions by parse_and_execute. */
250 int comsub_ignore_return = 0;
252 /* Non-zero if we have just forked and are currently running in a subshell
254 int subshell_environment;
256 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
257 int subshell_level = 0;
259 /* Currently-executing shell function. */
260 SHELL_VAR *this_shell_function;
262 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
263 int match_ignore_case = 0;
265 int executing_command_builtin = 0;
267 struct stat SB; /* used for debugging */
269 static int special_builtin_failed;
271 static COMMAND *currently_executing_command;
273 /* The line number that the currently executing function starts on. */
274 static int function_line_number;
276 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
277 number containing the function name. Used by executing_line_number to
278 report the correct line number. Kind of a hack. */
279 static int showing_function_line;
281 /* $LINENO ($BASH_LINENO) for use by an ERR trap. Global so parse_and_execute
282 can save and restore it. */
283 int line_number_for_err_trap;
285 /* A sort of function nesting level counter */
287 int funcnest_max = 0; /* bash-4.2 */
289 int lastpipe_opt = 0;
291 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
293 #define FD_BITMAP_DEFAULT_SIZE 32
295 /* Functions to allocate and deallocate the structures used to pass
296 information from the shell to its children about file descriptors
302 struct fd_bitmap *ret;
304 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
310 ret->bitmap = (char *)xmalloc (size);
311 memset (ret->bitmap, '\0', size);
314 ret->bitmap = (char *)NULL;
319 dispose_fd_bitmap (fdbp)
320 struct fd_bitmap *fdbp;
327 close_fd_bitmap (fdbp)
328 struct fd_bitmap *fdbp;
334 for (i = 0; i < fdbp->size; i++)
343 /* Return the line number of the currently executing command. */
345 executing_line_number ()
347 if (executing && showing_function_line == 0 &&
348 (variable_context == 0 || interactive_shell == 0) &&
349 currently_executing_command)
351 #if defined (COND_COMMAND)
352 if (currently_executing_command->type == cm_cond)
353 return currently_executing_command->value.Cond->line;
355 #if defined (DPAREN_ARITHMETIC)
356 if (currently_executing_command->type == cm_arith)
357 return currently_executing_command->value.Arith->line;
359 #if defined (ARITH_FOR_COMMAND)
360 if (currently_executing_command->type == cm_arith_for)
361 return currently_executing_command->value.ArithFor->line;
370 /* Execute the command passed in COMMAND. COMMAND is exactly what
371 read_command () places into GLOBAL_COMMAND. See "command.h" for the
372 details of the command structure.
374 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
375 return values. Executing a command with nothing in it returns
376 EXECUTION_SUCCESS. */
378 execute_command (command)
381 struct fd_bitmap *bitmap;
384 current_fds_to_close = (struct fd_bitmap *)NULL;
385 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
386 begin_unwind_frame ("execute-command");
387 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
389 /* Just do the command, but not asynchronously. */
390 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
392 dispose_fd_bitmap (bitmap);
393 discard_unwind_frame ("execute-command");
395 #if defined (PROCESS_SUBSTITUTION)
396 /* don't unlink fifos if we're in a shell function; wait until the function
398 if (variable_context == 0)
400 #endif /* PROCESS_SUBSTITUTION */
406 /* Return 1 if TYPE is a shell control structure type. */
408 shell_control_structure (type)
409 enum command_type type;
413 #if defined (ARITH_FOR_COMMAND)
416 #if defined (SELECT_COMMAND)
419 #if defined (DPAREN_ARITHMETIC)
422 #if defined (COND_COMMAND)
431 case cm_function_def:
439 /* A function to use to unwind_protect the redirection undo list
442 cleanup_redirects (list)
445 do_redirections (list, RX_ACTIVE);
446 dispose_redirects (list);
450 /* Function to unwind_protect the redirections for functions and builtins. */
452 cleanup_func_redirects (list)
455 do_redirections (list, RX_ACTIVE);
460 dispose_exec_redirects ()
462 if (exec_redirection_undo_list)
464 dispose_redirects (exec_redirection_undo_list);
465 exec_redirection_undo_list = (REDIRECT *)NULL;
469 #if defined (JOB_CONTROL)
470 /* A function to restore the signal mask to its proper value when the shell
471 is interrupted or errors occur while creating a pipeline. */
473 restore_signal_mask (set)
476 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
478 #endif /* JOB_CONTROL */
481 /* A debugging function that can be called from gdb, for instance. */
486 int f, fd_table_size;
488 fd_table_size = getdtablesize ();
490 fprintf (stderr, "pid %ld open files:", (long)getpid ());
491 for (i = 3; i < fd_table_size; i++)
493 if ((f = fcntl (i, F_GETFD, 0)) != -1)
494 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
496 fprintf (stderr, "\n");
501 async_redirect_stdin ()
505 fd = open ("/dev/null", O_RDONLY);
512 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
515 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
517 /* Execute the command passed in COMMAND, perhaps doing it asynchronously.
518 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
519 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
520 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
521 from and where it goes. They can have the value of NO_PIPE, which means
523 FDS_TO_CLOSE is a list of file descriptors to close once the child has
524 been forked. This list often contains the unusable sides of pipes, etc.
526 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
527 return values. Executing a command with nothing in it returns
528 EXECUTION_SUCCESS. */
530 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
534 int pipe_in, pipe_out;
535 struct fd_bitmap *fds_to_close;
537 int exec_result, user_subshell, invert, ignore_return, was_error_trap;
538 REDIRECT *my_undo_list, *exec_undo_list;
540 volatile int last_pid;
541 volatile int save_line_number;
542 #if defined (PROCESS_SUBSTITUTION)
543 volatile int ofifo, nfifo, osize, saved_fifo;
544 volatile char *ofifo_list;
547 if (breaking || continuing)
548 return (last_command_exit_value);
549 if (command == 0 || read_but_dont_execute)
550 return (EXECUTION_SUCCESS);
553 run_pending_traps ();
556 if (running_trap == 0)
558 currently_executing_command = command;
560 invert = (command->flags & CMD_INVERT_RETURN) != 0;
562 /* If we're inverting the return value and `set -e' has been executed,
563 we don't want a failing command to inadvertently cause the shell
565 if (exit_immediately_on_error && invert) /* XXX */
566 command->flags |= CMD_IGNORE_RETURN; /* XXX */
568 exec_result = EXECUTION_SUCCESS;
570 /* If a command was being explicitly run in a subshell, or if it is
571 a shell control-structure, and it has a pipe, then we do the command
573 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
574 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
576 #if defined (COPROCESS_SUPPORT)
577 if (command->type == cm_coproc)
578 return (execute_coproc (command, pipe_in, pipe_out, fds_to_close));
581 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
583 if (command->type == cm_subshell ||
584 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
585 (shell_control_structure (command->type) &&
586 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
591 /* Fork a subshell, turn off the subshell bit, turn off job
592 control and call execute_command () on the command again. */
593 line_number_for_err_trap = line_number;
594 tcmd = make_command_string (command);
595 paren_pid = make_child (savestring (tcmd), asynchronous);
597 if (user_subshell && signal_is_trapped (ERROR_TRAP) &&
598 signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
600 FREE (the_printed_command_except_trap);
601 the_printed_command_except_trap = savestring (the_printed_command);
606 /* We want to run the exit trap for forced {} subshells, and we
607 want to note this before execute_in_subshell modifies the
608 COMMAND struct. Need to keep in mind that execute_in_subshell
609 runs the exit trap for () subshells itself. */
610 /* This handles { command; } & */
611 s = user_subshell == 0 && command->type == cm_group && pipe_in == NO_PIPE && pipe_out == NO_PIPE && asynchronous;
612 /* run exit trap for : | { ...; } and { ...; } | : */
613 /* run exit trap for : | ( ...; ) and ( ...; ) | : */
614 s += user_subshell == 0 && command->type == cm_group && (pipe_in != NO_PIPE || pipe_out != NO_PIPE) && asynchronous == 0;
616 last_command_exit_value = execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close);
618 subshell_exit (last_command_exit_value);
620 exit (last_command_exit_value);
625 close_pipes (pipe_in, pipe_out);
627 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
628 if (variable_context == 0) /* wait until shell function completes */
631 /* If we are part of a pipeline, and not the end of the pipeline,
632 then we should simply return and let the last command in the
633 pipe be waited for. If we are not in a pipeline, or are the
634 last command in the pipeline, then we wait for the subshell
635 and return its exit status as usual. */
636 if (pipe_out != NO_PIPE)
637 return (EXECUTION_SUCCESS);
639 stop_pipeline (asynchronous, (COMMAND *)NULL);
641 if (asynchronous == 0)
643 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
644 invert = (command->flags & CMD_INVERT_RETURN) != 0;
645 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
647 exec_result = wait_for (paren_pid);
649 /* If we have to, invert the return value. */
651 exec_result = ((exec_result == EXECUTION_SUCCESS)
653 : EXECUTION_SUCCESS);
655 last_command_exit_value = exec_result;
656 if (user_subshell && was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
658 save_line_number = line_number;
659 line_number = line_number_for_err_trap;
661 line_number = save_line_number;
664 if (user_subshell && ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
666 run_pending_traps ();
667 jump_to_top_level (ERREXIT);
670 return (last_command_exit_value);
674 DESCRIBE_PID (paren_pid);
676 run_pending_traps ();
678 /* Posix 2013 2.9.3.1: "the exit status of an asynchronous list
680 last_command_exit_value = 0;
681 return (EXECUTION_SUCCESS);
686 #if defined (COMMAND_TIMING)
687 if (command->flags & CMD_TIME_PIPELINE)
691 command->flags |= CMD_FORCE_SUBSHELL;
692 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
696 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
698 if (running_trap == 0)
700 currently_executing_command = (COMMAND *)NULL;
702 return (exec_result);
704 #endif /* COMMAND_TIMING */
706 if (shell_control_structure (command->type) && command->redirects)
707 stdin_redir = stdin_redirects (command->redirects);
709 #if defined (PROCESS_SUBSTITUTION)
710 if (variable_context != 0)
712 ofifo = num_fifos ();
713 ofifo_list = copy_fifo_list ((int *)&osize);
720 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
722 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
724 cleanup_redirects (redirection_undo_list);
725 redirection_undo_list = (REDIRECT *)NULL;
726 dispose_exec_redirects ();
727 #if defined (PROCESS_SUBSTITUTION)
729 free ((void *)ofifo_list);
731 return (last_command_exit_value = EXECUTION_FAILURE);
734 if (redirection_undo_list)
736 /* XXX - why copy here? */
737 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
738 dispose_redirects (redirection_undo_list);
739 redirection_undo_list = (REDIRECT *)NULL;
742 my_undo_list = (REDIRECT *)NULL;
744 if (exec_redirection_undo_list)
746 /* XXX - why copy here? */
747 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
748 dispose_redirects (exec_redirection_undo_list);
749 exec_redirection_undo_list = (REDIRECT *)NULL;
752 exec_undo_list = (REDIRECT *)NULL;
754 if (my_undo_list || exec_undo_list)
755 begin_unwind_frame ("loop_redirections");
758 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
761 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
763 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
767 switch (command->type)
771 save_line_number = line_number;
772 /* We can't rely on variables retaining their values across a
773 call to execute_simple_command if a longjmp occurs as the
774 result of a `return' builtin. This is true for sure with gcc. */
775 #if defined (RECYCLES_PIDS)
776 last_made_pid = NO_PID;
778 last_pid = last_made_pid;
779 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
781 if (ignore_return && command->value.Simple)
782 command->value.Simple->flags |= CMD_IGNORE_RETURN;
783 if (command->flags & CMD_STDIN_REDIR)
784 command->value.Simple->flags |= CMD_STDIN_REDIR;
786 line_number_for_err_trap = line_number = command->value.Simple->line;
788 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
789 asynchronous, fds_to_close);
790 line_number = save_line_number;
792 /* The temporary environment should be used for only the simple
793 command immediately following its definition. */
794 dispose_used_env_vars ();
796 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
797 /* Reclaim memory allocated with alloca () on machines which
798 may be using the alloca emulation code. */
800 #endif /* (ultrix && mips) || C_ALLOCA */
802 /* If we forked to do the command, then we must wait_for ()
805 /* XXX - this is something to watch out for if there are problems
806 when the shell is compiled without job control. Don't worry about
807 whether or not last_made_pid == last_pid; already_making_children
808 tells us whether or not there are unwaited-for children to wait
810 if (already_making_children && pipe_out == NO_PIPE)
812 stop_pipeline (asynchronous, (COMMAND *)NULL);
816 DESCRIBE_PID (last_made_pid);
819 #if !defined (JOB_CONTROL)
820 /* Do not wait for asynchronous processes started from
822 if (last_made_pid != last_asynchronous_pid)
824 /* When executing a shell function that executes other
825 commands, this causes the last simple command in
826 the function to be waited for twice. This also causes
827 subshells forked to execute builtin commands (e.g., in
828 pipelines) to be waited for twice. */
829 exec_result = wait_for (last_made_pid);
833 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
834 only the failure of a simple command. */
835 if (was_error_trap && ignore_return == 0 && invert == 0 && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)
837 last_command_exit_value = exec_result;
838 line_number = line_number_for_err_trap;
840 line_number = save_line_number;
843 if (ignore_return == 0 && invert == 0 &&
844 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
845 (exit_immediately_on_error && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)))
847 last_command_exit_value = exec_result;
848 run_pending_traps ();
849 jump_to_top_level (ERREXIT);
856 command->value.For->flags |= CMD_IGNORE_RETURN;
857 exec_result = execute_for_command (command->value.For);
860 #if defined (ARITH_FOR_COMMAND)
863 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
864 exec_result = execute_arith_for_command (command->value.ArithFor);
868 #if defined (SELECT_COMMAND)
871 command->value.Select->flags |= CMD_IGNORE_RETURN;
872 exec_result = execute_select_command (command->value.Select);
878 command->value.Case->flags |= CMD_IGNORE_RETURN;
879 exec_result = execute_case_command (command->value.Case);
884 command->value.While->flags |= CMD_IGNORE_RETURN;
885 exec_result = execute_while_command (command->value.While);
890 command->value.While->flags |= CMD_IGNORE_RETURN;
891 exec_result = execute_until_command (command->value.While);
896 command->value.If->flags |= CMD_IGNORE_RETURN;
897 exec_result = execute_if_command (command->value.If);
902 /* This code can be executed from either of two paths: an explicit
903 '{}' command, or via a function call. If we are executed via a
904 function call, we have already taken care of the function being
905 executed in the background (down there in execute_simple_command ()),
906 and this command should *not* be marked as asynchronous. If we
907 are executing a regular '{}' group command, and asynchronous == 1,
908 we must want to execute the whole command in the background, so we
909 need a subshell, and we want the stuff executed in that subshell
910 (this group command) to be executed in the foreground of that
911 subshell (i.e. there will not be *another* subshell forked).
913 What we do is to force a subshell if asynchronous, and then call
914 execute_command_internal again with asynchronous still set to 1,
915 but with the original group command, so the printed command will
918 The code above that handles forking off subshells will note that
919 both subshell and async are on, and turn off async in the child
920 after forking the subshell (but leave async set in the parent, so
921 the normal call to describe_pid is made). This turning off
922 async is *crucial*; if it is not done, this will fall into an
923 infinite loop of executions through this spot in subshell after
924 subshell until the process limit is exhausted. */
928 command->flags |= CMD_FORCE_SUBSHELL;
930 execute_command_internal (command, 1, pipe_in, pipe_out,
935 if (ignore_return && command->value.Group->command)
936 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
938 execute_command_internal (command->value.Group->command,
939 asynchronous, pipe_in, pipe_out,
945 exec_result = execute_connection (command, asynchronous,
946 pipe_in, pipe_out, fds_to_close);
949 #if defined (DPAREN_ARITHMETIC)
951 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
953 command->value.Arith->flags |= CMD_IGNORE_RETURN;
954 line_number_for_err_trap = save_line_number = line_number;
955 exec_result = execute_arith_command (command->value.Arith);
956 line_number = save_line_number;
958 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
960 last_command_exit_value = exec_result;
961 save_line_number = line_number;
962 line_number = line_number_for_err_trap;
964 line_number = save_line_number;
967 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
969 last_command_exit_value = exec_result;
970 run_pending_traps ();
971 jump_to_top_level (ERREXIT);
977 #if defined (COND_COMMAND)
979 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
981 command->value.Cond->flags |= CMD_IGNORE_RETURN;
983 line_number_for_err_trap = save_line_number = line_number;
984 exec_result = execute_cond_command (command->value.Cond);
985 line_number = save_line_number;
987 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
989 last_command_exit_value = exec_result;
990 save_line_number = line_number;
991 line_number = line_number_for_err_trap;
993 line_number = save_line_number;
996 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
998 last_command_exit_value = exec_result;
999 run_pending_traps ();
1000 jump_to_top_level (ERREXIT);
1006 case cm_function_def:
1007 exec_result = execute_intern_function (command->value.Function_def->name,
1008 command->value.Function_def);
1012 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
1017 do_redirections (my_undo_list, RX_ACTIVE);
1018 dispose_redirects (my_undo_list);
1022 dispose_redirects (exec_undo_list);
1024 if (my_undo_list || exec_undo_list)
1025 discard_unwind_frame ("loop_redirections");
1027 #if defined (PROCESS_SUBSTITUTION)
1030 nfifo = num_fifos ();
1032 close_new_fifos ((char *)ofifo_list, osize);
1033 free ((void *)ofifo_list);
1037 /* Invert the return value if we have to */
1039 exec_result = (exec_result == EXECUTION_SUCCESS)
1041 : EXECUTION_SUCCESS;
1043 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
1044 /* This is where we set PIPESTATUS from the exit status of the appropriate
1045 compound commands (the ones that look enough like simple commands to
1046 cause confusion). We might be able to optimize by not doing this if
1047 subshell_environment != 0. */
1048 switch (command->type)
1050 # if defined (DPAREN_ARITHMETIC)
1053 # if defined (COND_COMMAND)
1056 set_pipestatus_from_exit (exec_result);
1061 last_command_exit_value = exec_result;
1062 run_pending_traps ();
1064 if (running_trap == 0)
1066 currently_executing_command = (COMMAND *)NULL;
1068 return (last_command_exit_value);
1071 #if defined (COMMAND_TIMING)
1073 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1074 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
1075 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
1076 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
1079 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1080 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1082 static const int precs[] = { 0, 100, 10, 1 };
1084 /* Expand one `%'-prefixed escape sequence from a time format string. */
1086 mkfmt (buf, prec, lng, sec, sec_fraction)
1093 char abuf[INT_STRLEN_BOUND(time_t) + 1];
1097 abuf[sizeof(abuf) - 1] = '\0';
1099 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1104 aind = sizeof(abuf) - 2;
1106 abuf[aind--] = (min % 10) + '0';
1110 buf[ind++] = abuf[aind++];
1114 /* Now add the seconds. */
1115 aind = sizeof (abuf) - 2;
1117 abuf[aind--] = (sec % 10) + '0';
1121 buf[ind++] = abuf[aind++];
1123 /* We want to add a decimal point and PREC places after it if PREC is
1124 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1129 for (aind = 1; aind <= prec; aind++)
1131 buf[ind++] = (sec_fraction / precs[aind]) + '0';
1132 sec_fraction %= precs[aind];
1143 /* Interpret the format string FORMAT, interpolating the following escape
1147 where the optional `prec' is a precision, meaning the number of
1148 characters after the decimal point, the optional `l' means to format
1149 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1150 and the last character is one of
1152 R number of seconds of `real' time
1153 U number of seconds of `user' time
1154 S number of seconds of `system' time
1156 An occurrence of `%%' in the format string is translated to a `%'. The
1157 result is printed to FP, a pointer to a FILE. The other variables are
1158 the seconds and thousandths of a second of real, user, and system time,
1161 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1172 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1177 len = strlen (format);
1178 ssize = (len + 64) - (len % 64);
1179 str = (char *)xmalloc (ssize);
1182 for (s = format; *s; s++)
1184 if (*s != '%' || s[1] == '\0')
1186 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1189 else if (s[1] == '%')
1192 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1195 else if (s[1] == 'P')
1199 /* clamp CPU usage at 100% */
1204 sum_frac = (cpu % 100) * 10;
1205 len = mkfmt (ts, 2, 0, sum, sum_frac);
1206 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1207 strcpy (str + sindex, ts);
1212 prec = 3; /* default is three places past the decimal point. */
1213 lng = 0; /* default is to not use minutes or append `s' */
1215 if (DIGIT (*s)) /* `precision' */
1218 if (prec > 3) prec = 3;
1220 if (*s == 'l') /* `length extender' */
1225 if (*s == 'R' || *s == 'E')
1226 len = mkfmt (ts, prec, lng, rs, rsf);
1228 len = mkfmt (ts, prec, lng, us, usf);
1230 len = mkfmt (ts, prec, lng, ss, ssf);
1233 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1237 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1238 strcpy (str + sindex, ts);
1244 fprintf (fp, "%s\n", str);
1251 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1253 int asynchronous, pipe_in, pipe_out;
1254 struct fd_bitmap *fds_to_close;
1256 int rv, posix_time, old_flags, nullcmd;
1262 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1263 struct timeval real, user, sys;
1264 struct timeval before, after;
1265 # if defined (HAVE_STRUCT_TIMEZONE)
1266 struct timezone dtz; /* posix doesn't define this */
1268 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1270 # if defined (HAVE_TIMES)
1271 clock_t tbefore, tafter, real, user, sys;
1272 struct tms before, after;
1276 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1277 # if defined (HAVE_STRUCT_TIMEZONE)
1278 gettimeofday (&before, &dtz);
1280 gettimeofday (&before, (void *)NULL);
1281 # endif /* !HAVE_STRUCT_TIMEZONE */
1282 getrusage (RUSAGE_SELF, &selfb);
1283 getrusage (RUSAGE_CHILDREN, &kidsb);
1285 # if defined (HAVE_TIMES)
1286 tbefore = times (&before);
1290 posix_time = command && (command->flags & CMD_TIME_POSIX);
1292 nullcmd = (command == 0) || (command->type == cm_simple && command->value.Simple->words == 0 && command->value.Simple->redirects == 0);
1293 if (posixly_correct && nullcmd)
1295 #if defined (HAVE_GETRUSAGE)
1296 selfb.ru_utime.tv_sec = kidsb.ru_utime.tv_sec = selfb.ru_stime.tv_sec = kidsb.ru_stime.tv_sec = 0;
1297 selfb.ru_utime.tv_usec = kidsb.ru_utime.tv_usec = selfb.ru_stime.tv_usec = kidsb.ru_stime.tv_usec = 0;
1298 before.tv_sec = shell_start_time;
1301 before.tms_utime = before.tms_stime = before.tms_cutime = before.tms_cstime = 0;
1302 tbefore = shell_start_time;
1306 old_flags = command->flags;
1307 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1308 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1309 command->flags = old_flags;
1312 rsf = usf = ssf = cpu = 0;
1314 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1315 # if defined (HAVE_STRUCT_TIMEZONE)
1316 gettimeofday (&after, &dtz);
1318 gettimeofday (&after, (void *)NULL);
1319 # endif /* !HAVE_STRUCT_TIMEZONE */
1320 getrusage (RUSAGE_SELF, &selfa);
1321 getrusage (RUSAGE_CHILDREN, &kidsa);
1323 difftimeval (&real, &before, &after);
1324 timeval_to_secs (&real, &rs, &rsf);
1326 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1327 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1328 timeval_to_secs (&user, &us, &usf);
1330 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1331 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1332 timeval_to_secs (&sys, &ss, &ssf);
1334 cpu = timeval_to_cpu (&real, &user, &sys);
1336 # if defined (HAVE_TIMES)
1337 tafter = times (&after);
1339 real = tafter - tbefore;
1340 clock_t_to_secs (real, &rs, &rsf);
1342 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1343 clock_t_to_secs (user, &us, &usf);
1345 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1346 clock_t_to_secs (sys, &ss, &ssf);
1348 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1352 rsf = usf = ssf = cpu = 0;
1357 time_format = POSIX_TIMEFORMAT;
1358 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1360 if (posixly_correct && nullcmd)
1361 time_format = "user\t%2lU\nsys\t%2lS";
1363 time_format = BASH_TIMEFORMAT;
1365 if (time_format && *time_format)
1366 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1370 #endif /* COMMAND_TIMING */
1372 /* Execute a command that's supposed to be in a subshell. This must be
1373 called after make_child and we must be running in the child process.
1374 The caller will return or exit() immediately with the value this returns. */
1376 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1379 int pipe_in, pipe_out;
1380 struct fd_bitmap *fds_to_close;
1382 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1383 int ois, user_coproc;
1385 volatile COMMAND *tcom;
1387 USE_VAR(user_subshell);
1388 USE_VAR(user_coproc);
1391 USE_VAR(asynchronous);
1394 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1395 pipe_in == NO_PIPE &&
1396 stdin_redirects (command->redirects) == 0);
1398 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1399 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1400 user_coproc = command->type == cm_coproc;
1402 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1404 /* If a command is asynchronous in a subshell (like ( foo ) & or
1405 the special case of an asynchronous GROUP command where the
1406 the subshell bit is turned on down in case cm_group: below),
1407 turn off `asynchronous', so that two subshells aren't spawned.
1408 XXX - asynchronous used to be set to 0 in this block, but that
1409 means that setup_async_signals was never run. Now it's set to
1410 0 after subshell_environment is set appropriately and setup_async_signals
1413 This seems semantically correct to me. For example,
1414 ( foo ) & seems to say ``do the command `foo' in a subshell
1415 environment, but don't wait for that subshell to finish'',
1416 and "{ foo ; bar ; } &" seems to me to be like functions or
1417 builtins in the background, which executed in a subshell
1418 environment. I just don't see the need to fork two subshells. */
1420 /* Don't fork again, we are already in a subshell. A `doubly
1421 async' shell is not interactive, however. */
1424 #if defined (JOB_CONTROL)
1425 /* If a construct like ( exec xxx yyy ) & is given while job
1426 control is active, we want to prevent exec from putting the
1427 subshell back into the original process group, carefully
1428 undoing all the work we just did in make_child. */
1430 #endif /* JOB_CONTROL */
1431 ois = interactive_shell;
1432 interactive_shell = 0;
1433 /* This test is to prevent alias expansion by interactive shells that
1434 run `(command) &' but to allow scripts that have enabled alias
1435 expansion with `shopt -s expand_alias' to continue to expand
1437 if (ois != interactive_shell)
1441 /* Subshells are neither login nor interactive. */
1442 login_shell = interactive = 0;
1445 subshell_environment = SUBSHELL_PAREN;
1448 subshell_environment = 0; /* XXX */
1450 subshell_environment |= SUBSHELL_ASYNC;
1451 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1452 subshell_environment |= SUBSHELL_PIPE;
1454 subshell_environment |= SUBSHELL_COPROC;
1457 reset_terminating_signals (); /* in sig.c */
1458 /* Cancel traps, in trap.c. */
1459 /* Reset the signal handlers in the child, but don't free the
1460 trap strings. Set a flag noting that we have to free the
1461 trap strings if we run trap to change a signal disposition. */
1462 reset_signal_handlers ();
1463 subshell_environment |= SUBSHELL_RESETTRAP;
1465 /* Make sure restore_original_signals doesn't undo the work done by
1466 make_child to ensure that asynchronous children are immune to SIGINT
1467 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1471 setup_async_signals ();
1475 #if defined (JOB_CONTROL)
1476 set_sigchld_handler ();
1477 #endif /* JOB_CONTROL */
1479 set_sigint_handler ();
1481 #if defined (JOB_CONTROL)
1482 /* Delete all traces that there were any jobs running. This is
1483 only for subshells. */
1484 without_job_control ();
1485 #endif /* JOB_CONTROL */
1488 close_fd_bitmap (fds_to_close);
1490 do_piping (pipe_in, pipe_out);
1492 #if defined (COPROCESS_SUPPORT)
1496 /* If this is a user subshell, set a flag if stdin was redirected.
1497 This is used later to decide whether to redirect fd 0 to
1498 /dev/null for async commands in the subshell. This adds more
1499 sh compatibility, but I'm not sure it's the right thing to do. */
1502 stdin_redir = stdin_redirects (command->redirects);
1503 restore_default_signal (EXIT_TRAP);
1506 /* If this is an asynchronous command (command &), we want to
1507 redirect the standard input from /dev/null in the absence of
1508 any specific redirection involving stdin. */
1509 if (should_redir_stdin && stdin_redir == 0)
1510 async_redirect_stdin ();
1512 /* Do redirections, then dispose of them before recursive call. */
1513 if (command->redirects)
1515 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1516 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1518 dispose_redirects (command->redirects);
1519 command->redirects = (REDIRECT *)NULL;
1522 if (command->type == cm_subshell)
1523 tcom = command->value.Subshell->command;
1524 else if (user_coproc)
1525 tcom = command->value.Coproc->command;
1529 if (command->flags & CMD_TIME_PIPELINE)
1530 tcom->flags |= CMD_TIME_PIPELINE;
1531 if (command->flags & CMD_TIME_POSIX)
1532 tcom->flags |= CMD_TIME_POSIX;
1534 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1535 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1536 tcom->flags |= CMD_IGNORE_RETURN;
1538 /* If this is a simple command, tell execute_disk_command that it
1539 might be able to get away without forking and simply exec.
1540 This means things like ( sleep 10 ) will only cause one fork.
1541 If we're timing the command or inverting its return value, however,
1542 we cannot do this optimization. */
1543 if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1544 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1545 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1547 tcom->flags |= CMD_NO_FORK;
1548 if (tcom->type == cm_simple)
1549 tcom->value.Simple->flags |= CMD_NO_FORK;
1552 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1553 tcom->flags &= ~CMD_INVERT_RETURN;
1555 result = setjmp_nosigs (top_level);
1557 /* If we're inside a function while executing this subshell, we
1558 need to handle a possible `return'. */
1560 if (return_catch_flag)
1561 function_value = setjmp_nosigs (return_catch);
1563 /* If we're going to exit the shell, we don't want to invert the return
1565 if (result == EXITPROG)
1566 invert = 0, return_code = last_command_exit_value;
1568 return_code = EXECUTION_FAILURE;
1569 else if (function_value)
1570 return_code = return_catch_value;
1572 return_code = execute_command_internal ((COMMAND *)tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1574 /* If we are asked to, invert the return value. */
1576 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1577 : EXECUTION_SUCCESS;
1579 /* If we were explicitly placed in a subshell with (), we need
1580 to do the `shell cleanup' things, such as running traps[0]. */
1581 if (user_subshell && signal_is_trapped (0))
1583 last_command_exit_value = return_code;
1584 return_code = run_exit_trap ();
1588 return (return_code);
1592 #if defined (COPROCESS_SUPPORT)
1593 #define COPROC_MAX 16
1595 typedef struct cpelement
1597 struct cpelement *next;
1598 struct coproc *coproc;
1602 typedef struct cplist
1604 struct cpelement *head;
1605 struct cpelement *tail;
1611 static struct cpelement *cpe_alloc __P((struct coproc *));
1612 static void cpe_dispose __P((struct cpelement *));
1613 static struct cpelement *cpl_add __P((struct coproc *));
1614 static struct cpelement *cpl_delete __P((pid_t));
1615 static void cpl_reap __P((void));
1616 static void cpl_flush __P((void));
1617 static void cpl_closeall __P((void));
1618 static struct cpelement *cpl_search __P((pid_t));
1619 static struct cpelement *cpl_searchbyname __P((const char *));
1620 static void cpl_prune __P((void));
1622 static void coproc_free __P((struct coproc *));
1624 /* Will go away when there is fully-implemented support for multiple coprocs. */
1625 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0, 0, 0, 0 };
1627 cplist_t coproc_list = {0, 0, 0};
1629 /* Functions to manage the list of coprocs */
1631 static struct cpelement *
1635 struct cpelement *cpe;
1637 cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1639 cpe->next = (struct cpelement *)0;
1645 struct cpelement *cpe;
1650 static struct cpelement *
1654 struct cpelement *cpe;
1656 cpe = cpe_alloc (cp);
1658 if (coproc_list.head == 0)
1660 coproc_list.head = coproc_list.tail = cpe;
1661 coproc_list.ncoproc = 0; /* just to make sure */
1665 coproc_list.tail->next = cpe;
1666 coproc_list.tail = cpe;
1668 coproc_list.ncoproc++;
1673 static struct cpelement *
1677 struct cpelement *prev, *p;
1679 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1680 if (p->coproc->c_pid == pid)
1682 prev->next = p->next; /* remove from list */
1687 return 0; /* not found */
1690 itrace("cpl_delete: deleting %d", pid);
1693 /* Housekeeping in the border cases. */
1694 if (p == coproc_list.head)
1695 coproc_list.head = coproc_list.head->next;
1696 else if (p == coproc_list.tail)
1697 coproc_list.tail = prev;
1699 coproc_list.ncoproc--;
1700 if (coproc_list.ncoproc == 0)
1701 coproc_list.head = coproc_list.tail = 0;
1702 else if (coproc_list.ncoproc == 1)
1703 coproc_list.tail = coproc_list.head; /* just to make sure */
1711 struct cpelement *p, *next, *nh, *nt;
1713 /* Build a new list by removing dead coprocs and fix up the coproc_list
1714 pointers when done. */
1715 nh = nt = next = (struct cpelement *)0;
1716 for (p = coproc_list.head; p; p = next)
1719 if (p->coproc->c_flags & COPROC_DEAD)
1721 coproc_list.ncoproc--; /* keep running count, fix up pointers later */
1724 itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1727 coproc_dispose (p->coproc);
1739 if (coproc_list.ncoproc == 0)
1740 coproc_list.head = coproc_list.tail = 0;
1745 coproc_list.head = nh;
1746 coproc_list.tail = nt;
1747 if (coproc_list.ncoproc == 1)
1748 coproc_list.tail = coproc_list.head; /* just to make sure */
1752 /* Clear out the list of saved statuses */
1756 struct cpelement *cpe, *p;
1758 for (cpe = coproc_list.head; cpe; )
1763 coproc_dispose (p->coproc);
1767 coproc_list.head = coproc_list.tail = 0;
1768 coproc_list.ncoproc = 0;
1774 struct cpelement *cpe;
1776 for (cpe = coproc_list.head; cpe; cpe = cpe->next)
1777 coproc_close (cpe->coproc);
1784 struct cpelement *cpe;
1786 for (cpe = coproc_list.head; cpe; cpe = cpe->next)
1787 coproc_checkfd (cpe->coproc, fd);
1790 /* Search for PID in the list of coprocs; return the cpelement struct if
1791 found. If not found, return NULL. */
1792 static struct cpelement *
1796 struct cpelement *cpe;
1798 for (cpe = coproc_list.head ; cpe; cpe = cpe->next)
1799 if (cpe->coproc->c_pid == pid)
1801 return (struct cpelement *)NULL;
1804 /* Search for the coproc named NAME in the list of coprocs; return the
1805 cpelement struct if found. If not found, return NULL. */
1806 static struct cpelement *
1807 cpl_searchbyname (name)
1810 struct cpelement *cp;
1812 for (cp = coproc_list.head ; cp; cp = cp->next)
1813 if (STREQ (cp->coproc->c_name, name))
1815 return (struct cpelement *)NULL;
1822 struct cpelement *cp;
1824 while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1826 cp = coproc_list.head;
1827 coproc_list.head = coproc_list.head->next;
1828 coproc_dispose (cp->coproc);
1830 coproc_list.ncoproc--;
1835 /* These currently use a single global "shell coproc" but are written in a
1836 way to not preclude additional coprocs later (using the list management
1840 getcoprocbypid (pid)
1843 #if MULTIPLE_COPROCS
1844 struct cpelement *p;
1846 p = cpl_search (pid);
1847 return (p ? p->coproc : 0);
1849 return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1854 getcoprocbyname (name)
1857 #if MULTIPLE_COPROCS
1858 struct cpelement *p;
1860 p = cpl_searchbyname (name);
1861 return (p ? p->coproc : 0);
1863 return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1873 cp->c_rfd = cp->c_wfd = -1;
1874 cp->c_rsave = cp->c_wsave = -1;
1875 cp->c_flags = cp->c_status = cp->c_lock = 0;
1879 coproc_alloc (name, pid)
1885 #if MULTIPLE_COPROCS
1886 cp = (struct coproc *)xmalloc (sizeof (struct coproc));
1894 cp->c_name = savestring (name);
1895 #if MULTIPLE_COPROCS
1918 BLOCK_SIGNAL (SIGCHLD, set, oset);
1920 coproc_unsetvars (cp);
1923 #if MULTIPLE_COPROCS
1929 UNBLOCK_SIGNAL (oset);
1932 /* Placeholder for now. Will require changes for multiple coprocs */
1936 #if MULTIPLE_COPROCS
1939 coproc_dispose (&sh_coproc);
1957 cp->c_rsave = cp->c_wsave = -1;
1963 #if MULTIPLE_COPROCS
1966 coproc_close (&sh_coproc); /* XXX - will require changes for multiple coprocs */
1973 #if MULTIPLE_COPROCS
1978 cp = &sh_coproc; /* XXX - will require changes for multiple coprocs */
1979 if (cp && (cp->c_flags & COPROC_DEAD))
1980 coproc_dispose (cp);
1985 coproc_rclose (cp, fd)
1989 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1997 coproc_wclose (cp, fd)
2001 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
2009 coproc_checkfd (cp, fd)
2016 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
2017 update = cp->c_rfd = -1;
2018 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
2019 update = cp->c_wfd = -1;
2021 coproc_setvars (cp);
2028 #if MULTIPLE_COPROCS
2031 coproc_checkfd (&sh_coproc, fd);
2036 coproc_fdclose (cp, fd)
2040 coproc_rclose (cp, fd);
2041 coproc_wclose (cp, fd);
2042 coproc_setvars (cp);
2049 cp->c_rsave = cp->c_rfd;
2050 cp->c_wsave = cp->c_wfd;
2054 coproc_fdrestore (cp)
2057 cp->c_rfd = cp->c_rsave;
2058 cp->c_wfd = cp->c_wsave;
2062 coproc_pidchk (pid, status)
2067 #if MULTIPLE_COPROCS
2068 struct cpelement *cpe;
2070 cpe = cpl_delete (pid);
2071 cp = cpe ? cpe->coproc : 0;
2073 cp = getcoprocbypid (pid);
2078 cp->c_status = status;
2079 cp->c_flags |= COPROC_DEAD;
2080 cp->c_flags &= ~COPROC_RUNNING;
2081 /* Don't dispose the coproc or unset the COPROC_XXX variables because
2082 this is executed in a signal handler context. Wait until coproc_reap
2083 takes care of it. */
2095 #if defined (ARRAY_VARS)
2099 if (cp->c_name == 0)
2102 l = strlen (cp->c_name);
2103 namevar = xmalloc (l + 16);
2105 #if defined (ARRAY_VARS)
2106 v = find_variable (cp->c_name);
2108 v = make_new_array_variable (cp->c_name);
2109 if (array_p (v) == 0)
2110 v = convert_var_to_array (v);
2112 t = itos (cp->c_rfd);
2114 v = bind_array_variable (cp->c_name, ind, t, 0);
2117 t = itos (cp->c_wfd);
2119 bind_array_variable (cp->c_name, ind, t, 0);
2122 sprintf (namevar, "%s_READ", cp->c_name);
2123 t = itos (cp->c_rfd);
2124 bind_variable (namevar, t, 0);
2126 sprintf (namevar, "%s_WRITE", cp->c_name);
2127 t = itos (cp->c_wfd);
2128 bind_variable (namevar, t, 0);
2132 sprintf (namevar, "%s_PID", cp->c_name);
2133 t = itos (cp->c_pid);
2134 bind_variable (namevar, t, 0);
2141 coproc_unsetvars (cp)
2147 if (cp->c_name == 0)
2150 l = strlen (cp->c_name);
2151 namevar = xmalloc (l + 16);
2153 sprintf (namevar, "%s_PID", cp->c_name);
2154 unbind_variable (namevar);
2156 #if defined (ARRAY_VARS)
2157 unbind_variable (cp->c_name);
2159 sprintf (namevar, "%s_READ", cp->c_name);
2160 unbind_variable (namevar);
2161 sprintf (namevar, "%s_WRITE", cp->c_name);
2162 unbind_variable (namevar);
2169 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
2171 int pipe_in, pipe_out;
2172 struct fd_bitmap *fds_to_close;
2174 int rpipe[2], wpipe[2], estat, invert;
2180 /* XXX -- can be removed after changes to handle multiple coprocs */
2181 #if !MULTIPLE_COPROCS
2182 if (sh_coproc.c_pid != NO_PID)
2183 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc.c_pid, sh_coproc.c_name);
2184 coproc_init (&sh_coproc);
2187 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2188 command_string_index = 0;
2189 tcmd = make_command_string (command);
2191 sh_openpipe ((int *)&rpipe); /* 0 = parent read, 1 = child write */
2192 sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2194 BLOCK_SIGNAL (SIGCHLD, set, oset);
2196 coproc_pid = make_child (savestring (tcmd), 1);
2198 if (coproc_pid == 0)
2203 UNBLOCK_SIGNAL (oset);
2204 estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2215 /* XXX - possibly run Coproc->name through word expansion? */
2216 cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2217 cp->c_rfd = rpipe[0];
2218 cp->c_wfd = wpipe[1];
2220 SET_CLOSE_ON_EXEC (cp->c_rfd);
2221 SET_CLOSE_ON_EXEC (cp->c_wfd);
2223 coproc_setvars (cp);
2225 UNBLOCK_SIGNAL (oset);
2228 itrace ("execute_coproc: [%d] %s", coproc_pid, the_printed_command);
2231 close_pipes (pipe_in, pipe_out);
2232 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2233 unlink_fifo_list ();
2235 stop_pipeline (1, (COMMAND *)NULL);
2236 DESCRIBE_PID (coproc_pid);
2237 run_pending_traps ();
2239 return (invert ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2251 /* Catch-all cleanup function for lastpipe code for unwind-protects */
2253 lastpipe_cleanup (s)
2256 unfreeze_jobs_list ();
2260 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2262 int asynchronous, pipe_in, pipe_out;
2263 struct fd_bitmap *fds_to_close;
2265 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2266 int lstdin, lastpipe_flag, lastpipe_jid;
2268 struct fd_bitmap *fd_bitmap;
2271 #if defined (JOB_CONTROL)
2273 BLOCK_CHILD (set, oset);
2274 #endif /* JOB_CONTROL */
2276 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2281 while (cmd && cmd->type == cm_connection &&
2282 cmd->value.Connection && cmd->value.Connection->connector == '|')
2284 /* Make a pipeline between the two commands. */
2285 if (pipe (fildes) < 0)
2287 sys_error (_("pipe error"));
2288 #if defined (JOB_CONTROL)
2289 terminate_current_pipeline ();
2290 kill_current_pipeline ();
2291 UNBLOCK_CHILD (oset);
2292 #endif /* JOB_CONTROL */
2293 last_command_exit_value = EXECUTION_FAILURE;
2294 /* The unwind-protects installed below will take care
2295 of closing all of the open file descriptors. */
2296 throw_to_top_level ();
2297 return (EXECUTION_FAILURE); /* XXX */
2300 /* Here is a problem: with the new file close-on-exec
2301 code, the read end of the pipe (fildes[0]) stays open
2302 in the first process, so that process will never get a
2303 SIGPIPE. There is no way to signal the first process
2304 that it should close fildes[0] after forking, so it
2305 remains open. No SIGPIPE is ever sent because there
2306 is still a file descriptor open for reading connected
2307 to the pipe. We take care of that here. This passes
2308 around a bitmap of file descriptors that must be
2309 closed after making a child process in execute_simple_command. */
2311 /* We need fd_bitmap to be at least as big as fildes[0].
2312 If fildes[0] is less than fds_to_close->size, then
2313 use fds_to_close->size. */
2314 new_bitmap_size = (fildes[0] < fds_to_close->size)
2315 ? fds_to_close->size
2318 fd_bitmap = new_fd_bitmap (new_bitmap_size);
2320 /* Now copy the old information into the new bitmap. */
2321 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2323 /* And mark the pipe file descriptors to be closed. */
2324 fd_bitmap->bitmap[fildes[0]] = 1;
2326 /* In case there are pipe or out-of-processes errors, we
2327 want all these file descriptors to be closed when
2328 unwind-protects are run, and the storage used for the
2329 bitmaps freed up. */
2330 begin_unwind_frame ("pipe-file-descriptors");
2331 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2332 add_unwind_protect (close_fd_bitmap, fd_bitmap);
2334 add_unwind_protect (close, prev);
2335 dummyfd = fildes[1];
2336 add_unwind_protect (close, dummyfd);
2338 #if defined (JOB_CONTROL)
2339 add_unwind_protect (restore_signal_mask, &oset);
2340 #endif /* JOB_CONTROL */
2342 if (ignore_return && cmd->value.Connection->first)
2343 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2344 execute_command_internal (cmd->value.Connection->first, asynchronous,
2345 prev, fildes[1], fd_bitmap);
2353 dispose_fd_bitmap (fd_bitmap);
2354 discard_unwind_frame ("pipe-file-descriptors");
2356 cmd = cmd->value.Connection->second;
2359 lastpid = last_made_pid;
2361 /* Now execute the rightmost command in the pipeline. */
2362 if (ignore_return && cmd)
2363 cmd->flags |= CMD_IGNORE_RETURN;
2367 begin_unwind_frame ("lastpipe-exec");
2369 /* If the `lastpipe' option is set with shopt, and job control is not
2370 enabled, execute the last element of non-async pipelines in the
2371 current shell environment. */
2372 if (lastpipe_opt && job_control == 0 && asynchronous == 0 && pipe_out == NO_PIPE && prev > 0)
2374 lstdin = move_to_high_fd (0, 1, -1);
2377 do_piping (prev, pipe_out);
2379 add_unwind_protect (restore_stdin, lstdin);
2381 freeze_jobs_list ();
2382 lastpipe_jid = stop_pipeline (0, (COMMAND *)NULL); /* XXX */
2383 add_unwind_protect (lastpipe_cleanup, lastpipe_jid);
2386 cmd->flags |= CMD_LASTPIPE;
2389 add_unwind_protect (close, prev);
2391 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2394 restore_stdin (lstdin);
2399 #if defined (JOB_CONTROL)
2400 UNBLOCK_CHILD (oset);
2407 #if defined (JOB_CONTROL)
2408 append_process (savestring (the_printed_command), dollar_dollar_pid, exec_result, lastpipe_jid);
2410 lstdin = wait_for (lastpid);
2411 #if defined (JOB_CONTROL)
2412 /* If wait_for removes the job from the jobs table, use result of last
2413 command as pipeline's exit status as usual. The jobs list can get
2414 frozen and unfrozen at inconvenient times if there are multiple pipelines
2415 running simultaneously. */
2416 if (INVALID_JOB (lastpipe_jid) == 0)
2417 exec_result = job_exit_status (lastpipe_jid);
2418 else if (pipefail_opt)
2419 exec_result = exec_result | lstdin; /* XXX */
2420 /* otherwise we use exec_result */
2423 unfreeze_jobs_list ();
2426 discard_unwind_frame ("lastpipe-exec");
2428 return (exec_result);
2432 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2434 int asynchronous, pipe_in, pipe_out;
2435 struct fd_bitmap *fds_to_close;
2437 COMMAND *tc, *second;
2438 int ignore_return, exec_result, was_error_trap, invert;
2439 volatile int save_line_number;
2441 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2443 switch (command->value.Connection->connector)
2445 /* Do the first command asynchronously. */
2447 tc = command->value.Connection->first;
2449 return (EXECUTION_SUCCESS);
2452 tc->flags |= CMD_IGNORE_RETURN;
2453 tc->flags |= CMD_AMPERSAND;
2455 /* If this shell was compiled without job control support,
2456 if we are currently in a subshell via `( xxx )', or if job
2457 control is not active then the standard input for an
2458 asynchronous command is forced to /dev/null. */
2459 #if defined (JOB_CONTROL)
2460 if ((subshell_environment || !job_control) && !stdin_redir)
2463 #endif /* JOB_CONTROL */
2464 tc->flags |= CMD_STDIN_REDIR;
2466 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2469 if (tc->flags & CMD_STDIN_REDIR)
2470 tc->flags &= ~CMD_STDIN_REDIR;
2472 second = command->value.Connection->second;
2476 second->flags |= CMD_IGNORE_RETURN;
2478 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2483 /* Just call execute command on both sides. */
2487 if (command->value.Connection->first)
2488 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2489 if (command->value.Connection->second)
2490 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2494 execute_command (command->value.Connection->first);
2496 exec_result = execute_command_internal (command->value.Connection->second,
2497 asynchronous, pipe_in, pipe_out,
2503 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2504 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2505 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2507 line_number_for_err_trap = line_number;
2508 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2510 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2512 last_command_exit_value = exec_result;
2513 save_line_number = line_number;
2514 line_number = line_number_for_err_trap;
2516 line_number = save_line_number;
2519 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2521 last_command_exit_value = exec_result;
2522 run_pending_traps ();
2523 jump_to_top_level (ERREXIT);
2532 /* If we have something like `a && b &' or `a || b &', run the
2533 && or || stuff in a subshell. Force a subshell and just call
2534 execute_command_internal again. Leave asynchronous on
2535 so that we get a report from the parent shell about the
2537 command->flags |= CMD_FORCE_SUBSHELL;
2538 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2542 /* Execute the first command. If the result of that is successful
2543 and the connector is AND_AND, or the result is not successful
2544 and the connector is OR_OR, then execute the second command,
2545 otherwise return. */
2548 if (command->value.Connection->first)
2549 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2551 exec_result = execute_command (command->value.Connection->first);
2553 if (((command->value.Connection->connector == AND_AND) &&
2554 (exec_result == EXECUTION_SUCCESS)) ||
2555 ((command->value.Connection->connector == OR_OR) &&
2556 (exec_result != EXECUTION_SUCCESS)))
2558 if (ignore_return && command->value.Connection->second)
2559 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2561 exec_result = execute_command (command->value.Connection->second);
2567 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2568 jump_to_top_level (DISCARD);
2569 exec_result = EXECUTION_FAILURE;
2578 if (!interactive_shell) \
2579 reap_dead_jobs (); \
2583 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2586 execute_for_command (for_command)
2587 FOR_COM *for_command;
2589 register WORD_LIST *releaser, *list;
2592 int retval, save_line_number;
2594 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2597 save_line_number = line_number;
2598 if (check_identifier (for_command->name, 1) == 0)
2600 if (posixly_correct && interactive_shell == 0)
2602 last_command_exit_value = EX_BADUSAGE;
2603 jump_to_top_level (ERREXIT);
2605 return (EXECUTION_FAILURE);
2609 identifier = for_command->name->word;
2611 line_number = for_command->line; /* for expansion error messages */
2612 list = releaser = expand_words_no_vars (for_command->map_list);
2614 begin_unwind_frame ("for");
2615 add_unwind_protect (dispose_words, releaser);
2618 if (lexical_scoping)
2620 old_value = copy_variable (find_variable (identifier));
2622 add_unwind_protect (dispose_variable, old_value);
2626 if (for_command->flags & CMD_IGNORE_RETURN)
2627 for_command->action->flags |= CMD_IGNORE_RETURN;
2629 for (retval = EXECUTION_SUCCESS; list; list = list->next)
2633 line_number = for_command->line;
2635 /* Remember what this command looks like, for debugger. */
2636 command_string_index = 0;
2637 print_for_command_head (for_command);
2639 if (echo_command_at_execute)
2640 xtrace_print_for_command_head (for_command);
2642 /* Save this command unless it's a trap command and we're not running
2644 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2646 FREE (the_printed_command_except_trap);
2647 the_printed_command_except_trap = savestring (the_printed_command);
2650 retval = run_debug_trap ();
2651 #if defined (DEBUGGER)
2652 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2653 skip the command. */
2654 if (debugging_mode && retval != EXECUTION_SUCCESS)
2658 this_command_name = (char *)NULL;
2659 /* XXX - special ksh93 for command index variable handling */
2660 v = find_variable_last_nameref (identifier);
2661 if (v && nameref_p (v))
2663 v = bind_variable_value (v, list->word->word, 0);
2666 v = bind_variable (identifier, list->word->word, 0);
2667 if (readonly_p (v) || noassign_p (v))
2669 line_number = save_line_number;
2670 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2672 last_command_exit_value = EXECUTION_FAILURE;
2673 jump_to_top_level (FORCE_EOF);
2677 dispose_words (releaser);
2678 discard_unwind_frame ("for");
2680 return (EXECUTION_FAILURE);
2683 retval = execute_command (for_command->action);
2702 line_number = save_line_number;
2705 if (lexical_scoping)
2708 unbind_variable (identifier);
2711 SHELL_VAR *new_value;
2713 new_value = bind_variable (identifier, value_cell(old_value), 0);
2714 new_value->attributes = old_value->attributes;
2715 dispose_variable (old_value);
2720 dispose_words (releaser);
2721 discard_unwind_frame ("for");
2725 #if defined (ARITH_FOR_COMMAND)
2726 /* Execute an arithmetic for command. The syntax is
2728 for (( init ; step ; test ))
2733 The execution should be exactly equivalent to
2736 while eval \(\( test \)\) ; do
2742 eval_arith_for_expr (l, okp)
2750 new = expand_words_no_vars (l);
2753 if (echo_command_at_execute)
2754 xtrace_print_arith_cmd (new);
2755 this_command_name = "(("; /* )) for expression error messages */
2757 command_string_index = 0;
2758 print_arith_command (new);
2759 if (signal_in_progress (DEBUG_TRAP) == 0)
2761 FREE (the_printed_command_except_trap);
2762 the_printed_command_except_trap = savestring (the_printed_command);
2765 r = run_debug_trap ();
2766 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2767 skip the command. */
2768 #if defined (DEBUGGER)
2769 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
2770 expresult = evalexp (new->word->word, okp);
2778 expresult = evalexp (new->word->word, okp);
2780 dispose_words (new);
2792 execute_arith_for_command (arith_for_command)
2793 ARITH_FOR_COM *arith_for_command;
2796 int expok, body_status, arith_lineno, save_lineno;
2798 body_status = EXECUTION_SUCCESS;
2800 save_lineno = line_number;
2802 if (arith_for_command->flags & CMD_IGNORE_RETURN)
2803 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
2805 this_command_name = "(("; /* )) for expression error messages */
2807 /* save the starting line number of the command so we can reset
2808 line_number before executing each expression -- for $LINENO
2809 and the DEBUG trap. */
2810 line_number = arith_lineno = arith_for_command->line;
2811 if (variable_context && interactive_shell)
2812 line_number -= function_line_number;
2814 /* Evaluate the initialization expression. */
2815 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
2818 line_number = save_lineno;
2819 return (EXECUTION_FAILURE);
2824 /* Evaluate the test expression. */
2825 line_number = arith_lineno;
2826 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
2827 line_number = save_lineno;
2831 body_status = EXECUTION_FAILURE;
2838 /* Execute the body of the arithmetic for command. */
2840 body_status = execute_command (arith_for_command->action);
2843 /* Handle any `break' or `continue' commands executed by the body. */
2857 /* Evaluate the step expression. */
2858 line_number = arith_lineno;
2859 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
2860 line_number = save_lineno;
2864 body_status = EXECUTION_FAILURE;
2870 line_number = save_lineno;
2872 return (body_status);
2876 #if defined (SELECT_COMMAND)
2877 static int LINES, COLS, tabsize;
2879 #define RP_SPACE ") "
2880 #define RP_SPACE_LEN 2
2882 /* XXX - does not handle numbers > 1000000 at all. */
2883 #define NUMBER_LEN(s) \
2887 : ((s < 10000) ? 4 \
2888 : ((s < 100000) ? 5 \
2895 #if defined (HANDLE_MULTIBYTE)
2901 slen = mbstowcs (wcstr, s, 0);
2904 wcstr = (wchar_t *)xmalloc (sizeof (wchar_t) * (slen + 1));
2905 mbstowcs (wcstr, s, slen + 1);
2906 wclen = wcswidth (wcstr, slen);
2908 return (wclen < 0 ? STRLEN(s) : wclen);
2910 return (STRLEN (s));
2915 print_index_and_element (len, ind, list)
2919 register WORD_LIST *l;
2924 for (i = ind, l = list; l && --i; l = l->next)
2926 if (l == 0) /* don't think this can happen */
2928 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
2929 return (displen (l->word->word));
2938 if ((to / tabsize) > (from / tabsize))
2940 putc ('\t', stderr);
2941 from += tabsize - from % tabsize;
2952 print_select_list (list, list_len, max_elem_len, indices_len)
2954 int list_len, max_elem_len, indices_len;
2956 int ind, row, elem_len, pos, cols, rows;
2957 int first_column_indices_len, other_indices_len;
2961 putc ('\n', stderr);
2965 cols = max_elem_len ? COLS / max_elem_len : 1;
2968 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
2969 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
2977 first_column_indices_len = NUMBER_LEN (rows);
2978 other_indices_len = indices_len;
2980 for (row = 0; row < rows; row++)
2986 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
2987 elem_len = print_index_and_element (indices_len, ind + 1, list);
2988 elem_len += indices_len + RP_SPACE_LEN;
2990 if (ind >= list_len)
2992 indent (pos + elem_len, pos + max_elem_len);
2993 pos += max_elem_len;
2995 putc ('\n', stderr);
2999 /* Print the elements of LIST, one per line, preceded by an index from 1 to
3000 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
3001 If the number is between 1 and LIST_LEN, return that selection. If EOF
3002 is read, return a null string. If a blank line is entered, or an invalid
3003 number is entered, the loop is executed again. */
3005 select_query (list, list_len, prompt, print_menu)
3011 int max_elem_len, indices_len, len;
3014 char *repl_string, *t;
3017 t = get_string_value ("LINES");
3018 LINES = (t && *t) ? atoi (t) : 24;
3020 t = get_string_value ("COLUMNS");
3021 COLS = (t && *t) ? atoi (t) : 80;
3024 t = get_string_value ("TABSIZE");
3025 tabsize = (t && *t) ? atoi (t) : 8;
3033 for (l = list; l; l = l->next)
3035 len = displen (l->word->word);
3036 if (len > max_elem_len)
3039 indices_len = NUMBER_LEN (list_len);
3040 max_elem_len += indices_len + RP_SPACE_LEN + 2;
3045 print_select_list (list, list_len, max_elem_len, indices_len);
3046 fprintf (stderr, "%s", prompt);
3050 if (read_builtin ((WORD_LIST *)NULL) != EXECUTION_SUCCESS)
3053 return ((char *)NULL);
3055 repl_string = get_string_value ("REPLY");
3056 if (*repl_string == 0)
3061 if (legal_number (repl_string, &reply) == 0)
3063 if (reply < 1 || reply > list_len)
3066 for (l = list; l && --reply; l = l->next)
3068 return (l->word->word); /* XXX - can't be null? */
3072 /* Execute a SELECT command. The syntax is:
3073 SELECT word IN list DO command_list DONE
3074 Only `break' or `return' in command_list will terminate
3077 execute_select_command (select_command)
3078 SELECT_COM *select_command;
3080 WORD_LIST *releaser, *list;
3082 char *identifier, *ps3_prompt, *selection;
3083 int retval, list_len, show_menu, save_line_number;
3085 if (check_identifier (select_command->name, 1) == 0)
3086 return (EXECUTION_FAILURE);
3088 save_line_number = line_number;
3089 line_number = select_command->line;
3091 command_string_index = 0;
3092 print_select_command_head (select_command);
3094 if (echo_command_at_execute)
3095 xtrace_print_select_command_head (select_command);
3098 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3100 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3103 FREE (the_printed_command_except_trap);
3104 the_printed_command_except_trap = savestring (the_printed_command);
3107 retval = run_debug_trap ();
3108 #if defined (DEBUGGER)
3109 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3110 skip the command. */
3111 if (debugging_mode && retval != EXECUTION_SUCCESS)
3112 return (EXECUTION_SUCCESS);
3116 identifier = select_command->name->word;
3118 /* command and arithmetic substitution, parameter and variable expansion,
3119 word splitting, pathname expansion, and quote removal. */
3120 list = releaser = expand_words_no_vars (select_command->map_list);
3121 list_len = list_length (list);
3122 if (list == 0 || list_len == 0)
3125 dispose_words (list);
3126 line_number = save_line_number;
3127 return (EXECUTION_SUCCESS);
3130 begin_unwind_frame ("select");
3131 add_unwind_protect (dispose_words, releaser);
3133 if (select_command->flags & CMD_IGNORE_RETURN)
3134 select_command->action->flags |= CMD_IGNORE_RETURN;
3136 retval = EXECUTION_SUCCESS;
3141 line_number = select_command->line;
3142 ps3_prompt = get_string_value ("PS3");
3143 if (ps3_prompt == 0)
3147 selection = select_query (list, list_len, ps3_prompt, show_menu);
3151 /* select_query returns EXECUTION_FAILURE if the read builtin
3152 fails, so we want to return failure in this case. */
3153 retval = EXECUTION_FAILURE;
3157 v = bind_variable (identifier, selection, 0);
3158 if (readonly_p (v) || noassign_p (v))
3160 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
3162 last_command_exit_value = EXECUTION_FAILURE;
3163 jump_to_top_level (FORCE_EOF);
3167 dispose_words (releaser);
3168 discard_unwind_frame ("select");
3170 line_number = save_line_number;
3171 return (EXECUTION_FAILURE);
3175 retval = execute_command (select_command->action);
3193 #if defined (KSH_COMPATIBLE_SELECT)
3195 selection = get_string_value ("REPLY");
3196 if (selection && *selection == '\0')
3202 line_number = save_line_number;
3204 dispose_words (releaser);
3205 discard_unwind_frame ("select");
3208 #endif /* SELECT_COMMAND */
3210 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
3211 The pattern_list is a linked list of pattern clauses; each clause contains
3212 some patterns to compare word_desc against, and an associated command to
3215 execute_case_command (case_command)
3216 CASE_COM *case_command;
3218 register WORD_LIST *list;
3219 WORD_LIST *wlist, *es;
3220 PATTERN_LIST *clauses;
3221 char *word, *pattern;
3222 int retval, match, ignore_return, save_line_number;
3224 save_line_number = line_number;
3225 line_number = case_command->line;
3227 command_string_index = 0;
3228 print_case_command_head (case_command);
3230 if (echo_command_at_execute)
3231 xtrace_print_case_command_head (case_command);
3234 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3236 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3239 FREE (the_printed_command_except_trap);
3240 the_printed_command_except_trap = savestring (the_printed_command);
3243 retval = run_debug_trap();
3244 #if defined (DEBUGGER)
3245 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3246 skip the command. */
3247 if (debugging_mode && retval != EXECUTION_SUCCESS)
3249 line_number = save_line_number;
3250 return (EXECUTION_SUCCESS);
3254 wlist = expand_word_unsplit (case_command->word, 0);
3255 word = wlist ? string_list (wlist) : savestring ("");
3256 dispose_words (wlist);
3258 retval = EXECUTION_SUCCESS;
3259 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
3261 begin_unwind_frame ("case");
3262 add_unwind_protect ((Function *)xfree, word);
3264 #define EXIT_CASE() goto exit_case_command
3266 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
3269 for (list = clauses->patterns; list; list = list->next)
3271 es = expand_word_leave_quoted (list->word, 0);
3273 if (es && es->word && es->word->word && *(es->word->word))
3274 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
3277 pattern = (char *)xmalloc (1);
3281 /* Since the pattern does not undergo quote removal (as per
3282 Posix.2, section 3.9.4.3), the strmatch () call must be able
3283 to recognize backslashes as escape characters. */
3284 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
3293 if (clauses->action && ignore_return)
3294 clauses->action->flags |= CMD_IGNORE_RETURN;
3295 retval = execute_command (clauses->action);
3297 while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3298 if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3310 discard_unwind_frame ("case");
3311 line_number = save_line_number;
3318 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3319 Repeatedly execute action while executing test produces
3320 EXECUTION_SUCCESS. */
3322 execute_while_command (while_command)
3323 WHILE_COM *while_command;
3325 return (execute_while_or_until (while_command, CMD_WHILE));
3328 /* UNTIL is just like WHILE except that the test result is negated. */
3330 execute_until_command (while_command)
3331 WHILE_COM *while_command;
3333 return (execute_while_or_until (while_command, CMD_UNTIL));
3336 /* The body for both while and until. The only difference between the
3337 two is that the test value is treated differently. TYPE is
3338 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3339 be EXECUTION_SUCCESS if no commands in the body are executed, and
3340 the status of the last command executed in the body otherwise. */
3342 execute_while_or_until (while_command, type)
3343 WHILE_COM *while_command;
3346 int return_value, body_status;
3348 body_status = EXECUTION_SUCCESS;
3351 while_command->test->flags |= CMD_IGNORE_RETURN;
3352 if (while_command->flags & CMD_IGNORE_RETURN)
3353 while_command->action->flags |= CMD_IGNORE_RETURN;
3357 return_value = execute_command (while_command->test);
3360 /* Need to handle `break' in the test when we would break out of the
3361 loop. The job control code will set `breaking' to loop_level
3362 when a job in a loop is stopped with SIGTSTP. If the stopped job
3363 is in the loop test, `breaking' will not be reset unless we do
3364 this, and the shell will cease to execute commands. */
3365 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3371 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3379 body_status = execute_command (while_command->action);
3397 return (body_status);
3400 /* IF test THEN command [ELSE command].
3401 IF also allows ELIF in the place of ELSE IF, but
3402 the parser makes *that* stupidity transparent. */
3404 execute_if_command (if_command)
3407 int return_value, save_line_number;
3409 save_line_number = line_number;
3410 if_command->test->flags |= CMD_IGNORE_RETURN;
3411 return_value = execute_command (if_command->test);
3412 line_number = save_line_number;
3414 if (return_value == EXECUTION_SUCCESS)
3418 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3419 if_command->true_case->flags |= CMD_IGNORE_RETURN;
3421 return (execute_command (if_command->true_case));
3427 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3428 if_command->false_case->flags |= CMD_IGNORE_RETURN;
3430 return (execute_command (if_command->false_case));
3434 #if defined (DPAREN_ARITHMETIC)
3436 execute_arith_command (arith_command)
3437 ARITH_COM *arith_command;
3439 int expok, save_line_number, retval;
3446 save_line_number = line_number;
3447 this_command_name = "(("; /* )) */
3448 line_number = arith_command->line;
3449 /* If we're in a function, update the line number information. */
3450 if (variable_context && interactive_shell)
3451 line_number -= function_line_number;
3453 command_string_index = 0;
3454 print_arith_command (arith_command->exp);
3456 if (signal_in_progress (DEBUG_TRAP) == 0)
3458 FREE (the_printed_command_except_trap);
3459 the_printed_command_except_trap = savestring (the_printed_command);
3462 /* Run the debug trap before each arithmetic command, but do it after we
3463 update the line number information and before we expand the various
3464 words in the expression. */
3465 retval = run_debug_trap ();
3466 #if defined (DEBUGGER)
3467 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3468 skip the command. */
3469 if (debugging_mode && retval != EXECUTION_SUCCESS)
3471 line_number = save_line_number;
3472 return (EXECUTION_SUCCESS);
3476 new = expand_words_no_vars (arith_command->exp);
3478 /* If we're tracing, make a new word list with `((' at the front and `))'
3479 at the back and print it. */
3480 if (echo_command_at_execute)
3481 xtrace_print_arith_cmd (new);
3485 exp = new->next ? string_list (new) : new->word->word;
3486 expresult = evalexp (exp, &expok);
3487 line_number = save_line_number;
3488 if (exp != new->word->word)
3490 dispose_words (new);
3499 return (EXECUTION_FAILURE);
3501 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3503 #endif /* DPAREN_ARITHMETIC */
3505 #if defined (COND_COMMAND)
3507 static char * const nullstr = "";
3509 /* XXX - can COND ever be NULL when this is called? */
3511 execute_cond_node (cond)
3514 int result, invert, patmatch, rmatch, mflags, ignore;
3520 invert = (cond->flags & CMD_INVERT_RETURN);
3521 ignore = (cond->flags & CMD_IGNORE_RETURN);
3525 cond->left->flags |= CMD_IGNORE_RETURN;
3527 cond->right->flags |= CMD_IGNORE_RETURN;
3530 if (cond->type == COND_EXPR)
3531 result = execute_cond_node (cond->left);
3532 else if (cond->type == COND_OR)
3534 result = execute_cond_node (cond->left);
3535 if (result != EXECUTION_SUCCESS)
3536 result = execute_cond_node (cond->right);
3538 else if (cond->type == COND_AND)
3540 result = execute_cond_node (cond->left);
3541 if (result == EXECUTION_SUCCESS)
3542 result = execute_cond_node (cond->right);
3544 else if (cond->type == COND_UNARY)
3547 comsub_ignore_return++;
3548 arg1 = cond_expand_word (cond->left->op, 0);
3550 comsub_ignore_return--;
3553 if (echo_command_at_execute)
3554 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3555 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3556 if (arg1 != nullstr)
3559 else if (cond->type == COND_BINARY)
3562 patmatch = (((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3563 (cond->op->word[0] == '!' || cond->op->word[0] == '=')) ||
3564 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3565 #if defined (COND_REGEXP)
3566 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3567 cond->op->word[2] == '\0');
3571 comsub_ignore_return++;
3572 arg1 = cond_expand_word (cond->left->op, 0);
3574 comsub_ignore_return--;
3578 comsub_ignore_return++;
3579 arg2 = cond_expand_word (cond->right->op,
3580 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3582 comsub_ignore_return--;
3586 if (echo_command_at_execute)
3587 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3589 #if defined (COND_REGEXP)
3592 mflags = SHMAT_PWARN;
3593 #if defined (ARRAY_VARS)
3594 mflags |= SHMAT_SUBEXP;
3598 t1 = strescape(arg1);
3599 t2 = strescape(arg2);
3600 itrace("execute_cond_node: sh_regmatch on `%s' and `%s'", t1, t2);
3605 result = sh_regmatch (arg1, arg2, mflags);
3608 #endif /* COND_REGEXP */
3613 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3615 : EXECUTION_FAILURE;
3618 if (arg1 != nullstr)
3620 if (arg2 != nullstr)
3625 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3626 jump_to_top_level (DISCARD);
3627 result = EXECUTION_FAILURE;
3631 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3637 execute_cond_command (cond_command)
3638 COND_COM *cond_command;
3640 int retval, save_line_number;
3642 retval = EXECUTION_SUCCESS;
3643 save_line_number = line_number;
3645 this_command_name = "[[";
3646 line_number = cond_command->line;
3647 /* If we're in a function, update the line number information. */
3648 if (variable_context && interactive_shell)
3649 line_number -= function_line_number;
3650 command_string_index = 0;
3651 print_cond_command (cond_command);
3653 if (signal_in_progress (DEBUG_TRAP) == 0)
3655 FREE (the_printed_command_except_trap);
3656 the_printed_command_except_trap = savestring (the_printed_command);
3659 /* Run the debug trap before each conditional command, but do it after we
3660 update the line number information. */
3661 retval = run_debug_trap ();
3662 #if defined (DEBUGGER)
3663 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3664 skip the command. */
3665 if (debugging_mode && retval != EXECUTION_SUCCESS)
3667 line_number = save_line_number;
3668 return (EXECUTION_SUCCESS);
3673 debug_print_cond_command (cond_command);
3676 last_command_exit_value = retval = execute_cond_node (cond_command);
3677 line_number = save_line_number;
3680 #endif /* COND_COMMAND */
3690 var = bind_variable ("_", arg, 0);
3691 VUNSETATTR (var, att_exported);
3694 /* Execute a null command. Fork a subshell if the command uses pipes or is
3695 to be run asynchronously. This handles all the side effects that are
3696 supposed to take place. */
3698 execute_null_command (redirects, pipe_in, pipe_out, async)
3699 REDIRECT *redirects;
3700 int pipe_in, pipe_out, async;
3706 for (forcefork = 0, rd = redirects; rd; rd = rd->next)
3707 forcefork += rd->rflags & REDIR_VARASSIGN;
3709 if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
3711 /* We have a null command, but we really want a subshell to take
3712 care of it. Just fork, do piping and redirections, and exit. */
3713 if (make_child ((char *)NULL, async) == 0)
3715 /* Cancel traps, in trap.c. */
3716 restore_original_signals (); /* XXX */
3718 do_piping (pipe_in, pipe_out);
3720 #if defined (COPROCESS_SUPPORT)
3724 subshell_environment = 0;
3726 subshell_environment |= SUBSHELL_ASYNC;
3727 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3728 subshell_environment |= SUBSHELL_PIPE;
3730 if (do_redirections (redirects, RX_ACTIVE) == 0)
3731 exit (EXECUTION_SUCCESS);
3733 exit (EXECUTION_FAILURE);
3737 close_pipes (pipe_in, pipe_out);
3738 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3739 if (pipe_out == NO_PIPE)
3740 unlink_fifo_list ();
3742 return (EXECUTION_SUCCESS);
3747 /* Even if there aren't any command names, pretend to do the
3748 redirections that are specified. The user expects the side
3749 effects to take place. If the redirections fail, then return
3750 failure. Otherwise, if a command substitution took place while
3751 expanding the command or a redirection, return the value of that
3752 substitution. Otherwise, return EXECUTION_SUCCESS. */
3754 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
3755 cleanup_redirects (redirection_undo_list);
3756 redirection_undo_list = (REDIRECT *)NULL;
3759 return (EXECUTION_FAILURE);
3760 else if (last_command_subst_pid != NO_PID)
3761 return (last_command_exit_value);
3763 return (EXECUTION_SUCCESS);
3767 /* This is a hack to suppress word splitting for assignment statements
3768 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3770 fix_assignment_words (words)
3773 WORD_LIST *w, *wcmd;
3775 int assoc, global, array, integer;
3781 assoc = global = array = integer = 0;
3783 /* Skip over assignment statements preceding a command name */
3785 for (wcmd = words; wcmd; wcmd = wcmd->next)
3786 if ((wcmd->word->flags & W_ASSIGNMENT) == 0)
3789 for (w = wcmd; w; w = w->next)
3790 if (w->word->flags & W_ASSIGNMENT)
3794 /* Posix (post-2008) says that `command' doesn't change whether
3795 or not the builtin it shadows is a `declaration command', even
3796 though it removes other special builtin properties. In Posix
3797 mode, we skip over one or more instances of `command' and
3798 deal with the next word as the assignment builtin. */
3799 while (posixly_correct && wcmd && wcmd->word && wcmd->word->word && STREQ (wcmd->word->word, "command"))
3801 b = builtin_address_internal (wcmd->word->word, 0);
3802 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3804 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3805 wcmd->word->flags |= W_ASSNBLTIN;
3807 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
3808 #if defined (ARRAY_VARS)
3810 w->word->flags |= W_ASSIGNASSOC;
3812 w->word->flags |= W_ASSIGNARRAY;
3815 w->word->flags |= W_ASSNGLOBAL;
3817 w->word->flags |= W_ASSIGNINT;
3819 #if defined (ARRAY_VARS)
3820 /* Note that we saw an associative array option to a builtin that takes
3821 assignment statements. This is a bit of a kludge. */
3822 else if (w->word->word[0] == '-' && (strchr (w->word->word+1, 'A') || strchr (w->word->word+1, 'a') || strchr (w->word->word+1, 'g')))
3824 else if (w->word->word[0] == '-' && strchr (w->word->word+1, 'g'))
3829 while (posixly_correct && wcmd && wcmd->word && wcmd->word->word && STREQ (wcmd->word->word, "command"))
3831 b = builtin_address_internal (wcmd->word->word, 0);
3832 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3834 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3835 wcmd->word->flags |= W_ASSNBLTIN;
3837 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'A'))
3839 else if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'a'))
3841 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'g'))
3843 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'i'))
3848 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3849 to PATHNAME, is a directory. Used by the autocd code below. */
3851 is_dirname (pathname)
3857 temp = search_for_command (pathname, 0);
3858 ret = (temp ? file_isdir (temp) : file_isdir (pathname));
3863 /* The meaty part of all the executions. We have to start hacking the
3864 real execution of commands here. Fork a process, set things up,
3865 execute the command. */
3867 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
3868 SIMPLE_COM *simple_command;
3869 int pipe_in, pipe_out, async;
3870 struct fd_bitmap *fds_to_close;
3872 WORD_LIST *words, *lastword;
3873 char *command_line, *lastarg, *temp;
3874 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
3875 pid_t old_last_async_pid;
3876 sh_builtin_func_t *builtin;
3878 volatile int old_builtin, old_command_builtin;
3880 result = EXECUTION_SUCCESS;
3881 special_builtin_failed = builtin_is_special = 0;
3882 command_line = (char *)0;
3886 /* If we're in a function, update the line number information. */
3887 if (variable_context && interactive_shell && sourcelevel == 0)
3888 line_number -= function_line_number;
3890 /* Remember what this command line looks like at invocation. */
3891 command_string_index = 0;
3892 print_simple_command (simple_command);
3895 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3897 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3900 FREE (the_printed_command_except_trap);
3901 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
3904 /* Run the debug trap before each simple command, but do it after we
3905 update the line number information. */
3906 result = run_debug_trap ();
3907 #if defined (DEBUGGER)
3908 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3909 skip the command. */
3910 if (debugging_mode && result != EXECUTION_SUCCESS)
3911 return (EXECUTION_SUCCESS);
3915 simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
3917 last_command_subst_pid = NO_PID;
3918 old_last_async_pid = last_asynchronous_pid;
3920 already_forked = dofork = 0;
3922 /* If we're in a pipeline or run in the background, set DOFORK so we
3923 make the child early, before word expansion. This keeps assignment
3924 statements from affecting the parent shell's environment when they
3926 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
3928 /* Something like `%2 &' should restart job 2 in the background, not cause
3929 the shell to fork here. */
3930 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
3931 simple_command->words && simple_command->words->word &&
3932 simple_command->words->word->word &&
3933 (simple_command->words->word->word[0] == '%'))
3938 /* Do this now, because execute_disk_command will do it anyway in the
3939 vast majority of cases. */
3940 maybe_make_export_env ();
3942 /* Don't let a DEBUG trap overwrite the command string to be saved with
3943 the process/job associated with this child. */
3944 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
3947 simple_command->flags |= CMD_NO_FORK;
3949 subshell_environment = SUBSHELL_FORK;
3950 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3951 subshell_environment |= SUBSHELL_PIPE;
3953 subshell_environment |= SUBSHELL_ASYNC;
3955 /* We need to do this before piping to handle some really
3956 pathological cases where one of the pipe file descriptors
3959 close_fd_bitmap (fds_to_close);
3961 do_piping (pipe_in, pipe_out);
3962 pipe_in = pipe_out = NO_PIPE;
3963 #if defined (COPROCESS_SUPPORT)
3967 last_asynchronous_pid = old_last_async_pid;
3973 /* Don't let simple commands that aren't the last command in a
3974 pipeline change $? for the rest of the pipeline (or at all). */
3975 if (pipe_out != NO_PIPE)
3976 result = last_command_exit_value;
3977 close_pipes (pipe_in, pipe_out);
3978 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3979 /* Close /dev/fd file descriptors in the parent after forking the
3980 last child in a (possibly one-element) pipeline. Defer this
3981 until any running shell function completes. */
3982 if (pipe_out == NO_PIPE && variable_context == 0) /* XXX */
3983 unlink_fifo_list (); /* XXX */
3985 command_line = (char *)NULL; /* don't free this. */
3986 bind_lastarg ((char *)NULL);
3991 /* If we are re-running this as the result of executing the `command'
3992 builtin, do not expand the command words a second time. */
3993 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
3995 current_fds_to_close = fds_to_close;
3996 fix_assignment_words (simple_command->words);
3997 /* Pass the ignore return flag down to command substitutions */
3998 if (simple_command->flags & CMD_IGNORE_RETURN) /* XXX */
3999 comsub_ignore_return++;
4000 words = expand_words (simple_command->words);
4001 if (simple_command->flags & CMD_IGNORE_RETURN)
4002 comsub_ignore_return--;
4003 current_fds_to_close = (struct fd_bitmap *)NULL;
4006 words = copy_word_list (simple_command->words);
4008 /* It is possible for WORDS not to have anything left in it.
4009 Perhaps all the words consisted of `$foo', and there was
4010 no variable `$foo'. */
4013 this_command_name = 0;
4014 result = execute_null_command (simple_command->redirects,
4016 already_forked ? 0 : async);
4021 bind_lastarg ((char *)NULL);
4022 set_pipestatus_from_exit (result);
4027 lastarg = (char *)NULL;
4029 begin_unwind_frame ("simple-command");
4031 if (echo_command_at_execute)
4032 xtrace_print_word_list (words, 1);
4034 builtin = (sh_builtin_func_t *)NULL;
4035 func = (SHELL_VAR *)NULL;
4036 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
4038 /* Posix.2 says special builtins are found before functions. We
4039 don't set builtin_is_special anywhere other than here, because
4040 this path is followed only when the `command' builtin is *not*
4041 being used, and we don't want to exit the shell if a special
4042 builtin executed with `command builtin' fails. `command' is not
4043 a special builtin. */
4044 if (posixly_correct)
4046 builtin = find_special_builtin (words->word->word);
4048 builtin_is_special = 1;
4051 func = find_function (words->word->word);
4054 /* In POSIX mode, assignment errors in the temporary environment cause a
4055 non-interactive shell to exit. */
4056 if (posixly_correct && builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
4058 last_command_exit_value = EXECUTION_FAILURE;
4059 jump_to_top_level (ERREXIT);
4061 tempenv_assign_error = 0; /* don't care about this any more */
4063 add_unwind_protect (dispose_words, words);
4066 /* Bind the last word in this command to "$_" after execution. */
4067 for (lastword = words; lastword->next; lastword = lastword->next)
4069 lastarg = lastword->word->word;
4071 #if defined (JOB_CONTROL)
4072 /* Is this command a job control related thing? */
4073 if (words->word->word[0] == '%' && already_forked == 0)
4075 this_command_name = async ? "bg" : "fg";
4076 last_shell_builtin = this_shell_builtin;
4077 this_shell_builtin = builtin_address (this_command_name);
4078 result = (*this_shell_builtin) (words);
4082 /* One other possibililty. The user may want to resume an existing job.
4083 If they do, find out whether this word is a candidate for a running
4085 if (job_control && already_forked == 0 && async == 0 &&
4086 !first_word_quoted &&
4088 words->word->word[0] &&
4089 !simple_command->redirects &&
4090 pipe_in == NO_PIPE &&
4091 pipe_out == NO_PIPE &&
4092 (temp = get_string_value ("auto_resume")))
4094 int job, jflags, started_status;
4096 jflags = JM_STOPPED|JM_FIRSTMATCH;
4097 if (STREQ (temp, "exact"))
4099 else if (STREQ (temp, "substring"))
4100 jflags |= JM_SUBSTRING;
4102 jflags |= JM_PREFIX;
4103 job = get_job_by_name (words->word->word, jflags);
4106 run_unwind_frame ("simple-command");
4107 this_command_name = "fg";
4108 last_shell_builtin = this_shell_builtin;
4109 this_shell_builtin = builtin_address ("fg");
4111 started_status = start_job (job, 1);
4112 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
4115 #endif /* JOB_CONTROL */
4118 /* Remember the name of this command globally. */
4119 this_command_name = words->word->word;
4123 /* This command could be a shell builtin or a user-defined function.
4124 We have already found special builtins by this time, so we do not
4125 set builtin_is_special. If this is a function or builtin, and we
4126 have pipes, then fork a subshell in here. Otherwise, just execute
4127 the command directly. */
4128 if (func == 0 && builtin == 0)
4129 builtin = find_shell_builtin (this_command_name);
4131 last_shell_builtin = this_shell_builtin;
4132 this_shell_builtin = builtin;
4134 if (builtin || func)
4138 old_builtin = executing_builtin;
4139 old_command_builtin = executing_command_builtin;
4140 unwind_protect_int (executing_builtin); /* modified in execute_builtin */
4141 unwind_protect_int (executing_command_builtin); /* ditto */
4145 /* reset_terminating_signals (); */ /* XXX */
4146 /* Reset the signal handlers in the child, but don't free the
4147 trap strings. Set a flag noting that we have to free the
4148 trap strings if we run trap to change a signal disposition. */
4149 reset_signal_handlers ();
4150 subshell_environment |= SUBSHELL_RESETTRAP;
4154 if ((simple_command->flags & CMD_STDIN_REDIR) &&
4155 pipe_in == NO_PIPE &&
4156 (stdin_redirects (simple_command->redirects) == 0))
4157 async_redirect_stdin ();
4158 setup_async_signals ();
4162 execute_subshell_builtin_or_function
4163 (words, simple_command->redirects, builtin, func,
4164 pipe_in, pipe_out, async, fds_to_close,
4165 simple_command->flags);
4170 result = execute_builtin_or_function
4171 (words, builtin, func, simple_command->redirects, fds_to_close,
4172 simple_command->flags);
4175 if (result > EX_SHERRBASE)
4182 /* These errors cause non-interactive posix mode shells to exit */
4183 if (posixly_correct && builtin_is_special && interactive_shell == 0)
4185 last_command_exit_value = EXECUTION_FAILURE;
4186 jump_to_top_level (ERREXIT);
4189 result = builtin_status (result);
4190 if (builtin_is_special)
4191 special_builtin_failed = 1;
4193 /* In POSIX mode, if there are assignment statements preceding
4194 a special builtin, they persist after the builtin
4196 if (posixly_correct && builtin_is_special && temporary_env)
4197 merge_temporary_env ();
4201 if (result == EX_USAGE)
4202 result = EX_BADUSAGE;
4203 else if (result > EX_SHERRBASE)
4204 result = EXECUTION_FAILURE;
4207 set_pipestatus_from_exit (result);
4213 if (autocd && interactive && words->word && is_dirname (words->word->word))
4215 words = make_word_list (make_word ("cd"), words);
4216 xtrace_print_word_list (words, 0);
4220 if (command_line == 0)
4221 command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
4223 #if defined (PROCESS_SUBSTITUTION)
4224 if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
4225 simple_command->flags &= ~CMD_NO_FORK;
4228 result = execute_disk_command (words, simple_command->redirects, command_line,
4229 pipe_in, pipe_out, async, fds_to_close,
4230 simple_command->flags);
4233 bind_lastarg (lastarg);
4234 FREE (command_line);
4235 dispose_words (words);
4238 executing_builtin = old_builtin;
4239 executing_command_builtin = old_command_builtin;
4241 discard_unwind_frame ("simple-command");
4242 this_command_name = (char *)NULL; /* points to freed memory now */
4246 /* Translate the special builtin exit statuses. We don't really need a
4247 function for this; it's a placeholder for future work. */
4249 builtin_status (result)
4263 r = EXECUTION_FAILURE;
4266 r = EXECUTION_SUCCESS;
4273 execute_builtin (builtin, words, flags, subshell)
4274 sh_builtin_func_t *builtin;
4276 int flags, subshell;
4278 int old_e_flag, result, eval_unwind;
4283 old_e_flag = exit_immediately_on_error;
4285 /* The eval builtin calls parse_and_execute, which does not know about
4286 the setting of flags, and always calls the execution functions with
4287 flags that will exit the shell on an error if -e is set. If the
4288 eval builtin is being called, and we're supposed to ignore the exit
4289 value of the command, we turn the -e flag off ourselves and disable
4290 the ERR trap, then restore them when the command completes. This is
4291 also a problem (as below) for the command and source/. builtins. */
4292 if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
4293 (builtin == eval_builtin || builtin == command_builtin || builtin == source_builtin))
4295 begin_unwind_frame ("eval_builtin");
4296 unwind_protect_int (exit_immediately_on_error);
4297 unwind_protect_int (builtin_ignoring_errexit);
4298 error_trap = TRAP_STRING (ERROR_TRAP);
4301 error_trap = savestring (error_trap);
4302 add_unwind_protect (xfree, error_trap);
4303 add_unwind_protect (set_error_trap, error_trap);
4304 restore_default_signal (ERROR_TRAP);
4306 exit_immediately_on_error = 0;
4307 builtin_ignoring_errexit = 1;
4313 /* The temporary environment for a builtin is supposed to apply to
4314 all commands executed by that builtin. Currently, this is a
4315 problem only with the `unset', `source' and `eval' builtins.
4316 `mapfile' is a special case because it uses evalstring (same as
4317 eval or source) to run its callbacks. */
4318 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin || builtin == mapfile_builtin);
4323 begin_unwind_frame ("builtin_env");
4327 push_scope (VC_BLTNENV, temporary_env);
4329 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
4330 temporary_env = (HASH_TABLE *)NULL;
4334 /* `return' does a longjmp() back to a saved environment in execute_function.
4335 If a variable assignment list preceded the command, and the shell is
4336 running in POSIX mode, we need to merge that into the shell_variables
4337 table, since `return' is a POSIX special builtin. */
4338 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4340 begin_unwind_frame ("return_temp_env");
4341 add_unwind_protect (merge_temporary_env, (char *)NULL);
4344 executing_builtin++;
4345 executing_command_builtin |= builtin == command_builtin;
4346 result = ((*builtin) (words->next));
4348 /* This shouldn't happen, but in case `return' comes back instead of
4349 longjmp'ing, we need to unwind. */
4350 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4351 discard_unwind_frame ("return_temp_env");
4353 if (subshell == 0 && isbltinenv)
4354 run_unwind_frame ("builtin_env");
4358 exit_immediately_on_error = errexit_flag;
4359 builtin_ignoring_errexit = 0;
4362 set_error_trap (error_trap);
4365 discard_unwind_frame ("eval_builtin");
4372 execute_function (var, words, flags, fds_to_close, async, subshell)
4376 struct fd_bitmap *fds_to_close;
4377 int async, subshell;
4379 int return_val, result;
4380 COMMAND *tc, *fc, *save_current;
4381 char *debug_trap, *error_trap, *return_trap;
4382 #if defined (ARRAY_VARS)
4383 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
4385 volatile ARRAY *bash_source_a;
4386 volatile ARRAY *bash_lineno_a;
4388 FUNCTION_DEF *shell_fn;
4393 if (funcnest_max > 0 && funcnest >= funcnest_max)
4395 internal_error (_("%s: maximum function nesting level exceeded (%d)"), var->name, funcnest);
4396 funcnest = 0; /* XXX - should we reset it somewhere else? */
4397 jump_to_top_level (DISCARD);
4400 #if defined (ARRAY_VARS)
4401 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4402 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4403 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4406 tc = (COMMAND *)copy_command (function_cell (var));
4407 if (tc && (flags & CMD_IGNORE_RETURN))
4408 tc->flags |= CMD_IGNORE_RETURN;
4412 begin_unwind_frame ("function_calling");
4413 push_context (var->name, subshell, temporary_env);
4414 add_unwind_protect (pop_context, (char *)NULL);
4415 unwind_protect_int (line_number);
4416 unwind_protect_int (return_catch_flag);
4417 unwind_protect_jmp_buf (return_catch);
4418 add_unwind_protect (dispose_command, (char *)tc);
4419 unwind_protect_pointer (this_shell_function);
4420 unwind_protect_int (loop_level);
4421 unwind_protect_int (funcnest);
4424 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
4426 temporary_env = (HASH_TABLE *)NULL;
4428 this_shell_function = var;
4429 make_funcname_visible (1);
4431 debug_trap = TRAP_STRING(DEBUG_TRAP);
4432 error_trap = TRAP_STRING(ERROR_TRAP);
4433 return_trap = TRAP_STRING(RETURN_TRAP);
4435 /* The order of the unwind protects for debug_trap, error_trap and
4436 return_trap is important here! unwind-protect commands are run
4437 in reverse order of registration. If this causes problems, take
4438 out the xfree unwind-protect calls and live with the small memory leak. */
4440 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4441 if the function has the trace attribute set, it inherits the DEBUG trap */
4442 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4446 debug_trap = savestring (debug_trap);
4447 add_unwind_protect (xfree, debug_trap);
4448 add_unwind_protect (set_debug_trap, debug_trap);
4450 restore_default_signal (DEBUG_TRAP);
4453 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4454 if (error_trap && error_trace_mode == 0)
4458 error_trap = savestring (error_trap);
4459 add_unwind_protect (xfree, error_trap);
4460 add_unwind_protect (set_error_trap, error_trap);
4462 restore_default_signal (ERROR_TRAP);
4465 /* Shell functions inherit the RETURN trap if function tracing is on
4466 globally or on individually for this function. */
4468 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4470 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
4475 return_trap = savestring (return_trap);
4476 add_unwind_protect (xfree, return_trap);
4477 add_unwind_protect (set_return_trap, return_trap);
4479 restore_default_signal (RETURN_TRAP);
4483 #if defined (ARRAY_VARS)
4484 /* This is quite similar to the code in shell.c and elsewhere. */
4485 shell_fn = find_function_def (this_shell_function->name);
4486 sfile = shell_fn ? shell_fn->source_file : "";
4487 array_push ((ARRAY *)funcname_a, this_shell_function->name);
4489 array_push ((ARRAY *)bash_source_a, sfile);
4490 t = itos (executing_line_number ());
4491 array_push ((ARRAY *)bash_lineno_a, t);
4495 /* The temporary environment for a function is supposed to apply to
4496 all commands executed within the function body. */
4498 remember_args (words->next, 1);
4500 /* Update BASH_ARGV and BASH_ARGC */
4502 push_args (words->next);
4504 /* Number of the line on which the function body starts. */
4505 line_number = function_line_number = tc->line;
4507 #if defined (JOB_CONTROL)
4509 stop_pipeline (async, (COMMAND *)NULL);
4514 return_catch_flag++;
4515 return_val = setjmp_nosigs (return_catch);
4519 result = return_catch_value;
4520 /* Run the RETURN trap in the function's context. */
4521 save_current = currently_executing_command;
4523 currently_executing_command = save_current;
4527 /* Run the debug trap here so we can trap at the start of a function's
4528 execution rather than the execution of the body's first command. */
4529 showing_function_line = 1;
4530 save_current = currently_executing_command;
4531 result = run_debug_trap ();
4532 #if defined (DEBUGGER)
4533 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4534 skip the command. */
4535 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
4537 showing_function_line = 0;
4538 currently_executing_command = save_current;
4539 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4541 /* Run the RETURN trap in the function's context */
4542 save_current = currently_executing_command;
4544 currently_executing_command = save_current;
4547 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4549 save_current = currently_executing_command;
4551 currently_executing_command = save_current;
4553 showing_function_line = 0;
4556 /* Restore BASH_ARGC and BASH_ARGV */
4561 run_unwind_frame ("function_calling");
4563 #if defined (ARRAY_VARS)
4564 /* These two variables cannot be unset, and cannot be affected by the
4566 array_pop ((ARRAY *)bash_source_a);
4567 array_pop ((ARRAY *)bash_lineno_a);
4569 /* FUNCNAME can be unset, and so can potentially be changed by the
4571 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4572 if (nfv == funcname_v)
4573 array_pop (funcname_a);
4576 if (variable_context == 0 || this_shell_function == 0)
4578 make_funcname_visible (0);
4579 #if defined (PROCESS_SUBSTITUTION)
4580 unlink_fifo_list ();
4587 /* A convenience routine for use by other parts of the shell to execute
4588 a particular shell function. */
4590 execute_shell_function (var, words)
4595 struct fd_bitmap *bitmap;
4597 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
4598 begin_unwind_frame ("execute-shell-function");
4599 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
4601 ret = execute_function (var, words, 0, bitmap, 0, 0);
4603 dispose_fd_bitmap (bitmap);
4604 discard_unwind_frame ("execute-shell-function");
4609 /* Execute a shell builtin or function in a subshell environment. This
4610 routine does not return; it only calls exit(). If BUILTIN is non-null,
4611 it points to a function to call to execute a shell builtin; otherwise
4612 VAR points at the body of a function to execute. WORDS is the arguments
4613 to the command, REDIRECTS specifies redirections to perform before the
4614 command is executed. */
4616 execute_subshell_builtin_or_function (words, redirects, builtin, var,
4617 pipe_in, pipe_out, async, fds_to_close,
4620 REDIRECT *redirects;
4621 sh_builtin_func_t *builtin;
4623 int pipe_in, pipe_out, async;
4624 struct fd_bitmap *fds_to_close;
4627 int result, r, funcvalue;
4628 #if defined (JOB_CONTROL)
4631 jobs_hack = (builtin == jobs_builtin) &&
4632 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
4635 /* A subshell is neither a login shell nor interactive. */
4636 login_shell = interactive = 0;
4639 subshell_environment |= SUBSHELL_ASYNC;
4640 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4641 subshell_environment |= SUBSHELL_PIPE;
4643 maybe_make_export_env (); /* XXX - is this needed? */
4645 #if defined (JOB_CONTROL)
4646 /* Eradicate all traces of job control after we fork the subshell, so
4647 all jobs begun by this subshell are in the same process group as
4648 the shell itself. */
4650 /* Allow the output of `jobs' to be piped. */
4652 kill_current_pipeline ();
4654 without_job_control ();
4656 set_sigchld_handler ();
4657 #endif /* JOB_CONTROL */
4659 set_sigint_handler ();
4662 close_fd_bitmap (fds_to_close);
4664 do_piping (pipe_in, pipe_out);
4666 if (do_redirections (redirects, RX_ACTIVE) != 0)
4667 exit (EXECUTION_FAILURE);
4671 /* Give builtins a place to jump back to on failure,
4672 so we don't go back up to main(). */
4673 result = setjmp_nosigs (top_level);
4675 /* Give the return builtin a place to jump to when executed in a subshell
4678 if (return_catch_flag && builtin == return_builtin)
4679 funcvalue = setjmp_nosigs (return_catch);
4681 if (result == EXITPROG)
4682 exit (last_command_exit_value);
4684 exit (EXECUTION_FAILURE);
4686 exit (return_catch_value);
4689 r = execute_builtin (builtin, words, flags, 1);
4698 r = execute_function (var, words, flags, fds_to_close, async, 1);
4704 /* Execute a builtin or function in the current shell context. If BUILTIN
4705 is non-null, it is the builtin command to execute, otherwise VAR points
4706 to the body of a function. WORDS are the command's arguments, REDIRECTS
4707 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4708 file descriptors to close.
4710 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4711 not undone before this function returns. */
4713 execute_builtin_or_function (words, builtin, var, redirects,
4714 fds_to_close, flags)
4716 sh_builtin_func_t *builtin;
4718 REDIRECT *redirects;
4719 struct fd_bitmap *fds_to_close;
4723 REDIRECT *saved_undo_list;
4724 #if defined (PROCESS_SUBSTITUTION)
4725 int ofifo, nfifo, osize;
4730 #if defined (PROCESS_SUBSTITUTION)
4731 ofifo = num_fifos ();
4732 ofifo_list = copy_fifo_list (&osize);
4735 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
4737 cleanup_redirects (redirection_undo_list);
4738 redirection_undo_list = (REDIRECT *)NULL;
4739 dispose_exec_redirects ();
4740 #if defined (PROCESS_SUBSTITUTION)
4743 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
4746 saved_undo_list = redirection_undo_list;
4748 /* Calling the "exec" builtin changes redirections forever. */
4749 if (builtin == exec_builtin)
4751 dispose_redirects (saved_undo_list);
4752 saved_undo_list = exec_redirection_undo_list;
4753 exec_redirection_undo_list = (REDIRECT *)NULL;
4756 dispose_exec_redirects ();
4758 if (saved_undo_list)
4760 begin_unwind_frame ("saved redirects");
4761 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
4764 redirection_undo_list = (REDIRECT *)NULL;
4767 result = execute_builtin (builtin, words, flags, 0);
4769 result = execute_function (var, words, flags, fds_to_close, 0, 0);
4771 /* We do this before undoing the effects of any redirections. */
4774 if (ferror (stdout))
4777 /* If we are executing the `command' builtin, but this_shell_builtin is
4778 set to `exec_builtin', we know that we have something like
4779 `command exec [redirection]', since otherwise `exec' would have
4780 overwritten the shell and we wouldn't get here. In this case, we
4781 want to behave as if the `command' builtin had not been specified
4782 and preserve the redirections. */
4783 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
4788 if (saved_undo_list)
4790 dispose_redirects (saved_undo_list);
4793 redirection_undo_list = exec_redirection_undo_list;
4794 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
4796 discard_unwind_frame ("saved redirects");
4799 if (saved_undo_list)
4801 redirection_undo_list = saved_undo_list;
4802 discard_unwind_frame ("saved redirects");
4805 if (redirection_undo_list)
4807 cleanup_redirects (redirection_undo_list);
4808 redirection_undo_list = (REDIRECT *)NULL;
4811 #if defined (PROCESS_SUBSTITUTION)
4812 /* Close any FIFOs created by this builtin or function. */
4813 nfifo = num_fifos ();
4815 close_new_fifos (ofifo_list, osize);
4823 setup_async_signals ()
4825 #if defined (__BEOS__)
4826 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
4829 #if defined (JOB_CONTROL)
4830 if (job_control == 0)
4833 /* Make sure we get the original signal dispositions now so we don't
4834 confuse the trap builtin later if the subshell tries to use it to
4835 reset SIGINT/SIGQUIT. Don't call set_signal_ignored; that sets
4836 the value of original_signals to SIG_IGN. Posix interpretation 751. */
4837 get_original_signal (SIGINT);
4838 set_signal_handler (SIGINT, SIG_IGN);
4840 get_original_signal (SIGQUIT);
4841 set_signal_handler (SIGQUIT, SIG_IGN);
4845 /* Execute a simple command that is hopefully defined in a disk file
4850 3) look up the command
4853 6) If the execve failed, see if the file has executable mode set.
4854 If so, and it isn't a directory, then execute its contents as
4857 Note that the filename hashing stuff has to take place up here,
4858 in the parent. This is probably why the Bourne style shells
4859 don't handle it, since that would require them to go through
4860 this gnarly hair, for no good reason.
4862 NOTE: callers expect this to fork or exit(). */
4864 /* Name of a shell function to call when a command name is not found. */
4865 #ifndef NOTFOUND_HOOK
4866 # define NOTFOUND_HOOK "command_not_found_handle"
4870 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
4871 async, fds_to_close, cmdflags)
4873 REDIRECT *redirects;
4875 int pipe_in, pipe_out, async;
4876 struct fd_bitmap *fds_to_close;
4879 char *pathname, *command, **args;
4885 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
4886 pathname = words->word->word;
4888 result = EXECUTION_SUCCESS;
4889 #if defined (RESTRICTED_SHELL)
4890 command = (char *)NULL;
4891 if (restricted && mbschr (pathname, '/'))
4893 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4895 result = last_command_exit_value = EXECUTION_FAILURE;
4897 /* If we're not going to fork below, we must already be in a child
4898 process or a context in which it's safe to call exit(2). */
4899 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4900 exit (last_command_exit_value);
4904 #endif /* RESTRICTED_SHELL */
4906 command = search_for_command (pathname, 1);
4910 maybe_make_export_env ();
4911 put_command_name_into_env (command);
4914 /* We have to make the child before we check for the non-existence
4915 of COMMAND, since we want the error messages to be redirected. */
4916 /* If we can get away without forking and there are no pipes to deal with,
4917 don't bother to fork, just directly exec the command. */
4918 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4921 pid = make_child (savestring (command_line), async);
4925 int old_interactive;
4927 reset_terminating_signals (); /* XXX */
4928 /* Cancel traps, in trap.c. */
4929 restore_original_signals ();
4933 /* restore_original_signals may have undone the work done
4934 by make_child to ensure that SIGINT and SIGQUIT are ignored
4935 in asynchronous children. */
4938 if ((cmdflags & CMD_STDIN_REDIR) &&
4939 pipe_in == NO_PIPE &&
4940 (stdin_redirects (redirects) == 0))
4941 async_redirect_stdin ();
4942 setup_async_signals ();
4945 /* This functionality is now provided by close-on-exec of the
4946 file descriptors manipulated by redirection and piping.
4947 Some file descriptors still need to be closed in all children
4948 because of the way bash does pipes; fds_to_close is a
4949 bitmap of all such file descriptors. */
4951 close_fd_bitmap (fds_to_close);
4953 do_piping (pipe_in, pipe_out);
4955 old_interactive = interactive;
4959 subshell_environment = SUBSHELL_FORK;
4961 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
4963 #if defined (PROCESS_SUBSTITUTION)
4964 /* Try to remove named pipes that may have been created as the
4965 result of redirections. */
4966 unlink_fifo_list ();
4967 #endif /* PROCESS_SUBSTITUTION */
4968 exit (EXECUTION_FAILURE);
4972 interactive = old_interactive;
4976 hookf = find_function (NOTFOUND_HOOK);
4979 /* Make sure filenames are displayed using printable characters */
4980 if (ansic_shouldquote (pathname))
4981 pathname = ansic_quote (pathname, 0, NULL);
4982 internal_error (_("%s: command not found"), pathname);
4983 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
4986 #if defined (JOB_CONTROL)
4987 /* May need to reinitialize more of the job control state here. */
4988 kill_current_pipeline ();
4991 wl = make_word_list (make_word (NOTFOUND_HOOK), words);
4992 exit (execute_shell_function (hookf, wl));
4997 /* Execve expects the command name to be in args[0]. So we
4998 leave it there, in the same format that the user used to
5000 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
5001 exit (shell_execve (command, args, export_env));
5008 /* Make sure that the pipes are closed in the parent. */
5009 close_pipes (pipe_in, pipe_out);
5010 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5011 if (variable_context == 0)
5012 unlink_fifo_list ();
5019 /* CPP defines to decide whether a particular index into the #! line
5020 corresponds to a valid interpreter name or argument character, or
5021 whitespace. The MSDOS define is to allow \r to be treated the same
5024 #if !defined (MSDOS)
5025 # define STRINGCHAR(ind) \
5026 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
5027 # define WHITECHAR(ind) \
5028 (ind < sample_len && whitespace (sample[ind]))
5030 # define STRINGCHAR(ind) \
5031 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
5032 # define WHITECHAR(ind) \
5033 (ind < sample_len && whitespace (sample[ind]))
5037 getinterp (sample, sample_len, endp)
5039 int sample_len, *endp;
5045 /* Find the name of the interpreter to exec. */
5046 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
5049 for (start = i; STRINGCHAR(i); i++)
5052 execname = substring (sample, start, i);
5059 #if !defined (HAVE_HASH_BANG_EXEC)
5060 /* If the operating system on which we're running does not handle
5061 the #! executable format, then help out. SAMPLE is the text read
5062 from the file, SAMPLE_LEN characters. COMMAND is the name of
5063 the script; it and ARGS, the arguments given by the user, will
5064 become arguments to the specified interpreter. ENV is the environment
5065 to pass to the interpreter.
5067 The word immediately following the #! is the interpreter to execute.
5068 A single argument to the interpreter is allowed. */
5071 execute_shell_script (sample, sample_len, command, args, env)
5077 char *execname, *firstarg;
5078 int i, start, size_increment, larry;
5080 /* Find the name of the interpreter to exec. */
5081 execname = getinterp (sample, sample_len, &i);
5084 /* Now the argument, if any. */
5085 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
5088 /* If there is more text on the line, then it is an argument for the
5093 for (start = i; STRINGCHAR(i); i++)
5095 firstarg = substring ((char *)sample, start, i);
5099 larry = strvec_len (args) + size_increment;
5100 args = strvec_resize (args, larry + 1);
5102 for (i = larry - 1; i; i--)
5103 args[i] = args[i - size_increment];
5114 args[larry] = (char *)NULL;
5116 return (shell_execve (execname, args, env));
5121 #endif /* !HAVE_HASH_BANG_EXEC */
5124 initialize_subshell ()
5127 /* Forget about any aliases that we knew of. We are in a subshell. */
5128 delete_all_aliases ();
5131 #if defined (HISTORY)
5132 /* Forget about the history lines we have read. This is a non-interactive
5134 history_lines_this_session = 0;
5137 #if defined (JOB_CONTROL)
5138 /* Forget about the way job control was working. We are in a subshell. */
5139 without_job_control ();
5140 set_sigchld_handler ();
5142 #endif /* JOB_CONTROL */
5144 /* Reset the values of the shell flags and options. */
5145 reset_shell_flags ();
5146 reset_shell_options ();
5147 reset_shopt_options ();
5149 /* Zero out builtin_env, since this could be a shell script run from a
5150 sourced file with a temporary environment supplied to the `source/.'
5151 builtin. Such variables are not supposed to be exported (empirical
5152 testing with sh and ksh). Just throw it away; don't worry about a
5154 if (vc_isbltnenv (shell_variables))
5155 shell_variables = shell_variables->down;
5157 clear_unwind_protect_list (0);
5158 /* XXX -- are there other things we should be resetting here? */
5159 parse_and_execute_level = 0; /* nothing left to restore it */
5161 /* We're no longer inside a shell function. */
5162 variable_context = return_catch_flag = funcnest = 0;
5164 executing_list = 0; /* XXX */
5166 /* If we're not interactive, close the file descriptor from which we're
5167 reading the current shell script. */
5168 if (interactive_shell == 0)
5169 unset_bash_input (0);
5172 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
5173 # define SETOSTYPE(x) __setostype(x)
5175 # define SETOSTYPE(x)
5178 #define READ_SAMPLE_BUF(file, buf, len) \
5181 fd = open(file, O_RDONLY); \
5184 len = read (fd, buf, 80); \
5192 /* Call execve (), handling interpreting shell scripts, and handling
5195 shell_execve (command, args, env)
5203 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
5204 execve (command, args, env);
5205 i = errno; /* error from execve() */
5209 /* If we get to this point, then start checking out the file.
5210 Maybe it is something we can hack ourselves. */
5213 if (file_isdir (command))
5214 #if defined (EISDIR)
5215 internal_error (_("%s: %s"), command, strerror (EISDIR));
5217 internal_error (_("%s: is a directory"), command);
5219 else if (executable_file (command) == 0)
5222 file_error (command);
5224 /* errors not involving the path argument to execve. */
5225 else if (i == E2BIG || i == ENOMEM)
5228 file_error (command);
5232 /* The file has the execute bits set, but the kernel refuses to
5233 run it for some reason. See why. */
5234 #if defined (HAVE_HASH_BANG_EXEC)
5235 READ_SAMPLE_BUF (command, sample, sample_len);
5236 sample[sample_len - 1] = '\0';
5237 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5242 interp = getinterp (sample, sample_len, (int *)NULL);
5243 ilen = strlen (interp);
5245 if (interp[ilen - 1] == '\r')
5247 interp = xrealloc (interp, ilen + 2);
5248 interp[ilen - 1] = '^';
5250 interp[ilen + 1] = '\0';
5252 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
5258 file_error (command);
5260 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
5263 /* This file is executable.
5264 If it begins with #!, then help out people with losing operating
5265 systems. Otherwise, check to see if it is a binary file by seeing
5266 if the contents of the first line (or up to 80 characters) are in the
5267 ASCII set. If it's a text file, execute the contents as shell commands,
5268 otherwise return 126 (EX_BINARY_FILE). */
5269 READ_SAMPLE_BUF (command, sample, sample_len);
5271 if (sample_len == 0)
5272 return (EXECUTION_SUCCESS);
5274 /* Is this supposed to be an executable script?
5275 If so, the format of the line is "#! interpreter [argument]".
5276 A single argument is allowed. The BSD kernel restricts
5277 the length of the entire line to 32 characters (32 bytes
5278 being the size of the BSD exec header), but we allow 80
5282 #if !defined (HAVE_HASH_BANG_EXEC)
5283 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5284 return (execute_shell_script (sample, sample_len, command, args, env));
5287 if (check_binary_file (sample, sample_len))
5289 internal_error (_("%s: cannot execute binary file: %s"), command, strerror (i));
5290 return (EX_BINARY_FILE);
5294 /* We have committed to attempting to execute the contents of this file
5295 as shell commands. */
5297 initialize_subshell ();
5299 set_sigint_handler ();
5301 /* Insert the name of this shell into the argument list. */
5302 larray = strvec_len (args) + 1;
5303 args = strvec_resize (args, larray + 1);
5305 for (i = larray - 1; i; i--)
5306 args[i] = args[i - 1];
5308 args[0] = shell_name;
5310 args[larray] = (char *)NULL;
5312 if (args[0][0] == '-')
5315 #if defined (RESTRICTED_SHELL)
5317 change_flag ('r', FLAG_OFF);
5322 /* Can't free subshell_argv[0]; that is shell_name. */
5323 for (i = 1; i < subshell_argc; i++)
5324 free (subshell_argv[i]);
5325 free (subshell_argv);
5328 dispose_command (currently_executing_command); /* XXX */
5329 currently_executing_command = (COMMAND *)NULL;
5331 subshell_argc = larray;
5332 subshell_argv = args;
5333 subshell_envp = env;
5335 unbind_args (); /* remove the positional parameters */
5337 longjmp (subshell_top_level, 1);
5342 execute_intern_function (name, funcdef)
5344 FUNCTION_DEF *funcdef;
5348 if (check_identifier (name, posixly_correct) == 0)
5350 if (posixly_correct && interactive_shell == 0)
5352 last_command_exit_value = EX_BADUSAGE;
5353 jump_to_top_level (ERREXIT);
5355 return (EXECUTION_FAILURE);
5358 /* Posix interpretation 383 */
5359 if (posixly_correct && find_special_builtin (name->word))
5361 internal_error (_("`%s': is a special builtin"), name->word);
5362 last_command_exit_value = EX_BADUSAGE;
5363 jump_to_top_level (ERREXIT);
5366 var = find_function (name->word);
5367 if (var && (readonly_p (var) || noassign_p (var)))
5369 if (readonly_p (var))
5370 internal_error (_("%s: readonly function"), var->name);
5371 return (EXECUTION_FAILURE);
5374 #if defined (DEBUGGER)
5375 bind_function_def (name->word, funcdef);
5378 bind_function (name->word, funcdef->command);
5379 return (EXECUTION_SUCCESS);
5382 #if defined (INCLUDE_UNUSED)
5383 #if defined (PROCESS_SUBSTITUTION)
5387 register int i, fd_table_size;
5389 fd_table_size = getdtablesize ();
5390 if (fd_table_size > 256) /* clamp to a reasonable value */
5391 fd_table_size = 256;
5393 for (i = 3; i < fd_table_size; i++)
5396 #endif /* PROCESS_SUBSTITUTION */
5400 close_pipes (in, out)
5410 dup_error (oldd, newd)
5413 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
5416 /* Redirect input and output to be from and to the specified pipes.
5417 NO_PIPE and REDIRECT_BOTH are handled correctly. */
5419 do_piping (pipe_in, pipe_out)
5420 int pipe_in, pipe_out;
5422 if (pipe_in != NO_PIPE)
5424 if (dup2 (pipe_in, 0) < 0)
5425 dup_error (pipe_in, 0);
5429 /* Let stdio know the fd may have changed from text to binary mode. */
5430 freopen (NULL, "r", stdin);
5431 #endif /* __CYGWIN__ */
5433 if (pipe_out != NO_PIPE)
5435 if (pipe_out != REDIRECT_BOTH)
5437 if (dup2 (pipe_out, 1) < 0)
5438 dup_error (pipe_out, 1);
5439 if (pipe_out == 0 || pipe_out > 1)
5444 if (dup2 (1, 2) < 0)
5448 /* Let stdio know the fd may have changed from text to binary mode, and
5449 make sure to preserve stdout line buffering. */
5450 freopen (NULL, "w", stdout);
5451 sh_setlinebuf (stdout);
5452 #endif /* __CYGWIN__ */