1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
34 #include "posixstat.h"
37 # include <sys/param.h>
40 #if defined (HAVE_UNISTD_H)
44 #include "posixtime.h"
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 # include <sys/resource.h>
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 # include <sys/times.h>
60 #define NEED_FPURGE_DECL
67 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
72 #include "execute_cmd.h"
79 #if defined (COND_COMMAND)
83 #include "builtins/common.h"
84 #include "builtins/builtext.h" /* list of builtins */
86 #include <glob/strmatch.h>
87 #include <tilde/tilde.h>
89 #if defined (BUFFERED_INPUT)
98 # include "bashhist.h"
101 extern int posixly_correct;
102 extern int expand_aliases;
104 extern int breaking, continuing, loop_level;
105 extern int parse_and_execute_level, running_trap, sourcelevel;
106 extern int command_string_index, line_number;
107 extern int dot_found_in_search;
108 extern int already_making_children;
109 extern int tempenv_assign_error;
110 extern char *the_printed_command, *shell_name;
111 extern pid_t last_command_subst_pid;
112 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
113 extern char **subshell_argv, **subshell_envp;
114 extern int subshell_argc;
115 extern time_t shell_start_time;
117 extern char *glob_argv_flags;
120 extern int close __P((int));
122 /* Static functions defined and used in this file. */
123 static void close_pipes __P((int, int));
124 static void do_piping __P((int, int));
125 static void bind_lastarg __P((char *));
126 static int shell_control_structure __P((enum command_type));
127 static void cleanup_redirects __P((REDIRECT *));
129 #if defined (JOB_CONTROL)
130 static int restore_signal_mask __P((sigset_t *));
133 static void async_redirect_stdin __P((void));
135 static int builtin_status __P((int));
137 static int execute_for_command __P((FOR_COM *));
138 #if defined (SELECT_COMMAND)
139 static int print_index_and_element __P((int, int, WORD_LIST *));
140 static void indent __P((int, int));
141 static void print_select_list __P((WORD_LIST *, int, int, int));
142 static char *select_query __P((WORD_LIST *, int, char *, int));
143 static int execute_select_command __P((SELECT_COM *));
145 #if defined (DPAREN_ARITHMETIC)
146 static int execute_arith_command __P((ARITH_COM *));
148 #if defined (COND_COMMAND)
149 static int execute_cond_node __P((COND_COM *));
150 static int execute_cond_command __P((COND_COM *));
152 #if defined (COMMAND_TIMING)
153 static int mkfmt __P((char *, int, int, time_t, int));
154 static void print_formatted_time __P((FILE *, char *,
155 time_t, int, time_t, int,
157 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
159 #if defined (ARITH_FOR_COMMAND)
160 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
161 static int execute_arith_for_command __P((ARITH_FOR_COM *));
163 static int execute_case_command __P((CASE_COM *));
164 static int execute_while_command __P((WHILE_COM *));
165 static int execute_until_command __P((WHILE_COM *));
166 static int execute_while_or_until __P((WHILE_COM *, int));
167 static int execute_if_command __P((IF_COM *));
168 static int execute_null_command __P((REDIRECT *, int, int, int));
169 static void fix_assignment_words __P((WORD_LIST *));
170 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
171 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
172 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
173 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
175 REDIRECT *, struct fd_bitmap *, int));
176 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
182 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
183 int, int, int, struct fd_bitmap *, int));
185 static char *getinterp __P((char *, int, int *));
186 static void initialize_subshell __P((void));
187 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
188 #if defined (COPROCESS_SUPPORT)
189 static int execute_coproc __P((COMMAND *, int, int, struct fd_bitmap *));
192 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
194 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
196 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
198 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
199 so that reader_loop can set it to zero before executing a command. */
202 /* The name of the command that is currently being executed.
203 `test' needs this, for example. */
204 char *this_command_name;
206 /* The printed representation of the currently-executing command (same as
207 the_printed_command), except when a trap is being executed. Useful for
208 a debugger to know where exactly the program is currently executing. */
209 char *the_printed_command_except_trap;
211 /* For catching RETURN in a function. */
212 int return_catch_flag;
213 int return_catch_value;
214 procenv_t return_catch;
216 /* The value returned by the last synchronous command. */
217 int last_command_exit_value;
219 /* Whether or not the last command (corresponding to last_command_exit_value)
220 was terminated by a signal, and, if so, which one. */
221 int last_command_exit_signal;
223 /* The list of redirections to perform which will undo the redirections
224 that I made in the shell. */
225 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
227 /* The list of redirections to perform which will undo the internal
228 redirections performed by the `exec' builtin. These are redirections
229 that must be undone even when exec discards redirection_undo_list. */
230 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
232 /* When greater than zero, value is the `level' of builtins we are
233 currently executing (e.g. `eval echo a' would have it set to 2). */
234 int executing_builtin = 0;
236 /* Non-zero if we are executing a command list (a;b;c, etc.) */
237 int executing_list = 0;
239 /* Non-zero if failing commands in a command substitution should not exit the
240 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
241 commands run in command substitutions by parse_and_execute. */
242 int comsub_ignore_return = 0;
244 /* Non-zero if we have just forked and are currently running in a subshell
246 int subshell_environment;
248 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
249 int subshell_level = 0;
251 /* Currently-executing shell function. */
252 SHELL_VAR *this_shell_function;
254 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
255 int match_ignore_case = 0;
257 struct stat SB; /* used for debugging */
259 static int special_builtin_failed;
261 static COMMAND *currently_executing_command;
263 /* The line number that the currently executing function starts on. */
264 static int function_line_number;
266 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
267 number containing the function name. Used by executing_line_number to
268 report the correct line number. Kind of a hack. */
269 static int showing_function_line;
271 static int line_number_for_err_trap;
273 /* A sort of function nesting level counter */
274 static int funcnest = 0;
275 int funcnest_max = 0; /* XXX - for bash-4.2 */
277 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
279 #define FD_BITMAP_DEFAULT_SIZE 32
281 /* Functions to allocate and deallocate the structures used to pass
282 information from the shell to its children about file descriptors
288 struct fd_bitmap *ret;
290 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
296 ret->bitmap = (char *)xmalloc (size);
297 memset (ret->bitmap, '\0', size);
300 ret->bitmap = (char *)NULL;
305 dispose_fd_bitmap (fdbp)
306 struct fd_bitmap *fdbp;
313 close_fd_bitmap (fdbp)
314 struct fd_bitmap *fdbp;
320 for (i = 0; i < fdbp->size; i++)
329 /* Return the line number of the currently executing command. */
331 executing_line_number ()
333 if (executing && showing_function_line == 0 &&
334 (variable_context == 0 || interactive_shell == 0) &&
335 currently_executing_command)
337 #if defined (COND_COMMAND)
338 if (currently_executing_command->type == cm_cond)
339 return currently_executing_command->value.Cond->line;
341 #if defined (DPAREN_ARITHMETIC)
342 else if (currently_executing_command->type == cm_arith)
343 return currently_executing_command->value.Arith->line;
345 #if defined (ARITH_FOR_COMMAND)
346 else if (currently_executing_command->type == cm_arith_for)
347 return currently_executing_command->value.ArithFor->line;
356 /* Execute the command passed in COMMAND. COMMAND is exactly what
357 read_command () places into GLOBAL_COMMAND. See "command.h" for the
358 details of the command structure.
360 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
361 return values. Executing a command with nothing in it returns
362 EXECUTION_SUCCESS. */
364 execute_command (command)
367 struct fd_bitmap *bitmap;
370 current_fds_to_close = (struct fd_bitmap *)NULL;
371 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
372 begin_unwind_frame ("execute-command");
373 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
375 /* Just do the command, but not asynchronously. */
376 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
378 dispose_fd_bitmap (bitmap);
379 discard_unwind_frame ("execute-command");
381 #if defined (PROCESS_SUBSTITUTION)
382 /* don't unlink fifos if we're in a shell function; wait until the function
384 if (variable_context == 0)
386 #endif /* PROCESS_SUBSTITUTION */
392 /* Return 1 if TYPE is a shell control structure type. */
394 shell_control_structure (type)
395 enum command_type type;
399 #if defined (ARITH_FOR_COMMAND)
402 #if defined (SELECT_COMMAND)
405 #if defined (DPAREN_ARITHMETIC)
408 #if defined (COND_COMMAND)
417 case cm_function_def:
425 /* A function to use to unwind_protect the redirection undo list
428 cleanup_redirects (list)
431 do_redirections (list, RX_ACTIVE);
432 dispose_redirects (list);
436 /* Function to unwind_protect the redirections for functions and builtins. */
438 cleanup_func_redirects (list)
441 do_redirections (list, RX_ACTIVE);
446 dispose_exec_redirects ()
448 if (exec_redirection_undo_list)
450 dispose_redirects (exec_redirection_undo_list);
451 exec_redirection_undo_list = (REDIRECT *)NULL;
455 #if defined (JOB_CONTROL)
456 /* A function to restore the signal mask to its proper value when the shell
457 is interrupted or errors occur while creating a pipeline. */
459 restore_signal_mask (set)
462 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
464 #endif /* JOB_CONTROL */
467 /* A debugging function that can be called from gdb, for instance. */
472 int f, fd_table_size;
474 fd_table_size = getdtablesize ();
476 fprintf (stderr, "pid %ld open files:", (long)getpid ());
477 for (i = 3; i < fd_table_size; i++)
479 if ((f = fcntl (i, F_GETFD, 0)) != -1)
480 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
482 fprintf (stderr, "\n");
487 async_redirect_stdin ()
491 fd = open ("/dev/null", O_RDONLY);
498 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
501 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
503 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
504 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
505 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
506 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
507 from and where it goes. They can have the value of NO_PIPE, which means
509 FDS_TO_CLOSE is a list of file descriptors to close once the child has
510 been forked. This list often contains the unusable sides of pipes, etc.
512 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
513 return values. Executing a command with nothing in it returns
514 EXECUTION_SUCCESS. */
516 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
520 int pipe_in, pipe_out;
521 struct fd_bitmap *fds_to_close;
523 int exec_result, user_subshell, invert, ignore_return, was_error_trap;
524 REDIRECT *my_undo_list, *exec_undo_list;
525 volatile int last_pid;
526 volatile int save_line_number;
529 if (command == 0 || breaking || continuing || read_but_dont_execute)
530 return (EXECUTION_SUCCESS);
532 if (breaking || continuing)
533 return (last_command_exit_value);
534 if (command == 0 || read_but_dont_execute)
535 return (EXECUTION_SUCCESS);
539 run_pending_traps ();
542 if (running_trap == 0)
544 currently_executing_command = command;
546 invert = (command->flags & CMD_INVERT_RETURN) != 0;
548 /* If we're inverting the return value and `set -e' has been executed,
549 we don't want a failing command to inadvertently cause the shell
551 if (exit_immediately_on_error && invert) /* XXX */
552 command->flags |= CMD_IGNORE_RETURN; /* XXX */
554 exec_result = EXECUTION_SUCCESS;
556 /* If a command was being explicitly run in a subshell, or if it is
557 a shell control-structure, and it has a pipe, then we do the command
559 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
560 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
562 #if defined (COPROCESS_SUPPORT)
563 if (command->type == cm_coproc)
564 return (execute_coproc (command, pipe_in, pipe_out, fds_to_close));
567 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
569 if (command->type == cm_subshell ||
570 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
571 (shell_control_structure (command->type) &&
572 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
576 /* Fork a subshell, turn off the subshell bit, turn off job
577 control and call execute_command () on the command again. */
578 line_number_for_err_trap = line_number;
579 paren_pid = make_child (savestring (make_command_string (command)),
582 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
586 close_pipes (pipe_in, pipe_out);
588 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
591 /* If we are part of a pipeline, and not the end of the pipeline,
592 then we should simply return and let the last command in the
593 pipe be waited for. If we are not in a pipeline, or are the
594 last command in the pipeline, then we wait for the subshell
595 and return its exit status as usual. */
596 if (pipe_out != NO_PIPE)
597 return (EXECUTION_SUCCESS);
599 stop_pipeline (asynchronous, (COMMAND *)NULL);
601 if (asynchronous == 0)
603 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
604 invert = (command->flags & CMD_INVERT_RETURN) != 0;
605 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
607 last_command_exit_value = wait_for (paren_pid);
609 /* If we have to, invert the return value. */
611 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
613 : EXECUTION_SUCCESS);
615 exec_result = last_command_exit_value;
617 if (user_subshell && was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
619 last_command_exit_value = exec_result;
620 save_line_number = line_number;
621 line_number = line_number_for_err_trap;
623 line_number = save_line_number;
626 if (user_subshell && ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
628 last_command_exit_value = exec_result;
629 run_pending_traps ();
630 jump_to_top_level (ERREXIT);
633 return (last_command_exit_value = exec_result);
637 DESCRIBE_PID (paren_pid);
639 run_pending_traps ();
641 return (EXECUTION_SUCCESS);
646 #if defined (COMMAND_TIMING)
647 if (command->flags & CMD_TIME_PIPELINE)
651 command->flags |= CMD_FORCE_SUBSHELL;
652 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
656 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
658 if (running_trap == 0)
660 currently_executing_command = (COMMAND *)NULL;
662 return (exec_result);
664 #endif /* COMMAND_TIMING */
666 if (shell_control_structure (command->type) && command->redirects)
667 stdin_redir = stdin_redirects (command->redirects);
669 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
671 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
673 cleanup_redirects (redirection_undo_list);
674 redirection_undo_list = (REDIRECT *)NULL;
675 dispose_exec_redirects ();
676 return (last_command_exit_value = EXECUTION_FAILURE);
679 if (redirection_undo_list)
681 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
682 dispose_redirects (redirection_undo_list);
683 redirection_undo_list = (REDIRECT *)NULL;
686 my_undo_list = (REDIRECT *)NULL;
688 if (exec_redirection_undo_list)
690 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
691 dispose_redirects (exec_redirection_undo_list);
692 exec_redirection_undo_list = (REDIRECT *)NULL;
695 exec_undo_list = (REDIRECT *)NULL;
697 if (my_undo_list || exec_undo_list)
698 begin_unwind_frame ("loop_redirections");
701 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
704 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
706 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
710 switch (command->type)
714 save_line_number = line_number;
715 /* We can't rely on variables retaining their values across a
716 call to execute_simple_command if a longjmp occurs as the
717 result of a `return' builtin. This is true for sure with gcc. */
718 #if defined (RECYCLES_PIDS)
719 last_made_pid = NO_PID;
721 last_pid = last_made_pid;
722 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
724 if (ignore_return && command->value.Simple)
725 command->value.Simple->flags |= CMD_IGNORE_RETURN;
726 if (command->flags & CMD_STDIN_REDIR)
727 command->value.Simple->flags |= CMD_STDIN_REDIR;
729 line_number_for_err_trap = line_number = command->value.Simple->line;
731 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
732 asynchronous, fds_to_close);
733 line_number = save_line_number;
735 /* The temporary environment should be used for only the simple
736 command immediately following its definition. */
737 dispose_used_env_vars ();
739 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
740 /* Reclaim memory allocated with alloca () on machines which
741 may be using the alloca emulation code. */
743 #endif /* (ultrix && mips) || C_ALLOCA */
745 /* If we forked to do the command, then we must wait_for ()
748 /* XXX - this is something to watch out for if there are problems
749 when the shell is compiled without job control. */
750 if (already_making_children && pipe_out == NO_PIPE &&
751 last_made_pid != last_pid)
753 stop_pipeline (asynchronous, (COMMAND *)NULL);
757 DESCRIBE_PID (last_made_pid);
760 #if !defined (JOB_CONTROL)
761 /* Do not wait for asynchronous processes started from
763 if (last_made_pid != last_asynchronous_pid)
765 /* When executing a shell function that executes other
766 commands, this causes the last simple command in
767 the function to be waited for twice. This also causes
768 subshells forked to execute builtin commands (e.g., in
769 pipelines) to be waited for twice. */
770 exec_result = wait_for (last_made_pid);
774 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
775 only the failure of a simple command. */
776 if (was_error_trap && ignore_return == 0 && invert == 0 && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)
778 last_command_exit_value = exec_result;
779 line_number = line_number_for_err_trap;
781 line_number = save_line_number;
784 if (ignore_return == 0 && invert == 0 &&
785 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
786 (exit_immediately_on_error && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)))
788 last_command_exit_value = exec_result;
789 run_pending_traps ();
790 jump_to_top_level (ERREXIT);
797 command->value.For->flags |= CMD_IGNORE_RETURN;
798 exec_result = execute_for_command (command->value.For);
801 #if defined (ARITH_FOR_COMMAND)
804 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
805 exec_result = execute_arith_for_command (command->value.ArithFor);
809 #if defined (SELECT_COMMAND)
812 command->value.Select->flags |= CMD_IGNORE_RETURN;
813 exec_result = execute_select_command (command->value.Select);
819 command->value.Case->flags |= CMD_IGNORE_RETURN;
820 exec_result = execute_case_command (command->value.Case);
825 command->value.While->flags |= CMD_IGNORE_RETURN;
826 exec_result = execute_while_command (command->value.While);
831 command->value.While->flags |= CMD_IGNORE_RETURN;
832 exec_result = execute_until_command (command->value.While);
837 command->value.If->flags |= CMD_IGNORE_RETURN;
838 exec_result = execute_if_command (command->value.If);
843 /* This code can be executed from either of two paths: an explicit
844 '{}' command, or via a function call. If we are executed via a
845 function call, we have already taken care of the function being
846 executed in the background (down there in execute_simple_command ()),
847 and this command should *not* be marked as asynchronous. If we
848 are executing a regular '{}' group command, and asynchronous == 1,
849 we must want to execute the whole command in the background, so we
850 need a subshell, and we want the stuff executed in that subshell
851 (this group command) to be executed in the foreground of that
852 subshell (i.e. there will not be *another* subshell forked).
854 What we do is to force a subshell if asynchronous, and then call
855 execute_command_internal again with asynchronous still set to 1,
856 but with the original group command, so the printed command will
859 The code above that handles forking off subshells will note that
860 both subshell and async are on, and turn off async in the child
861 after forking the subshell (but leave async set in the parent, so
862 the normal call to describe_pid is made). This turning off
863 async is *crucial*; if it is not done, this will fall into an
864 infinite loop of executions through this spot in subshell after
865 subshell until the process limit is exhausted. */
869 command->flags |= CMD_FORCE_SUBSHELL;
871 execute_command_internal (command, 1, pipe_in, pipe_out,
876 if (ignore_return && command->value.Group->command)
877 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
879 execute_command_internal (command->value.Group->command,
880 asynchronous, pipe_in, pipe_out,
886 exec_result = execute_connection (command, asynchronous,
887 pipe_in, pipe_out, fds_to_close);
890 #if defined (DPAREN_ARITHMETIC)
892 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
894 command->value.Arith->flags |= CMD_IGNORE_RETURN;
895 line_number_for_err_trap = save_line_number = line_number;
896 exec_result = execute_arith_command (command->value.Arith);
897 line_number = save_line_number;
899 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
901 last_command_exit_value = exec_result;
902 save_line_number = line_number;
903 line_number = line_number_for_err_trap;
905 line_number = save_line_number;
908 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
910 last_command_exit_value = exec_result;
911 run_pending_traps ();
912 jump_to_top_level (ERREXIT);
918 #if defined (COND_COMMAND)
920 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
922 command->value.Cond->flags |= CMD_IGNORE_RETURN;
924 line_number_for_err_trap = save_line_number = line_number;
925 exec_result = execute_cond_command (command->value.Cond);
926 line_number = save_line_number;
928 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
930 last_command_exit_value = exec_result;
931 save_line_number = line_number;
932 line_number = line_number_for_err_trap;
934 line_number = save_line_number;
937 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
939 last_command_exit_value = exec_result;
940 run_pending_traps ();
941 jump_to_top_level (ERREXIT);
947 case cm_function_def:
948 exec_result = execute_intern_function (command->value.Function_def->name,
949 command->value.Function_def->command);
953 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
958 do_redirections (my_undo_list, RX_ACTIVE);
959 dispose_redirects (my_undo_list);
963 dispose_redirects (exec_undo_list);
965 if (my_undo_list || exec_undo_list)
966 discard_unwind_frame ("loop_redirections");
968 /* Invert the return value if we have to */
970 exec_result = (exec_result == EXECUTION_SUCCESS)
974 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
975 /* This is where we set PIPESTATUS from the exit status of the appropriate
976 compound commands (the ones that look enough like simple commands to
977 cause confusion). We might be able to optimize by not doing this if
978 subshell_environment != 0. */
979 switch (command->type)
981 # if defined (DPAREN_ARITHMETIC)
984 # if defined (COND_COMMAND)
987 set_pipestatus_from_exit (exec_result);
992 last_command_exit_value = exec_result;
993 run_pending_traps ();
995 if (running_trap == 0)
997 currently_executing_command = (COMMAND *)NULL;
998 return (last_command_exit_value);
1001 #if defined (COMMAND_TIMING)
1003 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1004 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
1005 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
1006 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
1009 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1010 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1012 static const int precs[] = { 0, 100, 10, 1 };
1014 /* Expand one `%'-prefixed escape sequence from a time format string. */
1016 mkfmt (buf, prec, lng, sec, sec_fraction)
1023 char abuf[INT_STRLEN_BOUND(time_t) + 1];
1027 abuf[sizeof(abuf) - 1] = '\0';
1029 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1034 aind = sizeof(abuf) - 2;
1036 abuf[aind--] = (min % 10) + '0';
1040 buf[ind++] = abuf[aind++];
1044 /* Now add the seconds. */
1045 aind = sizeof (abuf) - 2;
1047 abuf[aind--] = (sec % 10) + '0';
1051 buf[ind++] = abuf[aind++];
1053 /* We want to add a decimal point and PREC places after it if PREC is
1054 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1059 for (aind = 1; aind <= prec; aind++)
1061 buf[ind++] = (sec_fraction / precs[aind]) + '0';
1062 sec_fraction %= precs[aind];
1073 /* Interpret the format string FORMAT, interpolating the following escape
1077 where the optional `prec' is a precision, meaning the number of
1078 characters after the decimal point, the optional `l' means to format
1079 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1080 and the last character is one of
1082 R number of seconds of `real' time
1083 U number of seconds of `user' time
1084 S number of seconds of `system' time
1086 An occurrence of `%%' in the format string is translated to a `%'. The
1087 result is printed to FP, a pointer to a FILE. The other variables are
1088 the seconds and thousandths of a second of real, user, and system time,
1091 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1102 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1107 len = strlen (format);
1108 ssize = (len + 64) - (len % 64);
1109 str = (char *)xmalloc (ssize);
1112 for (s = format; *s; s++)
1114 if (*s != '%' || s[1] == '\0')
1116 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1119 else if (s[1] == '%')
1122 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1125 else if (s[1] == 'P')
1129 /* clamp CPU usage at 100% */
1134 sum_frac = (cpu % 100) * 10;
1135 len = mkfmt (ts, 2, 0, sum, sum_frac);
1136 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1137 strcpy (str + sindex, ts);
1142 prec = 3; /* default is three places past the decimal point. */
1143 lng = 0; /* default is to not use minutes or append `s' */
1145 if (DIGIT (*s)) /* `precision' */
1148 if (prec > 3) prec = 3;
1150 if (*s == 'l') /* `length extender' */
1155 if (*s == 'R' || *s == 'E')
1156 len = mkfmt (ts, prec, lng, rs, rsf);
1158 len = mkfmt (ts, prec, lng, us, usf);
1160 len = mkfmt (ts, prec, lng, ss, ssf);
1163 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1167 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1168 strcpy (str + sindex, ts);
1174 fprintf (fp, "%s\n", str);
1181 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1183 int asynchronous, pipe_in, pipe_out;
1184 struct fd_bitmap *fds_to_close;
1186 int rv, posix_time, old_flags, nullcmd;
1192 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1193 struct timeval real, user, sys;
1194 struct timeval before, after;
1195 # if defined (HAVE_STRUCT_TIMEZONE)
1196 struct timezone dtz; /* posix doesn't define this */
1198 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1200 # if defined (HAVE_TIMES)
1201 clock_t tbefore, tafter, real, user, sys;
1202 struct tms before, after;
1206 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1207 # if defined (HAVE_STRUCT_TIMEZONE)
1208 gettimeofday (&before, &dtz);
1210 gettimeofday (&before, (void *)NULL);
1211 # endif /* !HAVE_STRUCT_TIMEZONE */
1212 getrusage (RUSAGE_SELF, &selfb);
1213 getrusage (RUSAGE_CHILDREN, &kidsb);
1215 # if defined (HAVE_TIMES)
1216 tbefore = times (&before);
1220 posix_time = (command->flags & CMD_TIME_POSIX);
1222 #if 0 /* XXX - bash-4.2 */
1223 nullcmd = (command == 0) || (command->type == cm_simple && command->value.Simple->words == 0 && command->value.Simple->redirects == 0);
1224 if (posixly_correct && nullcmd)
1226 #if defined (HAVE_GETRUSAGE)
1227 selfb.ru_utime.tv_sec = kidsb.ru_utime.tv_sec = selfb.ru_stime.tv_sec = kidsb.ru_stime.tv_sec = 0;
1228 selfb.ru_utime.tv_usec = kidsb.ru_utime.tv_usec = selfb.ru_stime.tv_usec = kidsb.ru_stime.tv_usec = 0;
1229 before.tv_sec = shell_start_time;
1232 before.tms_utime = before.tms_stime = before.tms_cutime = before.tms_cstime = 0;
1233 tbefore = shell_start_time;
1238 old_flags = command->flags;
1239 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1240 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1241 command->flags = old_flags;
1244 rsf = usf = ssf = cpu = 0;
1246 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1247 # if defined (HAVE_STRUCT_TIMEZONE)
1248 gettimeofday (&after, &dtz);
1250 gettimeofday (&after, (void *)NULL);
1251 # endif /* !HAVE_STRUCT_TIMEZONE */
1252 getrusage (RUSAGE_SELF, &selfa);
1253 getrusage (RUSAGE_CHILDREN, &kidsa);
1255 difftimeval (&real, &before, &after);
1256 timeval_to_secs (&real, &rs, &rsf);
1258 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1259 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1260 timeval_to_secs (&user, &us, &usf);
1262 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1263 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1264 timeval_to_secs (&sys, &ss, &ssf);
1266 cpu = timeval_to_cpu (&real, &user, &sys);
1268 # if defined (HAVE_TIMES)
1269 tafter = times (&after);
1271 real = tafter - tbefore;
1272 clock_t_to_secs (real, &rs, &rsf);
1274 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1275 clock_t_to_secs (user, &us, &usf);
1277 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1278 clock_t_to_secs (sys, &ss, &ssf);
1280 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1284 rsf = usf = ssf = cpu = 0;
1289 time_format = POSIX_TIMEFORMAT;
1290 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1292 #if 0 /* XXX - bash-4.2 */
1293 if (posixly_correct && nullcmd)
1294 time_format = "user\t%2lU\nsys\t%2lS";
1297 time_format = BASH_TIMEFORMAT;
1299 if (time_format && *time_format)
1300 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1304 #endif /* COMMAND_TIMING */
1306 /* Execute a command that's supposed to be in a subshell. This must be
1307 called after make_child and we must be running in the child process.
1308 The caller will return or exit() immediately with the value this returns. */
1310 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1313 int pipe_in, pipe_out;
1314 struct fd_bitmap *fds_to_close;
1316 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1317 int ois, user_coproc;
1321 USE_VAR(user_subshell);
1322 USE_VAR(user_coproc);
1325 USE_VAR(asynchronous);
1328 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1329 pipe_in == NO_PIPE &&
1330 stdin_redirects (command->redirects) == 0);
1332 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1333 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1334 user_coproc = command->type == cm_coproc;
1336 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1338 /* If a command is asynchronous in a subshell (like ( foo ) & or
1339 the special case of an asynchronous GROUP command where the
1340 the subshell bit is turned on down in case cm_group: below),
1341 turn off `asynchronous', so that two subshells aren't spawned.
1342 XXX - asynchronous used to be set to 0 in this block, but that
1343 means that setup_async_signals was never run. Now it's set to
1344 0 after subshell_environment is set appropriately and setup_async_signals
1347 This seems semantically correct to me. For example,
1348 ( foo ) & seems to say ``do the command `foo' in a subshell
1349 environment, but don't wait for that subshell to finish'',
1350 and "{ foo ; bar ; } &" seems to me to be like functions or
1351 builtins in the background, which executed in a subshell
1352 environment. I just don't see the need to fork two subshells. */
1354 /* Don't fork again, we are already in a subshell. A `doubly
1355 async' shell is not interactive, however. */
1358 #if defined (JOB_CONTROL)
1359 /* If a construct like ( exec xxx yyy ) & is given while job
1360 control is active, we want to prevent exec from putting the
1361 subshell back into the original process group, carefully
1362 undoing all the work we just did in make_child. */
1364 #endif /* JOB_CONTROL */
1365 ois = interactive_shell;
1366 interactive_shell = 0;
1367 /* This test is to prevent alias expansion by interactive shells that
1368 run `(command) &' but to allow scripts that have enabled alias
1369 expansion with `shopt -s expand_alias' to continue to expand
1371 if (ois != interactive_shell)
1375 /* Subshells are neither login nor interactive. */
1376 login_shell = interactive = 0;
1379 subshell_environment = SUBSHELL_PAREN;
1382 subshell_environment = 0; /* XXX */
1384 subshell_environment |= SUBSHELL_ASYNC;
1385 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1386 subshell_environment |= SUBSHELL_PIPE;
1388 subshell_environment |= SUBSHELL_COPROC;
1391 reset_terminating_signals (); /* in sig.c */
1392 /* Cancel traps, in trap.c. */
1393 restore_original_signals ();
1395 /* Make sure restore_original_signals doesn't undo the work done by
1396 make_child to ensure that asynchronous children are immune to SIGINT
1397 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1401 setup_async_signals ();
1405 #if defined (JOB_CONTROL)
1406 set_sigchld_handler ();
1407 #endif /* JOB_CONTROL */
1409 set_sigint_handler ();
1411 #if defined (JOB_CONTROL)
1412 /* Delete all traces that there were any jobs running. This is
1413 only for subshells. */
1414 without_job_control ();
1415 #endif /* JOB_CONTROL */
1418 close_fd_bitmap (fds_to_close);
1420 do_piping (pipe_in, pipe_out);
1422 #if defined (COPROCESS_SUPPORT)
1426 /* If this is a user subshell, set a flag if stdin was redirected.
1427 This is used later to decide whether to redirect fd 0 to
1428 /dev/null for async commands in the subshell. This adds more
1429 sh compatibility, but I'm not sure it's the right thing to do. */
1432 stdin_redir = stdin_redirects (command->redirects);
1433 restore_default_signal (0);
1436 /* If this is an asynchronous command (command &), we want to
1437 redirect the standard input from /dev/null in the absence of
1438 any specific redirection involving stdin. */
1439 if (should_redir_stdin && stdin_redir == 0)
1440 async_redirect_stdin ();
1442 /* Do redirections, then dispose of them before recursive call. */
1443 if (command->redirects)
1445 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1446 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1448 dispose_redirects (command->redirects);
1449 command->redirects = (REDIRECT *)NULL;
1452 if (command->type == cm_subshell)
1453 tcom = command->value.Subshell->command;
1454 else if (user_coproc)
1455 tcom = command->value.Coproc->command;
1459 if (command->flags & CMD_TIME_PIPELINE)
1460 tcom->flags |= CMD_TIME_PIPELINE;
1461 if (command->flags & CMD_TIME_POSIX)
1462 tcom->flags |= CMD_TIME_POSIX;
1464 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1465 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1466 tcom->flags |= CMD_IGNORE_RETURN;
1468 /* If this is a simple command, tell execute_disk_command that it
1469 might be able to get away without forking and simply exec.
1470 This means things like ( sleep 10 ) will only cause one fork.
1471 If we're timing the command or inverting its return value, however,
1472 we cannot do this optimization. */
1473 if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1474 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1475 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1477 tcom->flags |= CMD_NO_FORK;
1478 if (tcom->type == cm_simple)
1479 tcom->value.Simple->flags |= CMD_NO_FORK;
1482 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1483 tcom->flags &= ~CMD_INVERT_RETURN;
1485 result = setjmp (top_level);
1487 /* If we're inside a function while executing this subshell, we
1488 need to handle a possible `return'. */
1490 if (return_catch_flag)
1491 function_value = setjmp (return_catch);
1493 /* If we're going to exit the shell, we don't want to invert the return
1495 if (result == EXITPROG)
1496 invert = 0, return_code = last_command_exit_value;
1498 return_code = EXECUTION_FAILURE;
1499 else if (function_value)
1500 return_code = return_catch_value;
1502 return_code = execute_command_internal (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1504 /* If we are asked to, invert the return value. */
1506 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1507 : EXECUTION_SUCCESS;
1509 /* If we were explicitly placed in a subshell with (), we need
1510 to do the `shell cleanup' things, such as running traps[0]. */
1511 if (user_subshell && signal_is_trapped (0))
1513 last_command_exit_value = return_code;
1514 return_code = run_exit_trap ();
1518 return (return_code);
1522 #if defined (COPROCESS_SUPPORT)
1523 #define COPROC_MAX 16
1525 typedef struct cpelement
1527 struct cpelement *next;
1528 struct coproc *coproc;
1532 typedef struct cplist
1534 struct cpelement *head;
1535 struct cpelement *tail;
1540 static struct cpelement *cpe_alloc __P((struct coproc *));
1541 static void cpe_dispose __P((struct cpelement *));
1542 static struct cpelement *cpl_add __P((struct coproc *));
1543 static struct cpelement *cpl_delete __P((pid_t));
1544 static void cpl_reap __P((void));
1545 static void cpl_flush __P((void));
1546 static struct cpelement *cpl_search __P((pid_t));
1547 static struct cpelement *cpl_searchbyname __P((char *));
1548 static void cpl_prune __P((void));
1550 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0 };
1552 cplist_t coproc_list = {0, 0, 0};
1554 /* Functions to manage the list of coprocs */
1556 static struct cpelement *
1560 struct cpelement *cpe;
1562 cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1564 cpe->next = (struct cpelement *)0;
1570 struct cpelement *cpe;
1575 static struct cpelement *
1579 struct cpelement *cpe;
1581 cpe = cpe_alloc (cp);
1583 if (coproc_list.head == 0)
1585 coproc_list.head = coproc_list.tail = cpe;
1586 coproc_list.ncoproc = 0; /* just to make sure */
1590 coproc_list.tail->next = cpe;
1591 coproc_list.tail = cpe;
1593 coproc_list.ncoproc++;
1598 static struct cpelement *
1602 struct cpelement *prev, *p;
1604 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1605 if (p->coproc->c_pid == pid)
1607 prev->next = p->next; /* remove from list */
1612 return 0; /* not found */
1615 itrace("cpl_delete: deleting %d", pid);
1618 /* Housekeeping in the border cases. */
1619 if (p == coproc_list.head)
1620 coproc_list.head = coproc_list.head->next;
1621 else if (p == coproc_list.tail)
1622 coproc_list.tail = prev;
1624 coproc_list.ncoproc--;
1625 if (coproc_list.ncoproc == 0)
1626 coproc_list.head = coproc_list.tail = 0;
1627 else if (coproc_list.ncoproc == 1)
1628 coproc_list.tail = coproc_list.head; /* just to make sure */
1636 struct cpelement *prev, *p;
1638 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1639 if (p->coproc->c_flags & COPROC_DEAD)
1641 prev->next = p->next; /* remove from list */
1643 /* Housekeeping in the border cases. */
1644 if (p == coproc_list.head)
1645 coproc_list.head = coproc_list.head->next;
1646 else if (p == coproc_list.tail)
1647 coproc_list.tail = prev;
1649 coproc_list.ncoproc--;
1650 if (coproc_list.ncoproc == 0)
1651 coproc_list.head = coproc_list.tail = 0;
1652 else if (coproc_list.ncoproc == 1)
1653 coproc_list.tail = coproc_list.head; /* just to make sure */
1656 itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1659 coproc_dispose (p->coproc);
1664 /* Clear out the list of saved statuses */
1668 struct cpelement *cpe, *p;
1670 for (cpe = coproc_list.head; cpe; )
1675 coproc_dispose (p->coproc);
1679 coproc_list.head = coproc_list.tail = 0;
1680 coproc_list.ncoproc = 0;
1683 /* Search for PID in the list of coprocs; return the cpelement struct if
1684 found. If not found, return NULL. */
1685 static struct cpelement *
1689 struct cpelement *cp;
1691 for (cp = coproc_list.head ; cp; cp = cp->next)
1692 if (cp->coproc->c_pid == pid)
1694 return (struct cpelement *)NULL;
1697 /* Search for the coproc named NAME in the list of coprocs; return the
1698 cpelement struct if found. If not found, return NULL. */
1699 static struct cpelement *
1700 cpl_searchbyname (name)
1703 struct cpelement *cp;
1705 for (cp = coproc_list.head ; cp; cp = cp->next)
1706 if (STREQ (cp->coproc->c_name, name))
1708 return (struct cpelement *)NULL;
1715 struct cpelement *cp;
1717 while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1719 cp = coproc_list.head;
1720 coproc_list.head = coproc_list.head->next;
1721 coproc_dispose (cp->coproc);
1723 coproc_list.ncoproc--;
1728 /* These currently use a single global "shell coproc" but are written in a
1729 way to not preclude additional coprocs later (using the list management
1733 getcoprocbypid (pid)
1736 return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1740 getcoprocbyname (name)
1743 return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1752 cp->c_rfd = cp->c_wfd = -1;
1753 cp->c_rsave = cp->c_wsave = -1;
1754 cp->c_flags = cp->c_status = 0;
1758 coproc_alloc (name, pid)
1764 cp = &sh_coproc; /* XXX */
1767 cp->c_name = savestring (name);
1780 coproc_unsetvars (cp);
1786 /* Placeholder for now. */
1790 coproc_dispose (&sh_coproc);
1807 cp->c_rsave = cp->c_wsave = -1;
1813 coproc_close (&sh_coproc);
1822 if (cp && (cp->c_flags & COPROC_DEAD))
1823 coproc_dispose (cp);
1827 coproc_rclose (cp, fd)
1831 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1839 coproc_wclose (cp, fd)
1843 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1851 coproc_checkfd (cp, fd)
1858 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1859 update = cp->c_rfd = -1;
1860 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1861 update = cp->c_wfd = -1;
1863 coproc_setvars (cp);
1870 coproc_checkfd (&sh_coproc, fd);
1874 coproc_fdclose (cp, fd)
1878 coproc_rclose (cp, fd);
1879 coproc_wclose (cp, fd);
1880 coproc_setvars (cp);
1887 cp->c_rsave = cp->c_rfd;
1888 cp->c_wsave = cp->c_wfd;
1892 coproc_fdrestore (cp)
1895 cp->c_rfd = cp->c_rsave;
1896 cp->c_wfd = cp->c_wsave;
1900 coproc_pidchk (pid, status)
1905 cp = getcoprocbypid (pid);
1908 itrace("coproc_pidchk: pid %d has died", pid);
1912 cp->c_status = status;
1913 cp->c_flags |= COPROC_DEAD;
1914 cp->c_flags &= ~COPROC_RUNNING;
1916 coproc_dispose (cp);
1928 #if defined (ARRAY_VARS)
1932 if (cp->c_name == 0)
1935 l = strlen (cp->c_name);
1936 namevar = xmalloc (l + 16);
1938 #if defined (ARRAY_VARS)
1939 v = find_variable (cp->c_name);
1941 v = make_new_array_variable (cp->c_name);
1942 if (array_p (v) == 0)
1943 v = convert_var_to_array (v);
1945 t = itos (cp->c_rfd);
1947 v = bind_array_variable (cp->c_name, ind, t, 0);
1950 t = itos (cp->c_wfd);
1952 bind_array_variable (cp->c_name, ind, t, 0);
1955 sprintf (namevar, "%s_READ", cp->c_name);
1956 t = itos (cp->c_rfd);
1957 bind_variable (namevar, t, 0);
1959 sprintf (namevar, "%s_WRITE", cp->c_name);
1960 t = itos (cp->c_wfd);
1961 bind_variable (namevar, t, 0);
1965 sprintf (namevar, "%s_PID", cp->c_name);
1966 t = itos (cp->c_pid);
1967 bind_variable (namevar, t, 0);
1974 coproc_unsetvars (cp)
1980 if (cp->c_name == 0)
1983 l = strlen (cp->c_name);
1984 namevar = xmalloc (l + 16);
1986 sprintf (namevar, "%s_PID", cp->c_name);
1987 unbind_variable (namevar);
1989 #if defined (ARRAY_VARS)
1990 unbind_variable (cp->c_name);
1992 sprintf (namevar, "%s_READ", cp->c_name);
1993 unbind_variable (namevar);
1994 sprintf (namevar, "%s_WRITE", cp->c_name);
1995 unbind_variable (namevar);
2002 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
2004 int pipe_in, pipe_out;
2005 struct fd_bitmap *fds_to_close;
2007 int rpipe[2], wpipe[2], estat;
2012 /* XXX -- will require changes to handle multiple coprocs */
2013 if (sh_coproc.c_pid != NO_PID)
2016 internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc.c_pid, sh_coproc.c_name);
2017 return (last_command_exit_value = EXECUTION_FAILURE);
2019 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc.c_pid, sh_coproc.c_name);
2022 coproc_init (&sh_coproc);
2024 command_string_index = 0;
2025 tcmd = make_command_string (command);
2027 sh_openpipe ((int *)&rpipe); /* 0 = parent read, 1 = child write */
2028 sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2030 coproc_pid = make_child (savestring (tcmd), 1);
2031 if (coproc_pid == 0)
2036 estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2047 cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2048 cp->c_rfd = rpipe[0];
2049 cp->c_wfd = wpipe[1];
2051 SET_CLOSE_ON_EXEC (cp->c_rfd);
2052 SET_CLOSE_ON_EXEC (cp->c_wfd);
2054 coproc_setvars (cp);
2057 itrace ("execute_coproc: [%d] %s", coproc_pid, the_printed_command);
2060 close_pipes (pipe_in, pipe_out);
2061 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2062 unlink_fifo_list ();
2064 stop_pipeline (1, (COMMAND *)NULL);
2065 DESCRIBE_PID (coproc_pid);
2066 run_pending_traps ();
2068 return (EXECUTION_SUCCESS);
2073 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2075 int asynchronous, pipe_in, pipe_out;
2076 struct fd_bitmap *fds_to_close;
2078 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2080 struct fd_bitmap *fd_bitmap;
2082 #if defined (JOB_CONTROL)
2084 BLOCK_CHILD (set, oset);
2085 #endif /* JOB_CONTROL */
2087 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2092 while (cmd && cmd->type == cm_connection &&
2093 cmd->value.Connection && cmd->value.Connection->connector == '|')
2095 /* Make a pipeline between the two commands. */
2096 if (pipe (fildes) < 0)
2098 sys_error (_("pipe error"));
2099 #if defined (JOB_CONTROL)
2100 terminate_current_pipeline ();
2101 kill_current_pipeline ();
2102 UNBLOCK_CHILD (oset);
2103 #endif /* JOB_CONTROL */
2104 last_command_exit_value = EXECUTION_FAILURE;
2105 /* The unwind-protects installed below will take care
2106 of closing all of the open file descriptors. */
2107 throw_to_top_level ();
2108 return (EXECUTION_FAILURE); /* XXX */
2111 /* Here is a problem: with the new file close-on-exec
2112 code, the read end of the pipe (fildes[0]) stays open
2113 in the first process, so that process will never get a
2114 SIGPIPE. There is no way to signal the first process
2115 that it should close fildes[0] after forking, so it
2116 remains open. No SIGPIPE is ever sent because there
2117 is still a file descriptor open for reading connected
2118 to the pipe. We take care of that here. This passes
2119 around a bitmap of file descriptors that must be
2120 closed after making a child process in execute_simple_command. */
2122 /* We need fd_bitmap to be at least as big as fildes[0].
2123 If fildes[0] is less than fds_to_close->size, then
2124 use fds_to_close->size. */
2125 new_bitmap_size = (fildes[0] < fds_to_close->size)
2126 ? fds_to_close->size
2129 fd_bitmap = new_fd_bitmap (new_bitmap_size);
2131 /* Now copy the old information into the new bitmap. */
2132 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2134 /* And mark the pipe file descriptors to be closed. */
2135 fd_bitmap->bitmap[fildes[0]] = 1;
2137 /* In case there are pipe or out-of-processes errors, we
2138 want all these file descriptors to be closed when
2139 unwind-protects are run, and the storage used for the
2140 bitmaps freed up. */
2141 begin_unwind_frame ("pipe-file-descriptors");
2142 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2143 add_unwind_protect (close_fd_bitmap, fd_bitmap);
2145 add_unwind_protect (close, prev);
2146 dummyfd = fildes[1];
2147 add_unwind_protect (close, dummyfd);
2149 #if defined (JOB_CONTROL)
2150 add_unwind_protect (restore_signal_mask, &oset);
2151 #endif /* JOB_CONTROL */
2153 if (ignore_return && cmd->value.Connection->first)
2154 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2155 execute_command_internal (cmd->value.Connection->first, asynchronous,
2156 prev, fildes[1], fd_bitmap);
2164 dispose_fd_bitmap (fd_bitmap);
2165 discard_unwind_frame ("pipe-file-descriptors");
2167 cmd = cmd->value.Connection->second;
2170 /* Now execute the rightmost command in the pipeline. */
2171 if (ignore_return && cmd)
2172 cmd->flags |= CMD_IGNORE_RETURN;
2173 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2178 #if defined (JOB_CONTROL)
2179 UNBLOCK_CHILD (oset);
2183 return (exec_result);
2187 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2189 int asynchronous, pipe_in, pipe_out;
2190 struct fd_bitmap *fds_to_close;
2192 COMMAND *tc, *second;
2193 int ignore_return, exec_result, was_error_trap, invert;
2194 volatile int save_line_number;
2196 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2198 switch (command->value.Connection->connector)
2200 /* Do the first command asynchronously. */
2202 tc = command->value.Connection->first;
2204 return (EXECUTION_SUCCESS);
2207 tc->flags |= CMD_IGNORE_RETURN;
2208 tc->flags |= CMD_AMPERSAND;
2210 /* If this shell was compiled without job control support,
2211 if we are currently in a subshell via `( xxx )', or if job
2212 control is not active then the standard input for an
2213 asynchronous command is forced to /dev/null. */
2214 #if defined (JOB_CONTROL)
2215 if ((subshell_environment || !job_control) && !stdin_redir)
2218 #endif /* JOB_CONTROL */
2219 tc->flags |= CMD_STDIN_REDIR;
2221 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2224 if (tc->flags & CMD_STDIN_REDIR)
2225 tc->flags &= ~CMD_STDIN_REDIR;
2227 second = command->value.Connection->second;
2231 second->flags |= CMD_IGNORE_RETURN;
2233 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2238 /* Just call execute command on both sides. */
2242 if (command->value.Connection->first)
2243 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2244 if (command->value.Connection->second)
2245 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2249 execute_command (command->value.Connection->first);
2251 exec_result = execute_command_internal (command->value.Connection->second,
2252 asynchronous, pipe_in, pipe_out,
2258 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2259 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2260 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2262 line_number_for_err_trap = line_number;
2263 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2265 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2267 last_command_exit_value = exec_result;
2268 save_line_number = line_number;
2269 line_number = line_number_for_err_trap;
2271 line_number = save_line_number;
2274 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2276 last_command_exit_value = exec_result;
2277 run_pending_traps ();
2278 jump_to_top_level (ERREXIT);
2287 /* If we have something like `a && b &' or `a || b &', run the
2288 && or || stuff in a subshell. Force a subshell and just call
2289 execute_command_internal again. Leave asynchronous on
2290 so that we get a report from the parent shell about the
2292 command->flags |= CMD_FORCE_SUBSHELL;
2293 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2297 /* Execute the first command. If the result of that is successful
2298 and the connector is AND_AND, or the result is not successful
2299 and the connector is OR_OR, then execute the second command,
2300 otherwise return. */
2303 if (command->value.Connection->first)
2304 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2306 exec_result = execute_command (command->value.Connection->first);
2308 if (((command->value.Connection->connector == AND_AND) &&
2309 (exec_result == EXECUTION_SUCCESS)) ||
2310 ((command->value.Connection->connector == OR_OR) &&
2311 (exec_result != EXECUTION_SUCCESS)))
2313 if (ignore_return && command->value.Connection->second)
2314 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2316 exec_result = execute_command (command->value.Connection->second);
2322 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2323 jump_to_top_level (DISCARD);
2324 exec_result = EXECUTION_FAILURE;
2333 if (!interactive_shell) \
2334 reap_dead_jobs (); \
2338 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2341 execute_for_command (for_command)
2342 FOR_COM *for_command;
2344 register WORD_LIST *releaser, *list;
2347 int retval, save_line_number;
2349 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2352 save_line_number = line_number;
2353 if (check_identifier (for_command->name, 1) == 0)
2355 if (posixly_correct && interactive_shell == 0)
2357 last_command_exit_value = EX_BADUSAGE;
2358 jump_to_top_level (ERREXIT);
2360 return (EXECUTION_FAILURE);
2364 identifier = for_command->name->word;
2366 list = releaser = expand_words_no_vars (for_command->map_list);
2368 begin_unwind_frame ("for");
2369 add_unwind_protect (dispose_words, releaser);
2372 if (lexical_scoping)
2374 old_value = copy_variable (find_variable (identifier));
2376 add_unwind_protect (dispose_variable, old_value);
2380 if (for_command->flags & CMD_IGNORE_RETURN)
2381 for_command->action->flags |= CMD_IGNORE_RETURN;
2383 for (retval = EXECUTION_SUCCESS; list; list = list->next)
2387 line_number = for_command->line;
2389 /* Remember what this command looks like, for debugger. */
2390 command_string_index = 0;
2391 print_for_command_head (for_command);
2393 if (echo_command_at_execute)
2394 xtrace_print_for_command_head (for_command);
2396 /* Save this command unless it's a trap command and we're not running
2399 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2401 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2404 FREE (the_printed_command_except_trap);
2405 the_printed_command_except_trap = savestring (the_printed_command);
2408 retval = run_debug_trap ();
2409 #if defined (DEBUGGER)
2410 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2411 skip the command. */
2412 if (debugging_mode && retval != EXECUTION_SUCCESS)
2416 this_command_name = (char *)NULL;
2417 v = bind_variable (identifier, list->word->word, 0);
2418 if (readonly_p (v) || noassign_p (v))
2420 line_number = save_line_number;
2421 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2423 last_command_exit_value = EXECUTION_FAILURE;
2424 jump_to_top_level (FORCE_EOF);
2428 dispose_words (releaser);
2429 discard_unwind_frame ("for");
2431 return (EXECUTION_FAILURE);
2434 retval = execute_command (for_command->action);
2453 line_number = save_line_number;
2456 if (lexical_scoping)
2459 unbind_variable (identifier);
2462 SHELL_VAR *new_value;
2464 new_value = bind_variable (identifier, value_cell(old_value), 0);
2465 new_value->attributes = old_value->attributes;
2466 dispose_variable (old_value);
2471 dispose_words (releaser);
2472 discard_unwind_frame ("for");
2476 #if defined (ARITH_FOR_COMMAND)
2477 /* Execute an arithmetic for command. The syntax is
2479 for (( init ; step ; test ))
2484 The execution should be exactly equivalent to
2487 while eval \(\( test \)\) ; do
2493 eval_arith_for_expr (l, okp)
2501 new = expand_words_no_vars (l);
2504 if (echo_command_at_execute)
2505 xtrace_print_arith_cmd (new);
2506 this_command_name = "(("; /* )) for expression error messages */
2508 command_string_index = 0;
2509 print_arith_command (new);
2510 if (signal_in_progress (DEBUG_TRAP) == 0)
2512 FREE (the_printed_command_except_trap);
2513 the_printed_command_except_trap = savestring (the_printed_command);
2516 r = run_debug_trap ();
2517 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2518 skip the command. */
2519 #if defined (DEBUGGER)
2520 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
2521 expresult = evalexp (new->word->word, okp);
2529 expresult = evalexp (new->word->word, okp);
2531 dispose_words (new);
2543 execute_arith_for_command (arith_for_command)
2544 ARITH_FOR_COM *arith_for_command;
2547 int expok, body_status, arith_lineno, save_lineno;
2549 body_status = EXECUTION_SUCCESS;
2551 save_lineno = line_number;
2553 if (arith_for_command->flags & CMD_IGNORE_RETURN)
2554 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
2556 this_command_name = "(("; /* )) for expression error messages */
2558 /* save the starting line number of the command so we can reset
2559 line_number before executing each expression -- for $LINENO
2560 and the DEBUG trap. */
2561 line_number = arith_lineno = arith_for_command->line;
2562 if (variable_context && interactive_shell)
2563 line_number -= function_line_number;
2565 /* Evaluate the initialization expression. */
2566 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
2569 line_number = save_lineno;
2570 return (EXECUTION_FAILURE);
2575 /* Evaluate the test expression. */
2576 line_number = arith_lineno;
2577 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
2578 line_number = save_lineno;
2582 body_status = EXECUTION_FAILURE;
2589 /* Execute the body of the arithmetic for command. */
2591 body_status = execute_command (arith_for_command->action);
2594 /* Handle any `break' or `continue' commands executed by the body. */
2608 /* Evaluate the step expression. */
2609 line_number = arith_lineno;
2610 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
2611 line_number = save_lineno;
2615 body_status = EXECUTION_FAILURE;
2621 line_number = save_lineno;
2623 return (body_status);
2627 #if defined (SELECT_COMMAND)
2628 static int LINES, COLS, tabsize;
2630 #define RP_SPACE ") "
2631 #define RP_SPACE_LEN 2
2633 /* XXX - does not handle numbers > 1000000 at all. */
2634 #define NUMBER_LEN(s) \
2638 : ((s < 10000) ? 4 \
2639 : ((s < 100000) ? 5 \
2643 print_index_and_element (len, ind, list)
2647 register WORD_LIST *l;
2652 for (i = ind, l = list; l && --i; l = l->next)
2654 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
2655 return (STRLEN (l->word->word));
2664 if ((to / tabsize) > (from / tabsize))
2666 putc ('\t', stderr);
2667 from += tabsize - from % tabsize;
2678 print_select_list (list, list_len, max_elem_len, indices_len)
2680 int list_len, max_elem_len, indices_len;
2682 int ind, row, elem_len, pos, cols, rows;
2683 int first_column_indices_len, other_indices_len;
2687 putc ('\n', stderr);
2691 cols = max_elem_len ? COLS / max_elem_len : 1;
2694 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
2695 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
2703 first_column_indices_len = NUMBER_LEN (rows);
2704 other_indices_len = indices_len;
2706 for (row = 0; row < rows; row++)
2712 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
2713 elem_len = print_index_and_element (indices_len, ind + 1, list);
2714 elem_len += indices_len + RP_SPACE_LEN;
2716 if (ind >= list_len)
2718 indent (pos + elem_len, pos + max_elem_len);
2719 pos += max_elem_len;
2721 putc ('\n', stderr);
2725 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2726 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2727 If the number is between 1 and LIST_LEN, return that selection. If EOF
2728 is read, return a null string. If a blank line is entered, or an invalid
2729 number is entered, the loop is executed again. */
2731 select_query (list, list_len, prompt, print_menu)
2737 int max_elem_len, indices_len, len;
2740 char *repl_string, *t;
2743 t = get_string_value ("LINES");
2744 LINES = (t && *t) ? atoi (t) : 24;
2746 t = get_string_value ("COLUMNS");
2747 COLS = (t && *t) ? atoi (t) : 80;
2750 t = get_string_value ("TABSIZE");
2751 tabsize = (t && *t) ? atoi (t) : 8;
2759 for (l = list; l; l = l->next)
2761 len = STRLEN (l->word->word);
2762 if (len > max_elem_len)
2765 indices_len = NUMBER_LEN (list_len);
2766 max_elem_len += indices_len + RP_SPACE_LEN + 2;
2771 print_select_list (list, list_len, max_elem_len, indices_len);
2772 fprintf (stderr, "%s", prompt);
2776 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
2779 return ((char *)NULL);
2781 repl_string = get_string_value ("REPLY");
2782 if (*repl_string == 0)
2787 if (legal_number (repl_string, &reply) == 0)
2789 if (reply < 1 || reply > list_len)
2792 for (l = list; l && --reply; l = l->next)
2794 return (l->word->word);
2798 /* Execute a SELECT command. The syntax is:
2799 SELECT word IN list DO command_list DONE
2800 Only `break' or `return' in command_list will terminate
2803 execute_select_command (select_command)
2804 SELECT_COM *select_command;
2806 WORD_LIST *releaser, *list;
2808 char *identifier, *ps3_prompt, *selection;
2809 int retval, list_len, show_menu, save_line_number;
2811 if (check_identifier (select_command->name, 1) == 0)
2812 return (EXECUTION_FAILURE);
2814 save_line_number = line_number;
2815 line_number = select_command->line;
2817 command_string_index = 0;
2818 print_select_command_head (select_command);
2820 if (echo_command_at_execute)
2821 xtrace_print_select_command_head (select_command);
2824 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2826 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2829 FREE (the_printed_command_except_trap);
2830 the_printed_command_except_trap = savestring (the_printed_command);
2833 retval = run_debug_trap ();
2834 #if defined (DEBUGGER)
2835 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2836 skip the command. */
2837 if (debugging_mode && retval != EXECUTION_SUCCESS)
2838 return (EXECUTION_SUCCESS);
2842 identifier = select_command->name->word;
2844 /* command and arithmetic substitution, parameter and variable expansion,
2845 word splitting, pathname expansion, and quote removal. */
2846 list = releaser = expand_words_no_vars (select_command->map_list);
2847 list_len = list_length (list);
2848 if (list == 0 || list_len == 0)
2851 dispose_words (list);
2852 line_number = save_line_number;
2853 return (EXECUTION_SUCCESS);
2856 begin_unwind_frame ("select");
2857 add_unwind_protect (dispose_words, releaser);
2859 if (select_command->flags & CMD_IGNORE_RETURN)
2860 select_command->action->flags |= CMD_IGNORE_RETURN;
2862 retval = EXECUTION_SUCCESS;
2867 line_number = select_command->line;
2868 ps3_prompt = get_string_value ("PS3");
2869 if (ps3_prompt == 0)
2873 selection = select_query (list, list_len, ps3_prompt, show_menu);
2877 /* select_query returns EXECUTION_FAILURE if the read builtin
2878 fails, so we want to return failure in this case. */
2879 retval = EXECUTION_FAILURE;
2883 v = bind_variable (identifier, selection, 0);
2884 if (readonly_p (v) || noassign_p (v))
2886 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2888 last_command_exit_value = EXECUTION_FAILURE;
2889 jump_to_top_level (FORCE_EOF);
2893 dispose_words (releaser);
2894 discard_unwind_frame ("select");
2896 line_number = save_line_number;
2897 return (EXECUTION_FAILURE);
2901 retval = execute_command (select_command->action);
2919 #if defined (KSH_COMPATIBLE_SELECT)
2921 selection = get_string_value ("REPLY");
2922 if (selection && *selection == '\0')
2928 line_number = save_line_number;
2930 dispose_words (releaser);
2931 discard_unwind_frame ("select");
2934 #endif /* SELECT_COMMAND */
2936 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2937 The pattern_list is a linked list of pattern clauses; each clause contains
2938 some patterns to compare word_desc against, and an associated command to
2941 execute_case_command (case_command)
2942 CASE_COM *case_command;
2944 register WORD_LIST *list;
2945 WORD_LIST *wlist, *es;
2946 PATTERN_LIST *clauses;
2947 char *word, *pattern;
2948 int retval, match, ignore_return, save_line_number;
2950 save_line_number = line_number;
2951 line_number = case_command->line;
2953 command_string_index = 0;
2954 print_case_command_head (case_command);
2956 if (echo_command_at_execute)
2957 xtrace_print_case_command_head (case_command);
2960 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2962 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2965 FREE (the_printed_command_except_trap);
2966 the_printed_command_except_trap = savestring (the_printed_command);
2969 retval = run_debug_trap();
2970 #if defined (DEBUGGER)
2971 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2972 skip the command. */
2973 if (debugging_mode && retval != EXECUTION_SUCCESS)
2975 line_number = save_line_number;
2976 return (EXECUTION_SUCCESS);
2980 wlist = expand_word_unsplit (case_command->word, 0);
2981 word = wlist ? string_list (wlist) : savestring ("");
2982 dispose_words (wlist);
2984 retval = EXECUTION_SUCCESS;
2985 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2987 begin_unwind_frame ("case");
2988 add_unwind_protect ((Function *)xfree, word);
2990 #define EXIT_CASE() goto exit_case_command
2992 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2995 for (list = clauses->patterns; list; list = list->next)
2997 es = expand_word_leave_quoted (list->word, 0);
2999 if (es && es->word && es->word->word && *(es->word->word))
3000 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
3003 pattern = (char *)xmalloc (1);
3007 /* Since the pattern does not undergo quote removal (as per
3008 Posix.2, section 3.9.4.3), the strmatch () call must be able
3009 to recognize backslashes as escape characters. */
3010 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
3019 if (clauses->action && ignore_return)
3020 clauses->action->flags |= CMD_IGNORE_RETURN;
3021 retval = execute_command (clauses->action);
3023 while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3024 if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3036 discard_unwind_frame ("case");
3037 line_number = save_line_number;
3044 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3045 Repeatedly execute action while executing test produces
3046 EXECUTION_SUCCESS. */
3048 execute_while_command (while_command)
3049 WHILE_COM *while_command;
3051 return (execute_while_or_until (while_command, CMD_WHILE));
3054 /* UNTIL is just like WHILE except that the test result is negated. */
3056 execute_until_command (while_command)
3057 WHILE_COM *while_command;
3059 return (execute_while_or_until (while_command, CMD_UNTIL));
3062 /* The body for both while and until. The only difference between the
3063 two is that the test value is treated differently. TYPE is
3064 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3065 be EXECUTION_SUCCESS if no commands in the body are executed, and
3066 the status of the last command executed in the body otherwise. */
3068 execute_while_or_until (while_command, type)
3069 WHILE_COM *while_command;
3072 int return_value, body_status;
3074 body_status = EXECUTION_SUCCESS;
3077 while_command->test->flags |= CMD_IGNORE_RETURN;
3078 if (while_command->flags & CMD_IGNORE_RETURN)
3079 while_command->action->flags |= CMD_IGNORE_RETURN;
3083 return_value = execute_command (while_command->test);
3086 /* Need to handle `break' in the test when we would break out of the
3087 loop. The job control code will set `breaking' to loop_level
3088 when a job in a loop is stopped with SIGTSTP. If the stopped job
3089 is in the loop test, `breaking' will not be reset unless we do
3090 this, and the shell will cease to execute commands. */
3091 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3097 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3105 body_status = execute_command (while_command->action);
3123 return (body_status);
3126 /* IF test THEN command [ELSE command].
3127 IF also allows ELIF in the place of ELSE IF, but
3128 the parser makes *that* stupidity transparent. */
3130 execute_if_command (if_command)
3133 int return_value, save_line_number;
3135 save_line_number = line_number;
3136 if_command->test->flags |= CMD_IGNORE_RETURN;
3137 return_value = execute_command (if_command->test);
3138 line_number = save_line_number;
3140 if (return_value == EXECUTION_SUCCESS)
3144 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3145 if_command->true_case->flags |= CMD_IGNORE_RETURN;
3147 return (execute_command (if_command->true_case));
3153 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3154 if_command->false_case->flags |= CMD_IGNORE_RETURN;
3156 return (execute_command (if_command->false_case));
3160 #if defined (DPAREN_ARITHMETIC)
3162 execute_arith_command (arith_command)
3163 ARITH_COM *arith_command;
3165 int expok, save_line_number, retval;
3172 save_line_number = line_number;
3173 this_command_name = "(("; /* )) */
3174 line_number = arith_command->line;
3175 /* If we're in a function, update the line number information. */
3176 if (variable_context && interactive_shell)
3177 line_number -= function_line_number;
3179 command_string_index = 0;
3180 print_arith_command (arith_command->exp);
3182 if (signal_in_progress (DEBUG_TRAP) == 0)
3184 FREE (the_printed_command_except_trap);
3185 the_printed_command_except_trap = savestring (the_printed_command);
3188 /* Run the debug trap before each arithmetic command, but do it after we
3189 update the line number information and before we expand the various
3190 words in the expression. */
3191 retval = run_debug_trap ();
3192 #if defined (DEBUGGER)
3193 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3194 skip the command. */
3195 if (debugging_mode && retval != EXECUTION_SUCCESS)
3197 line_number = save_line_number;
3198 return (EXECUTION_SUCCESS);
3202 new = expand_words_no_vars (arith_command->exp);
3204 /* If we're tracing, make a new word list with `((' at the front and `))'
3205 at the back and print it. */
3206 if (echo_command_at_execute)
3207 xtrace_print_arith_cmd (new);
3211 exp = new->next ? string_list (new) : new->word->word;
3212 expresult = evalexp (exp, &expok);
3213 line_number = save_line_number;
3214 if (exp != new->word->word)
3216 dispose_words (new);
3225 return (EXECUTION_FAILURE);
3227 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3229 #endif /* DPAREN_ARITHMETIC */
3231 #if defined (COND_COMMAND)
3233 static char * const nullstr = "";
3236 execute_cond_node (cond)
3239 int result, invert, patmatch, rmatch, mflags, ignore;
3242 invert = (cond->flags & CMD_INVERT_RETURN);
3243 ignore = (cond->flags & CMD_IGNORE_RETURN);
3247 cond->left->flags |= CMD_IGNORE_RETURN;
3249 cond->right->flags |= CMD_IGNORE_RETURN;
3252 if (cond->type == COND_EXPR)
3253 result = execute_cond_node (cond->left);
3254 else if (cond->type == COND_OR)
3256 result = execute_cond_node (cond->left);
3257 if (result != EXECUTION_SUCCESS)
3258 result = execute_cond_node (cond->right);
3260 else if (cond->type == COND_AND)
3262 result = execute_cond_node (cond->left);
3263 if (result == EXECUTION_SUCCESS)
3264 result = execute_cond_node (cond->right);
3266 else if (cond->type == COND_UNARY)
3269 comsub_ignore_return++;
3270 arg1 = cond_expand_word (cond->left->op, 0);
3272 comsub_ignore_return--;
3275 if (echo_command_at_execute)
3276 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3277 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3278 if (arg1 != nullstr)
3281 else if (cond->type == COND_BINARY)
3284 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3285 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
3286 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3287 #if defined (COND_REGEXP)
3288 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3289 cond->op->word[2] == '\0');
3293 comsub_ignore_return++;
3294 arg1 = cond_expand_word (cond->left->op, 0);
3296 comsub_ignore_return--;
3300 comsub_ignore_return++;
3301 arg2 = cond_expand_word (cond->right->op,
3302 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3304 comsub_ignore_return--;
3308 if (echo_command_at_execute)
3309 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3311 #if defined (COND_REGEXP)
3314 mflags = SHMAT_PWARN;
3315 #if defined (ARRAY_VARS)
3316 mflags |= SHMAT_SUBEXP;
3319 result = sh_regmatch (arg1, arg2, mflags);
3322 #endif /* COND_REGEXP */
3327 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3329 : EXECUTION_FAILURE;
3332 if (arg1 != nullstr)
3334 if (arg2 != nullstr)
3339 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3340 jump_to_top_level (DISCARD);
3341 result = EXECUTION_FAILURE;
3345 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3351 execute_cond_command (cond_command)
3352 COND_COM *cond_command;
3354 int retval, save_line_number;
3356 retval = EXECUTION_SUCCESS;
3357 save_line_number = line_number;
3359 this_command_name = "[[";
3360 line_number = cond_command->line;
3361 /* If we're in a function, update the line number information. */
3362 if (variable_context && interactive_shell)
3363 line_number -= function_line_number;
3364 command_string_index = 0;
3365 print_cond_command (cond_command);
3367 if (signal_in_progress (DEBUG_TRAP) == 0)
3369 FREE (the_printed_command_except_trap);
3370 the_printed_command_except_trap = savestring (the_printed_command);
3373 /* Run the debug trap before each conditional command, but do it after we
3374 update the line number information. */
3375 retval = run_debug_trap ();
3376 #if defined (DEBUGGER)
3377 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3378 skip the command. */
3379 if (debugging_mode && retval != EXECUTION_SUCCESS)
3381 line_number = save_line_number;
3382 return (EXECUTION_SUCCESS);
3387 debug_print_cond_command (cond_command);
3390 last_command_exit_value = retval = execute_cond_node (cond_command);
3391 line_number = save_line_number;
3394 #endif /* COND_COMMAND */
3404 var = bind_variable ("_", arg, 0);
3405 VUNSETATTR (var, att_exported);
3408 /* Execute a null command. Fork a subshell if the command uses pipes or is
3409 to be run asynchronously. This handles all the side effects that are
3410 supposed to take place. */
3412 execute_null_command (redirects, pipe_in, pipe_out, async)
3413 REDIRECT *redirects;
3414 int pipe_in, pipe_out, async;
3420 for (forcefork = 0, rd = redirects; rd; rd = rd->next)
3421 forcefork += rd->rflags & REDIR_VARASSIGN;
3423 if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
3425 /* We have a null command, but we really want a subshell to take
3426 care of it. Just fork, do piping and redirections, and exit. */
3427 if (make_child ((char *)NULL, async) == 0)
3429 /* Cancel traps, in trap.c. */
3430 restore_original_signals (); /* XXX */
3432 do_piping (pipe_in, pipe_out);
3434 #if defined (COPROCESS_SUPPORT)
3438 subshell_environment = 0;
3440 subshell_environment |= SUBSHELL_ASYNC;
3441 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3442 subshell_environment |= SUBSHELL_PIPE;
3444 if (do_redirections (redirects, RX_ACTIVE) == 0)
3445 exit (EXECUTION_SUCCESS);
3447 exit (EXECUTION_FAILURE);
3451 close_pipes (pipe_in, pipe_out);
3452 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3453 unlink_fifo_list ();
3455 return (EXECUTION_SUCCESS);
3460 /* Even if there aren't any command names, pretend to do the
3461 redirections that are specified. The user expects the side
3462 effects to take place. If the redirections fail, then return
3463 failure. Otherwise, if a command substitution took place while
3464 expanding the command or a redirection, return the value of that
3465 substitution. Otherwise, return EXECUTION_SUCCESS. */
3467 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
3468 cleanup_redirects (redirection_undo_list);
3469 redirection_undo_list = (REDIRECT *)NULL;
3472 return (EXECUTION_FAILURE);
3473 else if (last_command_subst_pid != NO_PID)
3474 return (last_command_exit_value);
3476 return (EXECUTION_SUCCESS);
3480 /* This is a hack to suppress word splitting for assignment statements
3481 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3483 fix_assignment_words (words)
3496 for (w = words; w; w = w->next)
3497 if (w->word->flags & W_ASSIGNMENT)
3501 b = builtin_address_internal (words->word->word, 0);
3502 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3504 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3505 words->word->flags |= W_ASSNBLTIN;
3507 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
3508 #if defined (ARRAY_VARS)
3510 w->word->flags |= W_ASSIGNASSOC;
3513 #if defined (ARRAY_VARS)
3514 /* Note that we saw an associative array option to a builtin that takes
3515 assignment statements. This is a bit of a kludge. */
3516 else if (w->word->word[0] == '-' && strchr (w->word->word, 'A'))
3520 b = builtin_address_internal (words->word->word, 0);
3521 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3523 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3524 words->word->flags |= W_ASSNBLTIN;
3526 if (words->word->flags & W_ASSNBLTIN)
3532 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3533 to PATHNAME, is a directory. Used by the autocd code below. */
3535 is_dirname (pathname)
3539 temp = search_for_command (pathname);
3540 return (temp ? file_isdir (temp) : file_isdir (pathname));
3543 /* The meaty part of all the executions. We have to start hacking the
3544 real execution of commands here. Fork a process, set things up,
3545 execute the command. */
3547 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
3548 SIMPLE_COM *simple_command;
3549 int pipe_in, pipe_out, async;
3550 struct fd_bitmap *fds_to_close;
3552 WORD_LIST *words, *lastword;
3553 char *command_line, *lastarg, *temp;
3554 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
3555 pid_t old_last_async_pid;
3556 sh_builtin_func_t *builtin;
3559 result = EXECUTION_SUCCESS;
3560 special_builtin_failed = builtin_is_special = 0;
3561 command_line = (char *)0;
3563 /* If we're in a function, update the line number information. */
3564 if (variable_context && interactive_shell && sourcelevel == 0)
3565 line_number -= function_line_number;
3567 /* Remember what this command line looks like at invocation. */
3568 command_string_index = 0;
3569 print_simple_command (simple_command);
3572 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3574 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3577 FREE (the_printed_command_except_trap);
3578 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
3581 /* Run the debug trap before each simple command, but do it after we
3582 update the line number information. */
3583 result = run_debug_trap ();
3584 #if defined (DEBUGGER)
3585 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3586 skip the command. */
3587 if (debugging_mode && result != EXECUTION_SUCCESS)
3588 return (EXECUTION_SUCCESS);
3592 simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
3594 last_command_subst_pid = NO_PID;
3595 old_last_async_pid = last_asynchronous_pid;
3597 already_forked = dofork = 0;
3599 /* If we're in a pipeline or run in the background, set DOFORK so we
3600 make the child early, before word expansion. This keeps assignment
3601 statements from affecting the parent shell's environment when they
3603 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
3605 /* Something like `%2 &' should restart job 2 in the background, not cause
3606 the shell to fork here. */
3607 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
3608 simple_command->words && simple_command->words->word &&
3609 simple_command->words->word->word &&
3610 (simple_command->words->word->word[0] == '%'))
3615 /* Do this now, because execute_disk_command will do it anyway in the
3616 vast majority of cases. */
3617 maybe_make_export_env ();
3619 /* Don't let a DEBUG trap overwrite the command string to be saved with
3620 the process/job associated with this child. */
3621 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
3624 simple_command->flags |= CMD_NO_FORK;
3626 subshell_environment = SUBSHELL_FORK;
3627 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3628 subshell_environment |= SUBSHELL_PIPE;
3630 subshell_environment |= SUBSHELL_ASYNC;
3632 /* We need to do this before piping to handle some really
3633 pathological cases where one of the pipe file descriptors
3636 close_fd_bitmap (fds_to_close);
3638 do_piping (pipe_in, pipe_out);
3639 pipe_in = pipe_out = NO_PIPE;
3640 #if defined (COPROCESS_SUPPORT)
3644 last_asynchronous_pid = old_last_async_pid;
3648 close_pipes (pipe_in, pipe_out);
3649 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3650 unlink_fifo_list ();
3652 command_line = (char *)NULL; /* don't free this. */
3653 bind_lastarg ((char *)NULL);
3658 /* If we are re-running this as the result of executing the `command'
3659 builtin, do not expand the command words a second time. */
3660 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
3662 current_fds_to_close = fds_to_close;
3663 fix_assignment_words (simple_command->words);
3664 /* Pass the ignore return flag down to command substitutions */
3665 if (simple_command->flags & CMD_IGNORE_RETURN) /* XXX */
3666 comsub_ignore_return++;
3667 words = expand_words (simple_command->words);
3668 if (simple_command->flags & CMD_IGNORE_RETURN)
3669 comsub_ignore_return--;
3670 current_fds_to_close = (struct fd_bitmap *)NULL;
3673 words = copy_word_list (simple_command->words);
3675 /* It is possible for WORDS not to have anything left in it.
3676 Perhaps all the words consisted of `$foo', and there was
3677 no variable `$foo'. */
3680 this_command_name = 0;
3681 result = execute_null_command (simple_command->redirects,
3683 already_forked ? 0 : async);
3688 bind_lastarg ((char *)NULL);
3689 set_pipestatus_from_exit (result);
3694 lastarg = (char *)NULL;
3696 begin_unwind_frame ("simple-command");
3698 if (echo_command_at_execute)
3699 xtrace_print_word_list (words, 1);
3701 builtin = (sh_builtin_func_t *)NULL;
3702 func = (SHELL_VAR *)NULL;
3703 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
3705 /* Posix.2 says special builtins are found before functions. We
3706 don't set builtin_is_special anywhere other than here, because
3707 this path is followed only when the `command' builtin is *not*
3708 being used, and we don't want to exit the shell if a special
3709 builtin executed with `command builtin' fails. `command' is not
3710 a special builtin. */
3711 if (posixly_correct)
3713 builtin = find_special_builtin (words->word->word);
3715 builtin_is_special = 1;
3718 func = find_function (words->word->word);
3721 /* In POSIX mode, assignment errors in the temporary environment cause a
3722 non-interactive shell to exit. */
3723 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
3725 last_command_exit_value = EXECUTION_FAILURE;
3726 jump_to_top_level (ERREXIT);
3729 add_unwind_protect (dispose_words, words);
3732 /* Bind the last word in this command to "$_" after execution. */
3733 for (lastword = words; lastword->next; lastword = lastword->next)
3735 lastarg = lastword->word->word;
3737 #if defined (JOB_CONTROL)
3738 /* Is this command a job control related thing? */
3739 if (words->word->word[0] == '%' && already_forked == 0)
3741 this_command_name = async ? "bg" : "fg";
3742 last_shell_builtin = this_shell_builtin;
3743 this_shell_builtin = builtin_address (this_command_name);
3744 result = (*this_shell_builtin) (words);
3748 /* One other possiblilty. The user may want to resume an existing job.
3749 If they do, find out whether this word is a candidate for a running
3751 if (job_control && already_forked == 0 && async == 0 &&
3752 !first_word_quoted &&
3754 words->word->word[0] &&
3755 !simple_command->redirects &&
3756 pipe_in == NO_PIPE &&
3757 pipe_out == NO_PIPE &&
3758 (temp = get_string_value ("auto_resume")))
3760 int job, jflags, started_status;
3762 jflags = JM_STOPPED|JM_FIRSTMATCH;
3763 if (STREQ (temp, "exact"))
3765 else if (STREQ (temp, "substring"))
3766 jflags |= JM_SUBSTRING;
3768 jflags |= JM_PREFIX;
3769 job = get_job_by_name (words->word->word, jflags);
3772 run_unwind_frame ("simple-command");
3773 this_command_name = "fg";
3774 last_shell_builtin = this_shell_builtin;
3775 this_shell_builtin = builtin_address ("fg");
3777 started_status = start_job (job, 1);
3778 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
3781 #endif /* JOB_CONTROL */
3784 /* Remember the name of this command globally. */
3785 this_command_name = words->word->word;
3789 /* This command could be a shell builtin or a user-defined function.
3790 We have already found special builtins by this time, so we do not
3791 set builtin_is_special. If this is a function or builtin, and we
3792 have pipes, then fork a subshell in here. Otherwise, just execute
3793 the command directly. */
3794 if (func == 0 && builtin == 0)
3795 builtin = find_shell_builtin (this_command_name);
3797 last_shell_builtin = this_shell_builtin;
3798 this_shell_builtin = builtin;
3800 if (builtin || func)
3803 unwind_protect_int (executing_builtin); /* modified in execute_builtin */
3806 /* reset_terminating_signals (); */ /* XXX */
3807 /* Cancel traps, in trap.c. */
3808 restore_original_signals ();
3812 if ((simple_command->flags & CMD_STDIN_REDIR) &&
3813 pipe_in == NO_PIPE &&
3814 (stdin_redirects (simple_command->redirects) == 0))
3815 async_redirect_stdin ();
3816 setup_async_signals ();
3820 execute_subshell_builtin_or_function
3821 (words, simple_command->redirects, builtin, func,
3822 pipe_in, pipe_out, async, fds_to_close,
3823 simple_command->flags);
3828 result = execute_builtin_or_function
3829 (words, builtin, func, simple_command->redirects, fds_to_close,
3830 simple_command->flags);
3833 if (result > EX_SHERRBASE)
3835 result = builtin_status (result);
3836 if (builtin_is_special)
3837 special_builtin_failed = 1;
3839 /* In POSIX mode, if there are assignment statements preceding
3840 a special builtin, they persist after the builtin
3842 if (posixly_correct && builtin_is_special && temporary_env)
3843 merge_temporary_env ();
3847 if (result == EX_USAGE)
3848 result = EX_BADUSAGE;
3849 else if (result > EX_SHERRBASE)
3850 result = EXECUTION_FAILURE;
3853 set_pipestatus_from_exit (result);
3859 if (autocd && interactive && words->word && is_dirname (words->word->word))
3861 words = make_word_list (make_word ("cd"), words);
3862 xtrace_print_word_list (words, 0);
3866 if (command_line == 0)
3867 command_line = savestring (the_printed_command_except_trap);
3869 #if defined (PROCESS_SUBSTITUTION)
3870 if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
3871 simple_command->flags &= ~CMD_NO_FORK;
3874 execute_disk_command (words, simple_command->redirects, command_line,
3875 pipe_in, pipe_out, async, fds_to_close,
3876 simple_command->flags);
3879 bind_lastarg (lastarg);
3880 FREE (command_line);
3881 dispose_words (words);
3882 discard_unwind_frame ("simple-command");
3883 this_command_name = (char *)NULL; /* points to freed memory now */
3887 /* Translate the special builtin exit statuses. We don't really need a
3888 function for this; it's a placeholder for future work. */
3890 builtin_status (result)
3904 r = EXECUTION_FAILURE;
3907 r = EXECUTION_SUCCESS;
3914 execute_builtin (builtin, words, flags, subshell)
3915 sh_builtin_func_t *builtin;
3917 int flags, subshell;
3919 int old_e_flag, result, eval_unwind;
3924 /* XXX -- added 12/11 */
3925 terminate_immediately++;
3929 old_e_flag = exit_immediately_on_error;
3930 /* The eval builtin calls parse_and_execute, which does not know about
3931 the setting of flags, and always calls the execution functions with
3932 flags that will exit the shell on an error if -e is set. If the
3933 eval builtin is being called, and we're supposed to ignore the exit
3934 value of the command, we turn the -e flag off ourselves and disable
3935 the ERR trap, then restore them when the command completes. This is
3936 also a problem (as below) for the command and source/. builtins. */
3937 if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
3938 (builtin == eval_builtin || builtin == command_builtin || builtin == source_builtin))
3940 begin_unwind_frame ("eval_builtin");
3941 unwind_protect_int (exit_immediately_on_error);
3942 error_trap = TRAP_STRING (ERROR_TRAP);
3945 error_trap = savestring (error_trap);
3946 add_unwind_protect (xfree, error_trap);
3947 add_unwind_protect (set_error_trap, error_trap);
3948 restore_default_signal (ERROR_TRAP);
3950 exit_immediately_on_error = 0;
3956 /* The temporary environment for a builtin is supposed to apply to
3957 all commands executed by that builtin. Currently, this is a
3958 problem only with the `unset', `source' and `eval' builtins. */
3960 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
3965 begin_unwind_frame ("builtin_env");
3969 push_scope (VC_BLTNENV, temporary_env);
3971 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
3972 temporary_env = (HASH_TABLE *)NULL;
3976 /* `return' does a longjmp() back to a saved environment in execute_function.
3977 If a variable assignment list preceded the command, and the shell is
3978 running in POSIX mode, we need to merge that into the shell_variables
3979 table, since `return' is a POSIX special builtin. */
3980 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3982 begin_unwind_frame ("return_temp_env");
3983 add_unwind_protect (merge_temporary_env, (char *)NULL);
3986 executing_builtin++;
3987 result = ((*builtin) (words->next));
3989 /* This shouldn't happen, but in case `return' comes back instead of
3990 longjmp'ing, we need to unwind. */
3991 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3992 discard_unwind_frame ("return_temp_env");
3994 if (subshell == 0 && isbltinenv)
3995 run_unwind_frame ("builtin_env");
3999 exit_immediately_on_error += old_e_flag;
4002 set_error_trap (error_trap);
4005 discard_unwind_frame ("eval_builtin");
4009 /* XXX -- added 12/11 */
4010 terminate_immediately--;
4017 execute_function (var, words, flags, fds_to_close, async, subshell)
4021 struct fd_bitmap *fds_to_close;
4022 int async, subshell;
4024 int return_val, result;
4025 COMMAND *tc, *fc, *save_current;
4026 char *debug_trap, *error_trap, *return_trap;
4027 #if defined (ARRAY_VARS)
4028 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
4029 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
4031 FUNCTION_DEF *shell_fn;
4036 #if 0 /* for bash-4.2 */
4037 if (funcnest_max > 0 && funcnest >= funcnest_max)
4039 internal_error ("%s: maximum function nesting level exceeded (%d)", var->name, funcnest);
4040 jump_to_top_level (DISCARD);
4044 #if defined (ARRAY_VARS)
4045 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4046 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4047 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4050 tc = (COMMAND *)copy_command (function_cell (var));
4051 if (tc && (flags & CMD_IGNORE_RETURN))
4052 tc->flags |= CMD_IGNORE_RETURN;
4056 begin_unwind_frame ("function_calling");
4057 push_context (var->name, subshell, temporary_env);
4058 add_unwind_protect (pop_context, (char *)NULL);
4059 unwind_protect_int (line_number);
4060 unwind_protect_int (return_catch_flag);
4061 unwind_protect_jmp_buf (return_catch);
4062 add_unwind_protect (dispose_command, (char *)tc);
4063 unwind_protect_pointer (this_shell_function);
4064 unwind_protect_int (loop_level);
4065 unwind_protect_int (funcnest);
4068 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
4070 temporary_env = (HASH_TABLE *)NULL;
4072 this_shell_function = var;
4073 make_funcname_visible (1);
4075 debug_trap = TRAP_STRING(DEBUG_TRAP);
4076 error_trap = TRAP_STRING(ERROR_TRAP);
4077 return_trap = TRAP_STRING(RETURN_TRAP);
4079 /* The order of the unwind protects for debug_trap, error_trap and
4080 return_trap is important here! unwind-protect commands are run
4081 in reverse order of registration. If this causes problems, take
4082 out the xfree unwind-protect calls and live with the small memory leak. */
4084 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4085 if the function has the trace attribute set, it inherits the DEBUG trap */
4086 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4090 debug_trap = savestring (debug_trap);
4091 add_unwind_protect (xfree, debug_trap);
4092 add_unwind_protect (set_debug_trap, debug_trap);
4094 restore_default_signal (DEBUG_TRAP);
4097 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4098 if (error_trap && error_trace_mode == 0)
4102 error_trap = savestring (error_trap);
4103 add_unwind_protect (xfree, error_trap);
4104 add_unwind_protect (set_error_trap, error_trap);
4106 restore_default_signal (ERROR_TRAP);
4109 /* Shell functions inherit the RETURN trap if function tracing is on
4110 globally or on individually for this function. */
4112 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4114 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
4119 return_trap = savestring (return_trap);
4120 add_unwind_protect (xfree, return_trap);
4121 add_unwind_protect (set_return_trap, return_trap);
4123 restore_default_signal (RETURN_TRAP);
4127 #if defined (ARRAY_VARS)
4128 /* This is quite similar to the code in shell.c and elsewhere. */
4129 shell_fn = find_function_def (this_shell_function->name);
4130 sfile = shell_fn ? shell_fn->source_file : "";
4131 array_push (funcname_a, this_shell_function->name);
4133 array_push (bash_source_a, sfile);
4134 t = itos (executing_line_number ());
4135 array_push (bash_lineno_a, t);
4139 /* The temporary environment for a function is supposed to apply to
4140 all commands executed within the function body. */
4142 remember_args (words->next, 1);
4144 /* Update BASH_ARGV and BASH_ARGC */
4146 push_args (words->next);
4148 /* Number of the line on which the function body starts. */
4149 line_number = function_line_number = tc->line;
4151 #if defined (JOB_CONTROL)
4153 stop_pipeline (async, (COMMAND *)NULL);
4158 return_catch_flag++;
4159 return_val = setjmp (return_catch);
4163 result = return_catch_value;
4164 /* Run the RETURN trap in the function's context. */
4165 save_current = currently_executing_command;
4167 currently_executing_command = save_current;
4171 /* Run the debug trap here so we can trap at the start of a function's
4172 execution rather than the execution of the body's first command. */
4173 showing_function_line = 1;
4174 save_current = currently_executing_command;
4175 result = run_debug_trap ();
4176 #if defined (DEBUGGER)
4177 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4178 skip the command. */
4179 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
4181 showing_function_line = 0;
4182 currently_executing_command = save_current;
4183 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4185 /* Run the RETURN trap in the function's context */
4186 save_current = currently_executing_command;
4188 currently_executing_command = save_current;
4191 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4193 save_current = currently_executing_command;
4195 currently_executing_command = save_current;
4197 showing_function_line = 0;
4200 /* Restore BASH_ARGC and BASH_ARGV */
4205 run_unwind_frame ("function_calling");
4207 #if defined (ARRAY_VARS)
4208 /* These two variables cannot be unset, and cannot be affected by the
4210 array_pop (bash_source_a);
4211 array_pop (bash_lineno_a);
4213 /* FUNCNAME can be unset, and so can potentially be changed by the
4215 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4216 if (nfv == funcname_v)
4217 array_pop (funcname_a);
4220 if (variable_context == 0 || this_shell_function == 0)
4222 make_funcname_visible (0);
4223 #if defined (PROCESS_SUBSTITUTION)
4224 unlink_fifo_list ();
4231 /* A convenience routine for use by other parts of the shell to execute
4232 a particular shell function. */
4234 execute_shell_function (var, words)
4239 struct fd_bitmap *bitmap;
4241 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
4242 begin_unwind_frame ("execute-shell-function");
4243 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
4245 ret = execute_function (var, words, 0, bitmap, 0, 0);
4247 dispose_fd_bitmap (bitmap);
4248 discard_unwind_frame ("execute-shell-function");
4253 /* Execute a shell builtin or function in a subshell environment. This
4254 routine does not return; it only calls exit(). If BUILTIN is non-null,
4255 it points to a function to call to execute a shell builtin; otherwise
4256 VAR points at the body of a function to execute. WORDS is the arguments
4257 to the command, REDIRECTS specifies redirections to perform before the
4258 command is executed. */
4260 execute_subshell_builtin_or_function (words, redirects, builtin, var,
4261 pipe_in, pipe_out, async, fds_to_close,
4264 REDIRECT *redirects;
4265 sh_builtin_func_t *builtin;
4267 int pipe_in, pipe_out, async;
4268 struct fd_bitmap *fds_to_close;
4271 int result, r, funcvalue;
4272 #if defined (JOB_CONTROL)
4275 jobs_hack = (builtin == jobs_builtin) &&
4276 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
4279 /* A subshell is neither a login shell nor interactive. */
4280 login_shell = interactive = 0;
4283 subshell_environment |= SUBSHELL_ASYNC;
4284 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4285 subshell_environment |= SUBSHELL_PIPE;
4287 maybe_make_export_env (); /* XXX - is this needed? */
4289 #if defined (JOB_CONTROL)
4290 /* Eradicate all traces of job control after we fork the subshell, so
4291 all jobs begun by this subshell are in the same process group as
4292 the shell itself. */
4294 /* Allow the output of `jobs' to be piped. */
4296 kill_current_pipeline ();
4298 without_job_control ();
4300 set_sigchld_handler ();
4301 #endif /* JOB_CONTROL */
4303 set_sigint_handler ();
4306 close_fd_bitmap (fds_to_close);
4308 do_piping (pipe_in, pipe_out);
4310 if (do_redirections (redirects, RX_ACTIVE) != 0)
4311 exit (EXECUTION_FAILURE);
4315 /* Give builtins a place to jump back to on failure,
4316 so we don't go back up to main(). */
4317 result = setjmp (top_level);
4319 /* Give the return builtin a place to jump to when executed in a subshell
4322 if (return_catch_flag && builtin == return_builtin)
4323 funcvalue = setjmp (return_catch);
4325 if (result == EXITPROG)
4326 exit (last_command_exit_value);
4328 exit (EXECUTION_FAILURE);
4330 exit (return_catch_value);
4333 r = execute_builtin (builtin, words, flags, 1);
4342 r = execute_function (var, words, flags, fds_to_close, async, 1);
4348 /* Execute a builtin or function in the current shell context. If BUILTIN
4349 is non-null, it is the builtin command to execute, otherwise VAR points
4350 to the body of a function. WORDS are the command's arguments, REDIRECTS
4351 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4352 file descriptors to close.
4354 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4355 not undone before this function returns. */
4357 execute_builtin_or_function (words, builtin, var, redirects,
4358 fds_to_close, flags)
4360 sh_builtin_func_t *builtin;
4362 REDIRECT *redirects;
4363 struct fd_bitmap *fds_to_close;
4367 REDIRECT *saved_undo_list;
4369 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
4371 cleanup_redirects (redirection_undo_list);
4372 redirection_undo_list = (REDIRECT *)NULL;
4373 dispose_exec_redirects ();
4374 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
4377 saved_undo_list = redirection_undo_list;
4379 /* Calling the "exec" builtin changes redirections forever. */
4380 if (builtin == exec_builtin)
4382 dispose_redirects (saved_undo_list);
4383 saved_undo_list = exec_redirection_undo_list;
4384 exec_redirection_undo_list = (REDIRECT *)NULL;
4387 dispose_exec_redirects ();
4389 if (saved_undo_list)
4391 begin_unwind_frame ("saved redirects");
4392 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
4395 redirection_undo_list = (REDIRECT *)NULL;
4398 result = execute_builtin (builtin, words, flags, 0);
4400 result = execute_function (var, words, flags, fds_to_close, 0, 0);
4402 /* We do this before undoing the effects of any redirections. */
4405 if (ferror (stdout))
4408 /* If we are executing the `command' builtin, but this_shell_builtin is
4409 set to `exec_builtin', we know that we have something like
4410 `command exec [redirection]', since otherwise `exec' would have
4411 overwritten the shell and we wouldn't get here. In this case, we
4412 want to behave as if the `command' builtin had not been specified
4413 and preserve the redirections. */
4414 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
4416 if (saved_undo_list)
4417 dispose_redirects (saved_undo_list);
4418 redirection_undo_list = exec_redirection_undo_list;
4419 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
4420 discard_unwind_frame ("saved_redirects");
4423 if (saved_undo_list)
4425 redirection_undo_list = saved_undo_list;
4426 discard_unwind_frame ("saved redirects");
4429 if (redirection_undo_list)
4431 cleanup_redirects (redirection_undo_list);
4432 redirection_undo_list = (REDIRECT *)NULL;
4439 setup_async_signals ()
4441 #if defined (__BEOS__)
4442 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
4445 #if defined (JOB_CONTROL)
4446 if (job_control == 0)
4449 set_signal_handler (SIGINT, SIG_IGN);
4450 set_signal_ignored (SIGINT);
4451 set_signal_handler (SIGQUIT, SIG_IGN);
4452 set_signal_ignored (SIGQUIT);
4456 /* Execute a simple command that is hopefully defined in a disk file
4461 3) look up the command
4464 6) If the execve failed, see if the file has executable mode set.
4465 If so, and it isn't a directory, then execute its contents as
4468 Note that the filename hashing stuff has to take place up here,
4469 in the parent. This is probably why the Bourne style shells
4470 don't handle it, since that would require them to go through
4471 this gnarly hair, for no good reason.
4473 NOTE: callers expect this to fork or exit(). */
4475 /* Name of a shell function to call when a command name is not found. */
4476 #ifndef NOTFOUND_HOOK
4477 # define NOTFOUND_HOOK "command_not_found_handle"
4481 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
4482 async, fds_to_close, cmdflags)
4484 REDIRECT *redirects;
4486 int pipe_in, pipe_out, async;
4487 struct fd_bitmap *fds_to_close;
4490 char *pathname, *command, **args;
4496 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
4497 pathname = words->word->word;
4499 #if defined (RESTRICTED_SHELL)
4500 command = (char *)NULL;
4501 if (restricted && mbschr (pathname, '/'))
4503 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4505 last_command_exit_value = EXECUTION_FAILURE;
4507 /* If we're not going to fork below, we must already be in a child
4508 process or a context in which it's safe to call exit(2). */
4509 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4510 exit (last_command_exit_value);
4514 #endif /* RESTRICTED_SHELL */
4516 command = search_for_command (pathname);
4520 maybe_make_export_env ();
4521 put_command_name_into_env (command);
4524 /* We have to make the child before we check for the non-existence
4525 of COMMAND, since we want the error messages to be redirected. */
4526 /* If we can get away without forking and there are no pipes to deal with,
4527 don't bother to fork, just directly exec the command. */
4528 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4531 pid = make_child (savestring (command_line), async);
4535 int old_interactive;
4538 /* This has been disabled for the time being. */
4539 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4540 if (posixly_correct == 0)
4541 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
4545 /* Cancel traps, in trap.c. */
4546 restore_original_signals ();
4548 /* restore_original_signals may have undone the work done
4549 by make_child to ensure that SIGINT and SIGQUIT are ignored
4550 in asynchronous children. */
4553 if ((cmdflags & CMD_STDIN_REDIR) &&
4554 pipe_in == NO_PIPE &&
4555 (stdin_redirects (redirects) == 0))
4556 async_redirect_stdin ();
4557 setup_async_signals ();
4560 /* This functionality is now provided by close-on-exec of the
4561 file descriptors manipulated by redirection and piping.
4562 Some file descriptors still need to be closed in all children
4563 because of the way bash does pipes; fds_to_close is a
4564 bitmap of all such file descriptors. */
4566 close_fd_bitmap (fds_to_close);
4568 do_piping (pipe_in, pipe_out);
4570 old_interactive = interactive;
4574 subshell_environment = SUBSHELL_FORK;
4576 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
4578 #if defined (PROCESS_SUBSTITUTION)
4579 /* Try to remove named pipes that may have been created as the
4580 result of redirections. */
4581 unlink_fifo_list ();
4582 #endif /* PROCESS_SUBSTITUTION */
4583 exit (EXECUTION_FAILURE);
4587 interactive = old_interactive;
4591 hookf = find_function (NOTFOUND_HOOK);
4594 internal_error (_("%s: command not found"), pathname);
4595 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
4598 wl = make_word_list (make_word (NOTFOUND_HOOK), words);
4599 exit (execute_shell_function (hookf, wl));
4602 /* Execve expects the command name to be in args[0]. So we
4603 leave it there, in the same format that the user used to
4605 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
4606 exit (shell_execve (command, args, export_env));
4611 /* Make sure that the pipes are closed in the parent. */
4612 close_pipes (pipe_in, pipe_out);
4613 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4614 if (variable_context == 0)
4615 unlink_fifo_list ();
4621 /* CPP defines to decide whether a particular index into the #! line
4622 corresponds to a valid interpreter name or argument character, or
4623 whitespace. The MSDOS define is to allow \r to be treated the same
4626 #if !defined (MSDOS)
4627 # define STRINGCHAR(ind) \
4628 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4629 # define WHITECHAR(ind) \
4630 (ind < sample_len && whitespace (sample[ind]))
4632 # define STRINGCHAR(ind) \
4633 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4634 # define WHITECHAR(ind) \
4635 (ind < sample_len && whitespace (sample[ind]))
4639 getinterp (sample, sample_len, endp)
4641 int sample_len, *endp;
4647 /* Find the name of the interpreter to exec. */
4648 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
4651 for (start = i; STRINGCHAR(i); i++)
4654 execname = substring (sample, start, i);
4661 #if !defined (HAVE_HASH_BANG_EXEC)
4662 /* If the operating system on which we're running does not handle
4663 the #! executable format, then help out. SAMPLE is the text read
4664 from the file, SAMPLE_LEN characters. COMMAND is the name of
4665 the script; it and ARGS, the arguments given by the user, will
4666 become arguments to the specified interpreter. ENV is the environment
4667 to pass to the interpreter.
4669 The word immediately following the #! is the interpreter to execute.
4670 A single argument to the interpreter is allowed. */
4673 execute_shell_script (sample, sample_len, command, args, env)
4679 char *execname, *firstarg;
4680 int i, start, size_increment, larry;
4682 /* Find the name of the interpreter to exec. */
4683 execname = getinterp (sample, sample_len, &i);
4686 /* Now the argument, if any. */
4687 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
4690 /* If there is more text on the line, then it is an argument for the
4695 for (start = i; STRINGCHAR(i); i++)
4697 firstarg = substring ((char *)sample, start, i);
4701 larry = strvec_len (args) + size_increment;
4702 args = strvec_resize (args, larry + 1);
4704 for (i = larry - 1; i; i--)
4705 args[i] = args[i - size_increment];
4716 args[larry] = (char *)NULL;
4718 return (shell_execve (execname, args, env));
4723 #endif /* !HAVE_HASH_BANG_EXEC */
4726 initialize_subshell ()
4729 /* Forget about any aliases that we knew of. We are in a subshell. */
4730 delete_all_aliases ();
4733 #if defined (HISTORY)
4734 /* Forget about the history lines we have read. This is a non-interactive
4736 history_lines_this_session = 0;
4739 #if defined (JOB_CONTROL)
4740 /* Forget about the way job control was working. We are in a subshell. */
4741 without_job_control ();
4742 set_sigchld_handler ();
4744 #endif /* JOB_CONTROL */
4746 /* Reset the values of the shell flags and options. */
4747 reset_shell_flags ();
4748 reset_shell_options ();
4749 reset_shopt_options ();
4751 /* Zero out builtin_env, since this could be a shell script run from a
4752 sourced file with a temporary environment supplied to the `source/.'
4753 builtin. Such variables are not supposed to be exported (empirical
4754 testing with sh and ksh). Just throw it away; don't worry about a
4756 if (vc_isbltnenv (shell_variables))
4757 shell_variables = shell_variables->down;
4759 clear_unwind_protect_list (0);
4760 /* XXX -- are there other things we should be resetting here? */
4761 parse_and_execute_level = 0; /* nothing left to restore it */
4763 /* We're no longer inside a shell function. */
4764 variable_context = return_catch_flag = funcnest = 0;
4766 executing_list = 0; /* XXX */
4768 /* If we're not interactive, close the file descriptor from which we're
4769 reading the current shell script. */
4770 if (interactive_shell == 0)
4771 unset_bash_input (0);
4774 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4775 # define SETOSTYPE(x) __setostype(x)
4777 # define SETOSTYPE(x)
4780 #define READ_SAMPLE_BUF(file, buf, len) \
4783 fd = open(file, O_RDONLY); \
4786 len = read (fd, buf, 80); \
4794 /* Call execve (), handling interpreting shell scripts, and handling
4797 shell_execve (command, args, env)
4805 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
4806 execve (command, args, env);
4807 i = errno; /* error from execve() */
4811 /* If we get to this point, then start checking out the file.
4812 Maybe it is something we can hack ourselves. */
4815 if (file_isdir (command))
4816 internal_error (_("%s: is a directory"), command);
4817 else if (executable_file (command) == 0)
4820 file_error (command);
4822 /* errors not involving the path argument to execve. */
4823 else if (i == E2BIG || i == ENOMEM)
4826 file_error (command);
4830 /* The file has the execute bits set, but the kernel refuses to
4831 run it for some reason. See why. */
4832 #if defined (HAVE_HASH_BANG_EXEC)
4833 READ_SAMPLE_BUF (command, sample, sample_len);
4834 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4839 interp = getinterp (sample, sample_len, (int *)NULL);
4840 ilen = strlen (interp);
4842 if (interp[ilen - 1] == '\r')
4844 interp = xrealloc (interp, ilen + 2);
4845 interp[ilen - 1] = '^';
4847 interp[ilen + 1] = '\0';
4849 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
4855 file_error (command);
4857 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
4860 /* This file is executable.
4861 If it begins with #!, then help out people with losing operating
4862 systems. Otherwise, check to see if it is a binary file by seeing
4863 if the contents of the first line (or up to 80 characters) are in the
4864 ASCII set. If it's a text file, execute the contents as shell commands,
4865 otherwise return 126 (EX_BINARY_FILE). */
4866 READ_SAMPLE_BUF (command, sample, sample_len);
4868 if (sample_len == 0)
4869 return (EXECUTION_SUCCESS);
4871 /* Is this supposed to be an executable script?
4872 If so, the format of the line is "#! interpreter [argument]".
4873 A single argument is allowed. The BSD kernel restricts
4874 the length of the entire line to 32 characters (32 bytes
4875 being the size of the BSD exec header), but we allow 80
4879 #if !defined (HAVE_HASH_BANG_EXEC)
4880 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4881 return (execute_shell_script (sample, sample_len, command, args, env));
4884 if (check_binary_file (sample, sample_len))
4886 internal_error (_("%s: cannot execute binary file"), command);
4887 return (EX_BINARY_FILE);
4891 /* We have committed to attempting to execute the contents of this file
4892 as shell commands. */
4894 initialize_subshell ();
4896 set_sigint_handler ();
4898 /* Insert the name of this shell into the argument list. */
4899 larray = strvec_len (args) + 1;
4900 args = strvec_resize (args, larray + 1);
4902 for (i = larray - 1; i; i--)
4903 args[i] = args[i - 1];
4905 args[0] = shell_name;
4907 args[larray] = (char *)NULL;
4909 if (args[0][0] == '-')
4912 #if defined (RESTRICTED_SHELL)
4914 change_flag ('r', FLAG_OFF);
4919 /* Can't free subshell_argv[0]; that is shell_name. */
4920 for (i = 1; i < subshell_argc; i++)
4921 free (subshell_argv[i]);
4922 free (subshell_argv);
4925 dispose_command (currently_executing_command); /* XXX */
4926 currently_executing_command = (COMMAND *)NULL;
4928 subshell_argc = larray;
4929 subshell_argv = args;
4930 subshell_envp = env;
4932 unbind_args (); /* remove the positional parameters */
4934 longjmp (subshell_top_level, 1);
4939 execute_intern_function (name, function)
4945 if (check_identifier (name, posixly_correct) == 0)
4947 if (posixly_correct && interactive_shell == 0)
4949 last_command_exit_value = EX_BADUSAGE;
4950 jump_to_top_level (ERREXIT);
4952 return (EXECUTION_FAILURE);
4955 var = find_function (name->word);
4956 if (var && (readonly_p (var) || noassign_p (var)))
4958 if (readonly_p (var))
4959 internal_error (_("%s: readonly function"), var->name);
4960 return (EXECUTION_FAILURE);
4963 bind_function (name->word, function);
4964 return (EXECUTION_SUCCESS);
4967 #if defined (INCLUDE_UNUSED)
4968 #if defined (PROCESS_SUBSTITUTION)
4972 register int i, fd_table_size;
4974 fd_table_size = getdtablesize ();
4975 if (fd_table_size > 256) /* clamp to a reasonable value */
4976 fd_table_size = 256;
4978 for (i = 3; i < fd_table_size; i++)
4981 #endif /* PROCESS_SUBSTITUTION */
4985 close_pipes (in, out)
4995 dup_error (oldd, newd)
4998 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
5001 /* Redirect input and output to be from and to the specified pipes.
5002 NO_PIPE and REDIRECT_BOTH are handled correctly. */
5004 do_piping (pipe_in, pipe_out)
5005 int pipe_in, pipe_out;
5007 if (pipe_in != NO_PIPE)
5009 if (dup2 (pipe_in, 0) < 0)
5010 dup_error (pipe_in, 0);
5014 if (pipe_out != NO_PIPE)
5016 if (pipe_out != REDIRECT_BOTH)
5018 if (dup2 (pipe_out, 1) < 0)
5019 dup_error (pipe_out, 1);
5020 if (pipe_out == 0 || pipe_out > 1)
5025 if (dup2 (1, 2) < 0)