1 /* execute_command.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2005 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 it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
27 #include "chartypes.h"
28 #include "bashtypes.h"
29 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
30 # include <sys/file.h>
33 #include "posixstat.h"
36 # include <sys/param.h>
39 #if defined (HAVE_UNISTD_H)
43 #include "posixtime.h"
45 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
46 # include <sys/resource.h>
49 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
50 # include <sys/times.h>
64 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
69 #include "execute_cmd.h"
76 #if defined (COND_COMMAND)
80 #include "builtins/common.h"
81 #include "builtins/builtext.h" /* list of builtins */
83 #include <glob/strmatch.h>
84 #include <tilde/tilde.h>
86 #if defined (BUFFERED_INPUT)
95 # include "bashhist.h"
98 extern int posixly_correct;
99 extern int breaking, continuing, loop_level;
100 extern int expand_aliases;
101 extern int parse_and_execute_level, running_trap;
102 extern int command_string_index, line_number;
103 extern int dot_found_in_search;
104 extern int already_making_children;
105 extern int tempenv_assign_error;
106 extern char *the_printed_command, *shell_name;
107 extern pid_t last_command_subst_pid;
108 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
109 extern char **subshell_argv, **subshell_envp;
110 extern int subshell_argc;
112 extern char *glob_argv_flags;
115 extern int close __P((int));
117 /* Static functions defined and used in this file. */
118 static void close_pipes __P((int, int));
119 static void do_piping __P((int, int));
120 static void bind_lastarg __P((char *));
121 static int shell_control_structure __P((enum command_type));
122 static void cleanup_redirects __P((REDIRECT *));
124 #if defined (JOB_CONTROL)
125 static int restore_signal_mask __P((sigset_t *));
128 static void async_redirect_stdin __P((void));
130 static int builtin_status __P((int));
132 static int execute_for_command __P((FOR_COM *));
133 #if defined (SELECT_COMMAND)
134 static int print_index_and_element __P((int, int, WORD_LIST *));
135 static void indent __P((int, int));
136 static void print_select_list __P((WORD_LIST *, int, int, int));
137 static char *select_query __P((WORD_LIST *, int, char *, int));
138 static int execute_select_command __P((SELECT_COM *));
140 #if defined (DPAREN_ARITHMETIC)
141 static int execute_arith_command __P((ARITH_COM *));
143 #if defined (COND_COMMAND)
144 static int execute_cond_node __P((COND_COM *));
145 static int execute_cond_command __P((COND_COM *));
147 #if defined (COMMAND_TIMING)
148 static int mkfmt __P((char *, int, int, time_t, int));
149 static void print_formatted_time __P((FILE *, char *,
150 time_t, int, time_t, int,
152 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
154 #if defined (ARITH_FOR_COMMAND)
155 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
156 static int execute_arith_for_command __P((ARITH_FOR_COM *));
158 static int execute_case_command __P((CASE_COM *));
159 static int execute_while_command __P((WHILE_COM *));
160 static int execute_until_command __P((WHILE_COM *));
161 static int execute_while_or_until __P((WHILE_COM *, int));
162 static int execute_if_command __P((IF_COM *));
163 static int execute_null_command __P((REDIRECT *, int, int, int));
164 static void fix_assignment_words __P((WORD_LIST *));
165 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
166 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
167 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
168 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
170 REDIRECT *, struct fd_bitmap *, int));
171 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
177 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
178 int, int, int, struct fd_bitmap *, int));
180 static char *getinterp __P((char *, int, int *));
181 static void initialize_subshell __P((void));
182 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
184 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
186 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
188 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
190 /* The line number that the currently executing function starts on. */
191 static int function_line_number;
193 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
194 so that reader_loop can set it to zero before executing a command. */
197 /* The name of the command that is currently being executed.
198 `test' needs this, for example. */
199 char *this_command_name;
201 /* The printed representation of the currently-executing command (same as
202 the_printed_command), except when a trap is being executed. Useful for
203 a debugger to know where exactly the program is currently executing. */
204 char *the_printed_command_except_trap;
206 static COMMAND *currently_executing_command;
208 struct stat SB; /* used for debugging */
210 static int special_builtin_failed;
212 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
213 number containing the function name. Used by executing_line_number to
214 report the correct line number. Kind of a hack. */
215 static int showing_function_line;
217 /* For catching RETURN in a function. */
218 int return_catch_flag;
219 int return_catch_value;
220 procenv_t return_catch;
222 /* The value returned by the last synchronous command. */
223 int last_command_exit_value;
225 /* Whether or not the last command (corresponding to last_command_exit_value)
226 was terminated by a signal, and, if so, which one. */
227 int last_command_exit_signal;
229 /* The list of redirections to perform which will undo the redirections
230 that I made in the shell. */
231 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
233 /* The list of redirections to perform which will undo the internal
234 redirections performed by the `exec' builtin. These are redirections
235 that must be undone even when exec discards redirection_undo_list. */
236 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
238 /* Non-zero if we have just forked and are currently running in a subshell
240 int subshell_environment;
242 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
243 int subshell_level = 0;
245 /* Currently-executing shell function. */
246 SHELL_VAR *this_shell_function;
248 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
249 int match_ignore_case = 0;
251 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
253 #define FD_BITMAP_DEFAULT_SIZE 32
255 /* Functions to allocate and deallocate the structures used to pass
256 information from the shell to its children about file descriptors
262 struct fd_bitmap *ret;
264 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
270 ret->bitmap = (char *)xmalloc (size);
271 memset (ret->bitmap, '\0', size);
274 ret->bitmap = (char *)NULL;
279 dispose_fd_bitmap (fdbp)
280 struct fd_bitmap *fdbp;
287 close_fd_bitmap (fdbp)
288 struct fd_bitmap *fdbp;
294 for (i = 0; i < fdbp->size; i++)
303 /* Return the line number of the currently executing command. */
305 executing_line_number ()
307 if (executing && showing_function_line == 0 &&
308 (variable_context == 0 || interactive_shell == 0) &&
309 currently_executing_command)
311 #if defined (COND_COMMAND)
312 if (currently_executing_command->type == cm_cond)
313 return currently_executing_command->value.Cond->line;
315 #if defined (DPAREN_ARITHMETIC)
316 else if (currently_executing_command->type == cm_arith)
317 return currently_executing_command->value.Arith->line;
319 #if defined (ARITH_FOR_COMMAND)
320 else if (currently_executing_command->type == cm_arith_for)
321 return currently_executing_command->value.ArithFor->line;
330 /* Execute the command passed in COMMAND. COMMAND is exactly what
331 read_command () places into GLOBAL_COMMAND. See "command.h" for the
332 details of the command structure.
334 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
335 return values. Executing a command with nothing in it returns
336 EXECUTION_SUCCESS. */
338 execute_command (command)
341 struct fd_bitmap *bitmap;
344 current_fds_to_close = (struct fd_bitmap *)NULL;
345 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
346 begin_unwind_frame ("execute-command");
347 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
349 /* Just do the command, but not asynchronously. */
350 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
352 dispose_fd_bitmap (bitmap);
353 discard_unwind_frame ("execute-command");
355 #if defined (PROCESS_SUBSTITUTION)
356 /* don't unlink fifos if we're in a shell function; wait until the function
358 if (variable_context == 0)
360 #endif /* PROCESS_SUBSTITUTION */
365 /* Return 1 if TYPE is a shell control structure type. */
367 shell_control_structure (type)
368 enum command_type type;
372 #if defined (ARITH_FOR_COMMAND)
375 #if defined (SELECT_COMMAND)
378 #if defined (DPAREN_ARITHMETIC)
381 #if defined (COND_COMMAND)
390 case cm_function_def:
398 /* A function to use to unwind_protect the redirection undo list
401 cleanup_redirects (list)
404 do_redirections (list, RX_ACTIVE);
405 dispose_redirects (list);
409 /* Function to unwind_protect the redirections for functions and builtins. */
411 cleanup_func_redirects (list)
414 do_redirections (list, RX_ACTIVE);
419 dispose_exec_redirects ()
421 if (exec_redirection_undo_list)
423 dispose_redirects (exec_redirection_undo_list);
424 exec_redirection_undo_list = (REDIRECT *)NULL;
428 #if defined (JOB_CONTROL)
429 /* A function to restore the signal mask to its proper value when the shell
430 is interrupted or errors occur while creating a pipeline. */
432 restore_signal_mask (set)
435 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
437 #endif /* JOB_CONTROL */
440 /* A debugging function that can be called from gdb, for instance. */
445 int f, fd_table_size;
447 fd_table_size = getdtablesize ();
449 fprintf (stderr, "pid %ld open files:", (long)getpid ());
450 for (i = 3; i < fd_table_size; i++)
452 if ((f = fcntl (i, F_GETFD, 0)) != -1)
453 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
455 fprintf (stderr, "\n");
460 async_redirect_stdin ()
464 fd = open ("/dev/null", O_RDONLY);
471 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
474 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
476 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
477 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
478 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
479 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
480 from and where it goes. They can have the value of NO_PIPE, which means
482 FDS_TO_CLOSE is a list of file descriptors to close once the child has
483 been forked. This list often contains the unusable sides of pipes, etc.
485 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
486 return values. Executing a command with nothing in it returns
487 EXECUTION_SUCCESS. */
489 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
493 int pipe_in, pipe_out;
494 struct fd_bitmap *fds_to_close;
496 int exec_result, invert, ignore_return, was_error_trap;
497 REDIRECT *my_undo_list, *exec_undo_list;
498 volatile int last_pid;
499 volatile int save_line_number;
501 if (command == 0 || breaking || continuing || read_but_dont_execute)
502 return (EXECUTION_SUCCESS);
504 run_pending_traps ();
507 if (running_trap == 0)
509 currently_executing_command = command;
511 invert = (command->flags & CMD_INVERT_RETURN) != 0;
513 /* If we're inverting the return value and `set -e' has been executed,
514 we don't want a failing command to inadvertently cause the shell
516 if (exit_immediately_on_error && invert) /* XXX */
517 command->flags |= CMD_IGNORE_RETURN; /* XXX */
519 exec_result = EXECUTION_SUCCESS;
521 /* If a command was being explicitly run in a subshell, or if it is
522 a shell control-structure, and it has a pipe, then we do the command
524 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
525 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
527 if (command->type == cm_subshell ||
528 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
529 (shell_control_structure (command->type) &&
530 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
534 /* Fork a subshell, turn off the subshell bit, turn off job
535 control and call execute_command () on the command again. */
536 paren_pid = make_child (savestring (make_command_string (command)),
539 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
543 close_pipes (pipe_in, pipe_out);
545 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
548 /* If we are part of a pipeline, and not the end of the pipeline,
549 then we should simply return and let the last command in the
550 pipe be waited for. If we are not in a pipeline, or are the
551 last command in the pipeline, then we wait for the subshell
552 and return its exit status as usual. */
553 if (pipe_out != NO_PIPE)
554 return (EXECUTION_SUCCESS);
556 stop_pipeline (asynchronous, (COMMAND *)NULL);
558 if (asynchronous == 0)
560 last_command_exit_value = wait_for (paren_pid);
562 /* If we have to, invert the return value. */
564 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
566 : EXECUTION_SUCCESS);
568 exec_result = last_command_exit_value;
570 return (last_command_exit_value = exec_result);
574 DESCRIBE_PID (paren_pid);
576 run_pending_traps ();
578 return (EXECUTION_SUCCESS);
583 #if defined (COMMAND_TIMING)
584 if (command->flags & CMD_TIME_PIPELINE)
588 command->flags |= CMD_FORCE_SUBSHELL;
589 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
593 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
595 if (running_trap == 0)
597 currently_executing_command = (COMMAND *)NULL;
599 return (exec_result);
601 #endif /* COMMAND_TIMING */
603 if (shell_control_structure (command->type) && command->redirects)
604 stdin_redir = stdin_redirects (command->redirects);
606 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
608 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
610 cleanup_redirects (redirection_undo_list);
611 redirection_undo_list = (REDIRECT *)NULL;
612 dispose_exec_redirects ();
613 return (EXECUTION_FAILURE);
616 if (redirection_undo_list)
618 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
619 dispose_redirects (redirection_undo_list);
620 redirection_undo_list = (REDIRECT *)NULL;
623 my_undo_list = (REDIRECT *)NULL;
625 if (exec_redirection_undo_list)
627 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
628 dispose_redirects (exec_redirection_undo_list);
629 exec_redirection_undo_list = (REDIRECT *)NULL;
632 exec_undo_list = (REDIRECT *)NULL;
634 if (my_undo_list || exec_undo_list)
635 begin_unwind_frame ("loop_redirections");
638 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
641 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
643 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
647 switch (command->type)
651 save_line_number = line_number;
652 /* We can't rely on variables retaining their values across a
653 call to execute_simple_command if a longjmp occurs as the
654 result of a `return' builtin. This is true for sure with gcc. */
655 #if defined (RECYCLES_PIDS)
656 last_made_pid = NO_PID;
658 last_pid = last_made_pid;
659 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
661 if (ignore_return && command->value.Simple)
662 command->value.Simple->flags |= CMD_IGNORE_RETURN;
663 if (command->flags & CMD_STDIN_REDIR)
664 command->value.Simple->flags |= CMD_STDIN_REDIR;
666 line_number = command->value.Simple->line;
668 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
669 asynchronous, fds_to_close);
670 line_number = save_line_number;
672 /* The temporary environment should be used for only the simple
673 command immediately following its definition. */
674 dispose_used_env_vars ();
676 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
677 /* Reclaim memory allocated with alloca () on machines which
678 may be using the alloca emulation code. */
680 #endif /* (ultrix && mips) || C_ALLOCA */
682 /* If we forked to do the command, then we must wait_for ()
685 /* XXX - this is something to watch out for if there are problems
686 when the shell is compiled without job control. */
687 if (already_making_children && pipe_out == NO_PIPE &&
688 last_made_pid != last_pid)
690 stop_pipeline (asynchronous, (COMMAND *)NULL);
694 DESCRIBE_PID (last_made_pid);
697 #if !defined (JOB_CONTROL)
698 /* Do not wait for asynchronous processes started from
700 if (last_made_pid != last_asynchronous_pid)
702 /* When executing a shell function that executes other
703 commands, this causes the last simple command in
704 the function to be waited for twice. This also causes
705 subshells forked to execute builtin commands (e.g., in
706 pipelines) to be waited for twice. */
707 exec_result = wait_for (last_made_pid);
711 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
713 last_command_exit_value = exec_result;
717 if (ignore_return == 0 && invert == 0 &&
718 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
719 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
721 last_command_exit_value = exec_result;
722 run_pending_traps ();
723 jump_to_top_level (ERREXIT);
730 command->value.For->flags |= CMD_IGNORE_RETURN;
731 exec_result = execute_for_command (command->value.For);
734 #if defined (ARITH_FOR_COMMAND)
737 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
738 exec_result = execute_arith_for_command (command->value.ArithFor);
742 #if defined (SELECT_COMMAND)
745 command->value.Select->flags |= CMD_IGNORE_RETURN;
746 exec_result = execute_select_command (command->value.Select);
752 command->value.Case->flags |= CMD_IGNORE_RETURN;
753 exec_result = execute_case_command (command->value.Case);
758 command->value.While->flags |= CMD_IGNORE_RETURN;
759 exec_result = execute_while_command (command->value.While);
764 command->value.While->flags |= CMD_IGNORE_RETURN;
765 exec_result = execute_until_command (command->value.While);
770 command->value.If->flags |= CMD_IGNORE_RETURN;
771 exec_result = execute_if_command (command->value.If);
776 /* This code can be executed from either of two paths: an explicit
777 '{}' command, or via a function call. If we are executed via a
778 function call, we have already taken care of the function being
779 executed in the background (down there in execute_simple_command ()),
780 and this command should *not* be marked as asynchronous. If we
781 are executing a regular '{}' group command, and asynchronous == 1,
782 we must want to execute the whole command in the background, so we
783 need a subshell, and we want the stuff executed in that subshell
784 (this group command) to be executed in the foreground of that
785 subshell (i.e. there will not be *another* subshell forked).
787 What we do is to force a subshell if asynchronous, and then call
788 execute_command_internal again with asynchronous still set to 1,
789 but with the original group command, so the printed command will
792 The code above that handles forking off subshells will note that
793 both subshell and async are on, and turn off async in the child
794 after forking the subshell (but leave async set in the parent, so
795 the normal call to describe_pid is made). This turning off
796 async is *crucial*; if it is not done, this will fall into an
797 infinite loop of executions through this spot in subshell after
798 subshell until the process limit is exhausted. */
802 command->flags |= CMD_FORCE_SUBSHELL;
804 execute_command_internal (command, 1, pipe_in, pipe_out,
809 if (ignore_return && command->value.Group->command)
810 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
812 execute_command_internal (command->value.Group->command,
813 asynchronous, pipe_in, pipe_out,
819 exec_result = execute_connection (command, asynchronous,
820 pipe_in, pipe_out, fds_to_close);
823 #if defined (DPAREN_ARITHMETIC)
826 command->value.Arith->flags |= CMD_IGNORE_RETURN;
827 exec_result = execute_arith_command (command->value.Arith);
831 #if defined (COND_COMMAND)
834 command->value.Cond->flags |= CMD_IGNORE_RETURN;
835 save_line_number = line_number;
836 exec_result = execute_cond_command (command->value.Cond);
837 line_number = save_line_number;
841 case cm_function_def:
842 exec_result = execute_intern_function (command->value.Function_def->name,
843 command->value.Function_def->command);
847 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
852 do_redirections (my_undo_list, RX_ACTIVE);
853 dispose_redirects (my_undo_list);
857 dispose_redirects (exec_undo_list);
859 if (my_undo_list || exec_undo_list)
860 discard_unwind_frame ("loop_redirections");
862 /* Invert the return value if we have to */
864 exec_result = (exec_result == EXECUTION_SUCCESS)
868 last_command_exit_value = exec_result;
869 run_pending_traps ();
871 if (running_trap == 0)
873 currently_executing_command = (COMMAND *)NULL;
874 return (last_command_exit_value);
877 #if defined (COMMAND_TIMING)
879 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
880 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
881 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
882 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
885 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
886 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
888 static int precs[] = { 0, 100, 10, 1 };
890 /* Expand one `%'-prefixed escape sequence from a time format string. */
892 mkfmt (buf, prec, lng, sec, sec_fraction)
899 char abuf[INT_STRLEN_BOUND(time_t) + 1];
903 abuf[sizeof(abuf) - 1] = '\0';
905 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
910 aind = sizeof(abuf) - 2;
912 abuf[aind--] = (min % 10) + '0';
916 buf[ind++] = abuf[aind++];
920 /* Now add the seconds. */
921 aind = sizeof (abuf) - 2;
923 abuf[aind--] = (sec % 10) + '0';
927 buf[ind++] = abuf[aind++];
929 /* We want to add a decimal point and PREC places after it if PREC is
930 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
935 for (aind = 1; aind <= prec; aind++)
937 buf[ind++] = (sec_fraction / precs[aind]) + '0';
938 sec_fraction %= precs[aind];
949 /* Interpret the format string FORMAT, interpolating the following escape
953 where the optional `prec' is a precision, meaning the number of
954 characters after the decimal point, the optional `l' means to format
955 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
956 and the last character is one of
958 R number of seconds of `real' time
959 U number of seconds of `user' time
960 S number of seconds of `system' time
962 An occurrence of `%%' in the format string is translated to a `%'. The
963 result is printed to FP, a pointer to a FILE. The other variables are
964 the seconds and thousandths of a second of real, user, and system time,
967 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
978 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
983 len = strlen (format);
984 ssize = (len + 64) - (len % 64);
985 str = (char *)xmalloc (ssize);
988 for (s = format; *s; s++)
990 if (*s != '%' || s[1] == '\0')
992 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
995 else if (s[1] == '%')
998 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1001 else if (s[1] == 'P')
1007 sum_frac = (cpu % 100) * 10;
1008 len = mkfmt (ts, 2, 0, sum, sum_frac);
1009 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1010 strcpy (str + sindex, ts);
1015 prec = 3; /* default is three places past the decimal point. */
1016 lng = 0; /* default is to not use minutes or append `s' */
1018 if (DIGIT (*s)) /* `precision' */
1021 if (prec > 3) prec = 3;
1023 if (*s == 'l') /* `length extender' */
1028 if (*s == 'R' || *s == 'E')
1029 len = mkfmt (ts, prec, lng, rs, rsf);
1031 len = mkfmt (ts, prec, lng, us, usf);
1033 len = mkfmt (ts, prec, lng, ss, ssf);
1036 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1040 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1041 strcpy (str + sindex, ts);
1047 fprintf (fp, "%s\n", str);
1054 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1056 int asynchronous, pipe_in, pipe_out;
1057 struct fd_bitmap *fds_to_close;
1059 int rv, posix_time, old_flags;
1065 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1066 struct timeval real, user, sys;
1067 struct timeval before, after;
1068 # if defined (HAVE_STRUCT_TIMEZONE)
1069 struct timezone dtz; /* posix doesn't define this */
1071 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1073 # if defined (HAVE_TIMES)
1074 clock_t tbefore, tafter, real, user, sys;
1075 struct tms before, after;
1079 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1080 # if defined (HAVE_STRUCT_TIMEZONE)
1081 gettimeofday (&before, &dtz);
1083 gettimeofday (&before, (void *)NULL);
1084 # endif /* !HAVE_STRUCT_TIMEZONE */
1085 getrusage (RUSAGE_SELF, &selfb);
1086 getrusage (RUSAGE_CHILDREN, &kidsb);
1088 # if defined (HAVE_TIMES)
1089 tbefore = times (&before);
1093 posix_time = (command->flags & CMD_TIME_POSIX);
1095 old_flags = command->flags;
1096 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1097 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1098 command->flags = old_flags;
1101 rsf = usf = ssf = cpu = 0;
1103 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1104 # if defined (HAVE_STRUCT_TIMEZONE)
1105 gettimeofday (&after, &dtz);
1107 gettimeofday (&after, (void *)NULL);
1108 # endif /* !HAVE_STRUCT_TIMEZONE */
1109 getrusage (RUSAGE_SELF, &selfa);
1110 getrusage (RUSAGE_CHILDREN, &kidsa);
1112 difftimeval (&real, &before, &after);
1113 timeval_to_secs (&real, &rs, &rsf);
1115 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1116 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1117 timeval_to_secs (&user, &us, &usf);
1119 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1120 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1121 timeval_to_secs (&sys, &ss, &ssf);
1123 cpu = timeval_to_cpu (&real, &user, &sys);
1125 # if defined (HAVE_TIMES)
1126 tafter = times (&after);
1128 real = tafter - tbefore;
1129 clock_t_to_secs (real, &rs, &rsf);
1131 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1132 clock_t_to_secs (user, &us, &usf);
1134 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1135 clock_t_to_secs (sys, &ss, &ssf);
1137 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1141 rsf = usf = ssf = cpu = 0;
1146 time_format = POSIX_TIMEFORMAT;
1147 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1148 time_format = BASH_TIMEFORMAT;
1150 if (time_format && *time_format)
1151 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1155 #endif /* COMMAND_TIMING */
1157 /* Execute a command that's supposed to be in a subshell. This must be
1158 called after make_child and we must be running in the child process.
1159 The caller will return or exit() immediately with the value this returns. */
1161 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1164 int pipe_in, pipe_out;
1165 struct fd_bitmap *fds_to_close;
1167 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1171 USE_VAR(user_subshell);
1174 USE_VAR(asynchronous);
1177 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1178 pipe_in == NO_PIPE &&
1179 stdin_redirects (command->redirects) == 0);
1181 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1182 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1184 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1186 /* If a command is asynchronous in a subshell (like ( foo ) & or
1187 the special case of an asynchronous GROUP command where the
1188 the subshell bit is turned on down in case cm_group: below),
1189 turn off `asynchronous', so that two subshells aren't spawned.
1191 This seems semantically correct to me. For example,
1192 ( foo ) & seems to say ``do the command `foo' in a subshell
1193 environment, but don't wait for that subshell to finish'',
1194 and "{ foo ; bar ; } &" seems to me to be like functions or
1195 builtins in the background, which executed in a subshell
1196 environment. I just don't see the need to fork two subshells. */
1198 /* Don't fork again, we are already in a subshell. A `doubly
1199 async' shell is not interactive, however. */
1202 #if defined (JOB_CONTROL)
1203 /* If a construct like ( exec xxx yyy ) & is given while job
1204 control is active, we want to prevent exec from putting the
1205 subshell back into the original process group, carefully
1206 undoing all the work we just did in make_child. */
1208 #endif /* JOB_CONTROL */
1209 ois = interactive_shell;
1210 interactive_shell = 0;
1211 /* This test is to prevent alias expansion by interactive shells that
1212 run `(command) &' but to allow scripts that have enabled alias
1213 expansion with `shopt -s expand_alias' to continue to expand
1215 if (ois != interactive_shell)
1220 /* Subshells are neither login nor interactive. */
1221 login_shell = interactive = 0;
1223 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1225 reset_terminating_signals (); /* in sig.c */
1226 /* Cancel traps, in trap.c. */
1227 restore_original_signals ();
1229 setup_async_signals ();
1231 #if defined (JOB_CONTROL)
1232 set_sigchld_handler ();
1233 #endif /* JOB_CONTROL */
1235 set_sigint_handler ();
1237 #if defined (JOB_CONTROL)
1238 /* Delete all traces that there were any jobs running. This is
1239 only for subshells. */
1240 without_job_control ();
1241 #endif /* JOB_CONTROL */
1244 close_fd_bitmap (fds_to_close);
1246 do_piping (pipe_in, pipe_out);
1248 /* If this is a user subshell, set a flag if stdin was redirected.
1249 This is used later to decide whether to redirect fd 0 to
1250 /dev/null for async commands in the subshell. This adds more
1251 sh compatibility, but I'm not sure it's the right thing to do. */
1254 stdin_redir = stdin_redirects (command->redirects);
1255 restore_default_signal (0);
1258 /* If this is an asynchronous command (command &), we want to
1259 redirect the standard input from /dev/null in the absence of
1260 any specific redirection involving stdin. */
1261 if (should_redir_stdin && stdin_redir == 0)
1262 async_redirect_stdin ();
1264 /* Do redirections, then dispose of them before recursive call. */
1265 if (command->redirects)
1267 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1268 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1270 dispose_redirects (command->redirects);
1271 command->redirects = (REDIRECT *)NULL;
1274 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1276 if (command->flags & CMD_TIME_PIPELINE)
1277 tcom->flags |= CMD_TIME_PIPELINE;
1278 if (command->flags & CMD_TIME_POSIX)
1279 tcom->flags |= CMD_TIME_POSIX;
1281 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1282 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1283 tcom->flags |= CMD_IGNORE_RETURN;
1285 /* If this is a simple command, tell execute_disk_command that it
1286 might be able to get away without forking and simply exec.
1287 This means things like ( sleep 10 ) will only cause one fork.
1288 If we're timing the command or inverting its return value, however,
1289 we cannot do this optimization. */
1290 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1291 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1292 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1294 tcom->flags |= CMD_NO_FORK;
1295 if (tcom->type == cm_simple)
1296 tcom->value.Simple->flags |= CMD_NO_FORK;
1299 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1300 tcom->flags &= ~CMD_INVERT_RETURN;
1302 /* If we're inside a function while executing this subshell, we
1303 need to handle a possible `return'. */
1305 if (return_catch_flag)
1306 function_value = setjmp (return_catch);
1309 return_code = return_catch_value;
1311 return_code = execute_command_internal
1312 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1314 /* If we are asked to, invert the return value. */
1316 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1317 : EXECUTION_SUCCESS;
1319 /* If we were explicitly placed in a subshell with (), we need
1320 to do the `shell cleanup' things, such as running traps[0]. */
1321 if (user_subshell && signal_is_trapped (0))
1323 last_command_exit_value = return_code;
1324 return_code = run_exit_trap ();
1328 return (return_code);
1333 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1335 int asynchronous, pipe_in, pipe_out;
1336 struct fd_bitmap *fds_to_close;
1338 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1340 struct fd_bitmap *fd_bitmap;
1342 #if defined (JOB_CONTROL)
1344 BLOCK_CHILD (set, oset);
1345 #endif /* JOB_CONTROL */
1347 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1352 while (cmd && cmd->type == cm_connection &&
1353 cmd->value.Connection && cmd->value.Connection->connector == '|')
1355 /* Make a pipeline between the two commands. */
1356 if (pipe (fildes) < 0)
1358 sys_error ("pipe error");
1359 #if defined (JOB_CONTROL)
1360 terminate_current_pipeline ();
1361 kill_current_pipeline ();
1362 UNBLOCK_CHILD (oset);
1363 #endif /* JOB_CONTROL */
1364 last_command_exit_value = EXECUTION_FAILURE;
1365 /* The unwind-protects installed below will take care
1366 of closing all of the open file descriptors. */
1367 throw_to_top_level ();
1368 return (EXECUTION_FAILURE); /* XXX */
1371 /* Here is a problem: with the new file close-on-exec
1372 code, the read end of the pipe (fildes[0]) stays open
1373 in the first process, so that process will never get a
1374 SIGPIPE. There is no way to signal the first process
1375 that it should close fildes[0] after forking, so it
1376 remains open. No SIGPIPE is ever sent because there
1377 is still a file descriptor open for reading connected
1378 to the pipe. We take care of that here. This passes
1379 around a bitmap of file descriptors that must be
1380 closed after making a child process in execute_simple_command. */
1382 /* We need fd_bitmap to be at least as big as fildes[0].
1383 If fildes[0] is less than fds_to_close->size, then
1384 use fds_to_close->size. */
1385 new_bitmap_size = (fildes[0] < fds_to_close->size)
1386 ? fds_to_close->size
1389 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1391 /* Now copy the old information into the new bitmap. */
1392 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1394 /* And mark the pipe file descriptors to be closed. */
1395 fd_bitmap->bitmap[fildes[0]] = 1;
1397 /* In case there are pipe or out-of-processes errors, we
1398 want all these file descriptors to be closed when
1399 unwind-protects are run, and the storage used for the
1400 bitmaps freed up. */
1401 begin_unwind_frame ("pipe-file-descriptors");
1402 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1403 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1405 add_unwind_protect (close, prev);
1406 dummyfd = fildes[1];
1407 add_unwind_protect (close, dummyfd);
1409 #if defined (JOB_CONTROL)
1410 add_unwind_protect (restore_signal_mask, &oset);
1411 #endif /* JOB_CONTROL */
1413 if (ignore_return && cmd->value.Connection->first)
1414 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1415 execute_command_internal (cmd->value.Connection->first, asynchronous,
1416 prev, fildes[1], fd_bitmap);
1424 dispose_fd_bitmap (fd_bitmap);
1425 discard_unwind_frame ("pipe-file-descriptors");
1427 cmd = cmd->value.Connection->second;
1430 /* Now execute the rightmost command in the pipeline. */
1431 if (ignore_return && cmd)
1432 cmd->flags |= CMD_IGNORE_RETURN;
1433 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1438 #if defined (JOB_CONTROL)
1439 UNBLOCK_CHILD (oset);
1442 return (exec_result);
1446 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1448 int asynchronous, pipe_in, pipe_out;
1449 struct fd_bitmap *fds_to_close;
1452 COMMAND *tc, *second;
1453 int ignore_return, exec_result;
1455 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1457 switch (command->value.Connection->connector)
1459 /* Do the first command asynchronously. */
1461 tc = command->value.Connection->first;
1463 return (EXECUTION_SUCCESS);
1468 tc->flags |= CMD_IGNORE_RETURN;
1469 tc->flags |= CMD_AMPERSAND;
1471 /* If this shell was compiled without job control support,
1472 if we are currently in a subshell via `( xxx )', or if job
1473 control is not active then the standard input for an
1474 asynchronous command is forced to /dev/null. */
1475 #if defined (JOB_CONTROL)
1476 if ((subshell_environment || !job_control) && !stdin_redir)
1479 #endif /* JOB_CONTROL */
1480 tc->flags |= CMD_STDIN_REDIR;
1482 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1484 if (tc->flags & CMD_STDIN_REDIR)
1485 tc->flags &= ~CMD_STDIN_REDIR;
1487 second = command->value.Connection->second;
1491 second->flags |= CMD_IGNORE_RETURN;
1493 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1498 /* Just call execute command on both sides. */
1502 if (command->value.Connection->first)
1503 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1504 if (command->value.Connection->second)
1505 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1508 execute_command (command->value.Connection->first);
1510 exec_result = execute_command_internal (command->value.Connection->second,
1511 asynchronous, pipe_in, pipe_out,
1516 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1523 /* If we have something like `a && b &' or `a || b &', run the
1524 && or || stuff in a subshell. Force a subshell and just call
1525 execute_command_internal again. Leave asynchronous on
1526 so that we get a report from the parent shell about the
1528 command->flags |= CMD_FORCE_SUBSHELL;
1529 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1533 /* Execute the first command. If the result of that is successful
1534 and the connector is AND_AND, or the result is not successful
1535 and the connector is OR_OR, then execute the second command,
1536 otherwise return. */
1538 if (command->value.Connection->first)
1539 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1541 exec_result = execute_command (command->value.Connection->first);
1543 if (((command->value.Connection->connector == AND_AND) &&
1544 (exec_result == EXECUTION_SUCCESS)) ||
1545 ((command->value.Connection->connector == OR_OR) &&
1546 (exec_result != EXECUTION_SUCCESS)))
1548 if (ignore_return && command->value.Connection->second)
1549 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1551 exec_result = execute_command (command->value.Connection->second);
1556 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1557 jump_to_top_level (DISCARD);
1558 exec_result = EXECUTION_FAILURE;
1567 if (!interactive_shell) \
1568 reap_dead_jobs (); \
1572 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1575 execute_for_command (for_command)
1576 FOR_COM *for_command;
1578 register WORD_LIST *releaser, *list;
1581 int retval, save_line_number;
1583 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1586 save_line_number = line_number;
1587 if (check_identifier (for_command->name, 1) == 0)
1589 if (posixly_correct && interactive_shell == 0)
1591 last_command_exit_value = EX_USAGE;
1592 jump_to_top_level (ERREXIT);
1594 return (EXECUTION_FAILURE);
1598 identifier = for_command->name->word;
1600 list = releaser = expand_words_no_vars (for_command->map_list);
1602 begin_unwind_frame ("for");
1603 add_unwind_protect (dispose_words, releaser);
1606 if (lexical_scoping)
1608 old_value = copy_variable (find_variable (identifier));
1610 add_unwind_protect (dispose_variable, old_value);
1614 if (for_command->flags & CMD_IGNORE_RETURN)
1615 for_command->action->flags |= CMD_IGNORE_RETURN;
1617 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1621 line_number = for_command->line;
1623 /* Remember what this command looks like, for debugger. */
1624 command_string_index = 0;
1625 print_for_command_head (for_command);
1627 if (echo_command_at_execute)
1628 xtrace_print_for_command_head (for_command);
1630 /* Save this command unless it's a trap command and we're not running
1632 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
1634 FREE (the_printed_command_except_trap);
1635 the_printed_command_except_trap = savestring (the_printed_command);
1638 retval = run_debug_trap ();
1639 #if defined (DEBUGGER)
1640 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1641 skip the command. */
1642 if (debugging_mode && retval != EXECUTION_SUCCESS)
1646 this_command_name = (char *)NULL;
1647 v = bind_variable (identifier, list->word->word, 0);
1648 if (readonly_p (v) || noassign_p (v))
1650 line_number = save_line_number;
1651 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1653 last_command_exit_value = EXECUTION_FAILURE;
1654 jump_to_top_level (FORCE_EOF);
1658 dispose_words (releaser);
1659 discard_unwind_frame ("for");
1661 return (EXECUTION_FAILURE);
1664 retval = execute_command (for_command->action);
1683 line_number = save_line_number;
1686 if (lexical_scoping)
1689 unbind_variable (identifier);
1692 SHELL_VAR *new_value;
1694 new_value = bind_variable (identifier, value_cell(old_value), 0);
1695 new_value->attributes = old_value->attributes;
1696 dispose_variable (old_value);
1701 dispose_words (releaser);
1702 discard_unwind_frame ("for");
1706 #if defined (ARITH_FOR_COMMAND)
1707 /* Execute an arithmetic for command. The syntax is
1709 for (( init ; step ; test ))
1714 The execution should be exactly equivalent to
1717 while eval \(\( test \)\) ; do
1723 eval_arith_for_expr (l, okp)
1731 new = expand_words_no_vars (l);
1734 if (echo_command_at_execute)
1735 xtrace_print_arith_cmd (new);
1736 this_command_name = "(("; /* )) for expression error messages */
1738 command_string_index = 0;
1739 print_arith_command (new);
1740 if (signal_in_progress (DEBUG_TRAP) == 0)
1742 FREE (the_printed_command_except_trap);
1743 the_printed_command_except_trap = savestring (the_printed_command);
1746 r = run_debug_trap ();
1747 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1748 skip the command. */
1749 #if defined (DEBUGGER)
1750 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
1751 expresult = evalexp (new->word->word, okp);
1759 expresult = evalexp (new->word->word, okp);
1761 dispose_words (new);
1773 execute_arith_for_command (arith_for_command)
1774 ARITH_FOR_COM *arith_for_command;
1777 int expok, body_status, arith_lineno, save_lineno;
1779 body_status = EXECUTION_SUCCESS;
1781 save_lineno = line_number;
1783 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1784 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1786 this_command_name = "(("; /* )) for expression error messages */
1788 /* save the starting line number of the command so we can reset
1789 line_number before executing each expression -- for $LINENO
1790 and the DEBUG trap. */
1791 line_number = arith_lineno = arith_for_command->line;
1792 if (variable_context && interactive_shell)
1793 line_number -= function_line_number;
1795 /* Evaluate the initialization expression. */
1796 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1799 line_number = save_lineno;
1800 return (EXECUTION_FAILURE);
1805 /* Evaluate the test expression. */
1806 line_number = arith_lineno;
1807 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1808 line_number = save_lineno;
1812 body_status = EXECUTION_FAILURE;
1819 /* Execute the body of the arithmetic for command. */
1821 body_status = execute_command (arith_for_command->action);
1824 /* Handle any `break' or `continue' commands executed by the body. */
1838 /* Evaluate the step expression. */
1839 line_number = arith_lineno;
1840 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1841 line_number = save_lineno;
1845 body_status = EXECUTION_FAILURE;
1851 line_number = save_lineno;
1853 return (body_status);
1857 #if defined (SELECT_COMMAND)
1858 static int LINES, COLS, tabsize;
1860 #define RP_SPACE ") "
1861 #define RP_SPACE_LEN 2
1863 /* XXX - does not handle numbers > 1000000 at all. */
1864 #define NUMBER_LEN(s) \
1868 : ((s < 10000) ? 4 \
1869 : ((s < 100000) ? 5 \
1873 print_index_and_element (len, ind, list)
1877 register WORD_LIST *l;
1882 for (i = ind, l = list; l && --i; l = l->next)
1884 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1885 return (STRLEN (l->word->word));
1894 if ((to / tabsize) > (from / tabsize))
1896 putc ('\t', stderr);
1897 from += tabsize - from % tabsize;
1908 print_select_list (list, list_len, max_elem_len, indices_len)
1910 int list_len, max_elem_len, indices_len;
1912 int ind, row, elem_len, pos, cols, rows;
1913 int first_column_indices_len, other_indices_len;
1917 putc ('\n', stderr);
1921 cols = max_elem_len ? COLS / max_elem_len : 1;
1924 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1925 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1933 first_column_indices_len = NUMBER_LEN (rows);
1934 other_indices_len = indices_len;
1936 for (row = 0; row < rows; row++)
1942 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1943 elem_len = print_index_and_element (indices_len, ind + 1, list);
1944 elem_len += indices_len + RP_SPACE_LEN;
1946 if (ind >= list_len)
1948 indent (pos + elem_len, pos + max_elem_len);
1949 pos += max_elem_len;
1951 putc ('\n', stderr);
1955 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1956 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1957 If the number is between 1 and LIST_LEN, return that selection. If EOF
1958 is read, return a null string. If a blank line is entered, or an invalid
1959 number is entered, the loop is executed again. */
1961 select_query (list, list_len, prompt, print_menu)
1967 int max_elem_len, indices_len, len;
1970 char *repl_string, *t;
1972 t = get_string_value ("LINES");
1973 LINES = (t && *t) ? atoi (t) : 24;
1974 t = get_string_value ("COLUMNS");
1975 COLS = (t && *t) ? atoi (t) : 80;
1978 t = get_string_value ("TABSIZE");
1979 tabsize = (t && *t) ? atoi (t) : 8;
1987 for (l = list; l; l = l->next)
1989 len = STRLEN (l->word->word);
1990 if (len > max_elem_len)
1993 indices_len = NUMBER_LEN (list_len);
1994 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1999 print_select_list (list, list_len, max_elem_len, indices_len);
2000 fprintf (stderr, "%s", prompt);
2004 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
2007 return ((char *)NULL);
2009 repl_string = get_string_value ("REPLY");
2010 if (*repl_string == 0)
2015 if (legal_number (repl_string, &reply) == 0)
2017 if (reply < 1 || reply > list_len)
2020 for (l = list; l && --reply; l = l->next)
2022 return (l->word->word);
2026 /* Execute a SELECT command. The syntax is:
2027 SELECT word IN list DO command_list DONE
2028 Only `break' or `return' in command_list will terminate
2031 execute_select_command (select_command)
2032 SELECT_COM *select_command;
2034 WORD_LIST *releaser, *list;
2036 char *identifier, *ps3_prompt, *selection;
2037 int retval, list_len, show_menu, save_line_number;
2039 if (check_identifier (select_command->name, 1) == 0)
2040 return (EXECUTION_FAILURE);
2042 save_line_number = line_number;
2043 line_number = select_command->line;
2045 command_string_index = 0;
2046 print_select_command_head (select_command);
2048 if (echo_command_at_execute)
2049 xtrace_print_select_command_head (select_command);
2051 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2053 FREE (the_printed_command_except_trap);
2054 the_printed_command_except_trap = savestring (the_printed_command);
2057 retval = run_debug_trap ();
2058 #if defined (DEBUGGER)
2059 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2060 skip the command. */
2061 if (debugging_mode && retval != EXECUTION_SUCCESS)
2062 return (EXECUTION_SUCCESS);
2066 identifier = select_command->name->word;
2068 /* command and arithmetic substitution, parameter and variable expansion,
2069 word splitting, pathname expansion, and quote removal. */
2070 list = releaser = expand_words_no_vars (select_command->map_list);
2071 list_len = list_length (list);
2072 if (list == 0 || list_len == 0)
2075 dispose_words (list);
2076 line_number = save_line_number;
2077 return (EXECUTION_SUCCESS);
2080 begin_unwind_frame ("select");
2081 add_unwind_protect (dispose_words, releaser);
2083 if (select_command->flags & CMD_IGNORE_RETURN)
2084 select_command->action->flags |= CMD_IGNORE_RETURN;
2086 retval = EXECUTION_SUCCESS;
2091 line_number = select_command->line;
2092 ps3_prompt = get_string_value ("PS3");
2093 if (ps3_prompt == 0)
2097 selection = select_query (list, list_len, ps3_prompt, show_menu);
2101 /* select_query returns EXECUTION_FAILURE if the read builtin
2102 fails, so we want to return failure in this case. */
2103 retval = EXECUTION_FAILURE;
2107 v = bind_variable (identifier, selection, 0);
2108 if (readonly_p (v) || noassign_p (v))
2110 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2112 last_command_exit_value = EXECUTION_FAILURE;
2113 jump_to_top_level (FORCE_EOF);
2117 dispose_words (releaser);
2118 discard_unwind_frame ("select");
2120 line_number = save_line_number;
2121 return (EXECUTION_FAILURE);
2125 retval = execute_command (select_command->action);
2143 #if defined (KSH_COMPATIBLE_SELECT)
2145 selection = get_string_value ("REPLY");
2146 if (selection && *selection == '\0')
2152 line_number = save_line_number;
2154 dispose_words (releaser);
2155 discard_unwind_frame ("select");
2158 #endif /* SELECT_COMMAND */
2160 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2161 The pattern_list is a linked list of pattern clauses; each clause contains
2162 some patterns to compare word_desc against, and an associated command to
2165 execute_case_command (case_command)
2166 CASE_COM *case_command;
2168 register WORD_LIST *list;
2169 WORD_LIST *wlist, *es;
2170 PATTERN_LIST *clauses;
2171 char *word, *pattern;
2172 int retval, match, ignore_return, save_line_number;
2174 save_line_number = line_number;
2175 line_number = case_command->line;
2177 command_string_index = 0;
2178 print_case_command_head (case_command);
2180 if (echo_command_at_execute)
2181 xtrace_print_case_command_head (case_command);
2183 if (signal_in_progress (DEBUG_TRAP == 0) && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2185 FREE (the_printed_command_except_trap);
2186 the_printed_command_except_trap = savestring (the_printed_command);
2189 retval = run_debug_trap();
2190 #if defined (DEBUGGER)
2191 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2192 skip the command. */
2193 if (debugging_mode && retval != EXECUTION_SUCCESS)
2195 line_number = save_line_number;
2196 return (EXECUTION_SUCCESS);
2200 wlist = expand_word_unsplit (case_command->word, 0);
2201 word = wlist ? string_list (wlist) : savestring ("");
2202 dispose_words (wlist);
2204 retval = EXECUTION_SUCCESS;
2205 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2207 begin_unwind_frame ("case");
2208 add_unwind_protect ((Function *)xfree, word);
2210 #define EXIT_CASE() goto exit_case_command
2212 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2215 for (list = clauses->patterns; list; list = list->next)
2217 es = expand_word_leave_quoted (list->word, 0);
2219 if (es && es->word && es->word->word && *(es->word->word))
2220 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2223 pattern = (char *)xmalloc (1);
2227 /* Since the pattern does not undergo quote removal (as per
2228 Posix.2, section 3.9.4.3), the strmatch () call must be able
2229 to recognize backslashes as escape characters. */
2230 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
2237 if (clauses->action && ignore_return)
2238 clauses->action->flags |= CMD_IGNORE_RETURN;
2239 retval = execute_command (clauses->action);
2249 discard_unwind_frame ("case");
2250 line_number = save_line_number;
2257 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2258 Repeatedly execute action while executing test produces
2259 EXECUTION_SUCCESS. */
2261 execute_while_command (while_command)
2262 WHILE_COM *while_command;
2264 return (execute_while_or_until (while_command, CMD_WHILE));
2267 /* UNTIL is just like WHILE except that the test result is negated. */
2269 execute_until_command (while_command)
2270 WHILE_COM *while_command;
2272 return (execute_while_or_until (while_command, CMD_UNTIL));
2275 /* The body for both while and until. The only difference between the
2276 two is that the test value is treated differently. TYPE is
2277 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2278 be EXECUTION_SUCCESS if no commands in the body are executed, and
2279 the status of the last command executed in the body otherwise. */
2281 execute_while_or_until (while_command, type)
2282 WHILE_COM *while_command;
2285 int return_value, body_status;
2287 body_status = EXECUTION_SUCCESS;
2290 while_command->test->flags |= CMD_IGNORE_RETURN;
2291 if (while_command->flags & CMD_IGNORE_RETURN)
2292 while_command->action->flags |= CMD_IGNORE_RETURN;
2296 return_value = execute_command (while_command->test);
2299 /* Need to handle `break' in the test when we would break out of the
2300 loop. The job control code will set `breaking' to loop_level
2301 when a job in a loop is stopped with SIGTSTP. If the stopped job
2302 is in the loop test, `breaking' will not be reset unless we do
2303 this, and the shell will cease to execute commands. */
2304 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2310 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2318 body_status = execute_command (while_command->action);
2336 return (body_status);
2339 /* IF test THEN command [ELSE command].
2340 IF also allows ELIF in the place of ELSE IF, but
2341 the parser makes *that* stupidity transparent. */
2343 execute_if_command (if_command)
2346 int return_value, save_line_number;
2348 save_line_number = line_number;
2349 if_command->test->flags |= CMD_IGNORE_RETURN;
2350 return_value = execute_command (if_command->test);
2351 line_number = save_line_number;
2353 if (return_value == EXECUTION_SUCCESS)
2357 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2358 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2360 return (execute_command (if_command->true_case));
2366 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2367 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2369 return (execute_command (if_command->false_case));
2373 #if defined (DPAREN_ARITHMETIC)
2375 execute_arith_command (arith_command)
2376 ARITH_COM *arith_command;
2378 int expok, save_line_number, retval;
2384 save_line_number = line_number;
2385 this_command_name = "(("; /* )) */
2386 line_number = arith_command->line;
2387 /* If we're in a function, update the line number information. */
2388 if (variable_context && interactive_shell)
2389 line_number -= function_line_number;
2391 command_string_index = 0;
2392 print_arith_command (arith_command->exp);
2394 if (signal_in_progress (DEBUG_TRAP) == 0)
2396 FREE (the_printed_command_except_trap);
2397 the_printed_command_except_trap = savestring (the_printed_command);
2400 /* Run the debug trap before each arithmetic command, but do it after we
2401 update the line number information and before we expand the various
2402 words in the expression. */
2403 retval = run_debug_trap ();
2404 #if defined (DEBUGGER)
2405 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2406 skip the command. */
2407 if (debugging_mode && retval != EXECUTION_SUCCESS)
2409 line_number = save_line_number;
2410 return (EXECUTION_SUCCESS);
2414 new = expand_words_no_vars (arith_command->exp);
2416 /* If we're tracing, make a new word list with `((' at the front and `))'
2417 at the back and print it. */
2418 if (echo_command_at_execute)
2419 xtrace_print_arith_cmd (new);
2423 expresult = evalexp (new->word->word, &expok);
2424 line_number = save_line_number;
2425 dispose_words (new);
2434 return (EXECUTION_FAILURE);
2436 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2438 #endif /* DPAREN_ARITHMETIC */
2440 #if defined (COND_COMMAND)
2442 static char *nullstr = "";
2445 execute_cond_node (cond)
2448 int result, invert, patmatch, rmatch, mflags;
2451 invert = (cond->flags & CMD_INVERT_RETURN);
2453 if (cond->type == COND_EXPR)
2454 result = execute_cond_node (cond->left);
2455 else if (cond->type == COND_OR)
2457 result = execute_cond_node (cond->left);
2458 if (result != EXECUTION_SUCCESS)
2459 result = execute_cond_node (cond->right);
2461 else if (cond->type == COND_AND)
2463 result = execute_cond_node (cond->left);
2464 if (result == EXECUTION_SUCCESS)
2465 result = execute_cond_node (cond->right);
2467 else if (cond->type == COND_UNARY)
2469 arg1 = cond_expand_word (cond->left->op, 0);
2472 if (echo_command_at_execute)
2473 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2474 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2475 if (arg1 != nullstr)
2478 else if (cond->type == COND_BINARY)
2480 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2481 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2482 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2483 #if defined (COND_REGEXP)
2484 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
2485 cond->op->word[2] == '\0');
2488 arg1 = cond_expand_word (cond->left->op, 0);
2491 arg2 = cond_expand_word (cond->right->op, patmatch);
2495 if (echo_command_at_execute)
2496 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2498 #if defined (COND_REGEXP)
2501 mflags = SHMAT_PWARN;
2502 #if defined (ARRAY_VARS)
2503 mflags |= SHMAT_SUBEXP;
2506 result = sh_regmatch (arg1, arg2, mflags);
2509 #endif /* COND_REGEXP */
2514 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2516 : EXECUTION_FAILURE;
2519 if (arg1 != nullstr)
2521 if (arg2 != nullstr)
2526 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2527 jump_to_top_level (DISCARD);
2528 result = EXECUTION_FAILURE;
2532 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2538 execute_cond_command (cond_command)
2539 COND_COM *cond_command;
2541 int retval, save_line_number;
2543 retval = EXECUTION_SUCCESS;
2544 save_line_number = line_number;
2546 this_command_name = "[[";
2547 line_number = cond_command->line;
2548 /* If we're in a function, update the line number information. */
2549 if (variable_context && interactive_shell)
2550 line_number -= function_line_number;
2552 command_string_index = 0;
2553 print_cond_command (cond_command);
2555 if (signal_in_progress (DEBUG_TRAP) == 0)
2557 FREE (the_printed_command_except_trap);
2558 the_printed_command_except_trap = savestring (the_printed_command);
2561 /* Run the debug trap before each conditional command, but do it after we
2562 update the line number information. */
2563 retval = run_debug_trap ();
2564 #if defined (DEBUGGER)
2565 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2566 skip the command. */
2567 if (debugging_mode && retval != EXECUTION_SUCCESS)
2569 line_number = save_line_number;
2570 return (EXECUTION_SUCCESS);
2575 debug_print_cond_command (cond_command);
2578 last_command_exit_value = retval = execute_cond_node (cond_command);
2579 line_number = save_line_number;
2582 #endif /* COND_COMMAND */
2592 var = bind_variable ("_", arg, 0);
2593 VUNSETATTR (var, att_exported);
2596 /* Execute a null command. Fork a subshell if the command uses pipes or is
2597 to be run asynchronously. This handles all the side effects that are
2598 supposed to take place. */
2600 execute_null_command (redirects, pipe_in, pipe_out, async)
2601 REDIRECT *redirects;
2602 int pipe_in, pipe_out, async;
2606 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2608 /* We have a null command, but we really want a subshell to take
2609 care of it. Just fork, do piping and redirections, and exit. */
2610 if (make_child ((char *)NULL, async) == 0)
2612 /* Cancel traps, in trap.c. */
2613 restore_original_signals (); /* XXX */
2615 do_piping (pipe_in, pipe_out);
2617 subshell_environment = SUBSHELL_ASYNC;
2619 if (do_redirections (redirects, RX_ACTIVE) == 0)
2620 exit (EXECUTION_SUCCESS);
2622 exit (EXECUTION_FAILURE);
2626 close_pipes (pipe_in, pipe_out);
2627 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2628 unlink_fifo_list ();
2630 return (EXECUTION_SUCCESS);
2635 /* Even if there aren't any command names, pretend to do the
2636 redirections that are specified. The user expects the side
2637 effects to take place. If the redirections fail, then return
2638 failure. Otherwise, if a command substitution took place while
2639 expanding the command or a redirection, return the value of that
2640 substitution. Otherwise, return EXECUTION_SUCCESS. */
2642 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
2643 cleanup_redirects (redirection_undo_list);
2644 redirection_undo_list = (REDIRECT *)NULL;
2647 return (EXECUTION_FAILURE);
2648 else if (last_command_subst_pid != NO_PID)
2649 return (last_command_exit_value);
2651 return (EXECUTION_SUCCESS);
2655 /* This is a hack to suppress word splitting for assignment statements
2656 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2658 fix_assignment_words (words)
2669 for (w = words; w; w = w->next)
2670 if (w->word->flags & W_ASSIGNMENT)
2674 b = builtin_address_internal (words->word->word, 0);
2675 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2677 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
2678 words->word->flags |= W_ASSNBLTIN;
2680 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
2684 /* The meaty part of all the executions. We have to start hacking the
2685 real execution of commands here. Fork a process, set things up,
2686 execute the command. */
2688 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2689 SIMPLE_COM *simple_command;
2690 int pipe_in, pipe_out, async;
2691 struct fd_bitmap *fds_to_close;
2693 WORD_LIST *words, *lastword;
2694 char *command_line, *lastarg, *temp;
2695 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2696 pid_t old_last_async_pid;
2697 sh_builtin_func_t *builtin;
2700 result = EXECUTION_SUCCESS;
2701 special_builtin_failed = builtin_is_special = 0;
2702 command_line = (char *)0;
2704 /* If we're in a function, update the line number information. */
2705 if (variable_context && interactive_shell)
2706 line_number -= function_line_number;
2708 /* Remember what this command line looks like at invocation. */
2709 command_string_index = 0;
2710 print_simple_command (simple_command);
2712 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2714 FREE (the_printed_command_except_trap);
2715 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
2718 /* Run the debug trap before each simple command, but do it after we
2719 update the line number information. */
2720 result = run_debug_trap ();
2721 #if defined (DEBUGGER)
2722 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2723 skip the command. */
2724 if (debugging_mode && result != EXECUTION_SUCCESS)
2725 return (EXECUTION_SUCCESS);
2729 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2731 last_command_subst_pid = NO_PID;
2732 old_last_async_pid = last_asynchronous_pid;
2734 already_forked = dofork = 0;
2736 /* If we're in a pipeline or run in the background, set DOFORK so we
2737 make the child early, before word expansion. This keeps assignment
2738 statements from affecting the parent shell's environment when they
2740 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2742 /* Something like `%2 &' should restart job 2 in the background, not cause
2743 the shell to fork here. */
2744 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2745 simple_command->words && simple_command->words->word &&
2746 simple_command->words->word->word &&
2747 (simple_command->words->word->word[0] == '%'))
2752 /* Do this now, because execute_disk_command will do it anyway in the
2753 vast majority of cases. */
2754 maybe_make_export_env ();
2757 if (make_child (savestring (the_printed_command), async) == 0)
2759 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
2763 simple_command->flags |= CMD_NO_FORK;
2765 subshell_environment = SUBSHELL_FORK;
2766 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2767 subshell_environment |= SUBSHELL_PIPE;
2769 subshell_environment |= SUBSHELL_ASYNC;
2771 /* We need to do this before piping to handle some really
2772 pathological cases where one of the pipe file descriptors
2775 close_fd_bitmap (fds_to_close);
2777 do_piping (pipe_in, pipe_out);
2778 pipe_in = pipe_out = NO_PIPE;
2780 last_asynchronous_pid = old_last_async_pid;
2784 close_pipes (pipe_in, pipe_out);
2785 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2786 unlink_fifo_list ();
2788 command_line = (char *)NULL; /* don't free this. */
2789 bind_lastarg ((char *)NULL);
2794 /* If we are re-running this as the result of executing the `command'
2795 builtin, do not expand the command words a second time. */
2796 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2798 current_fds_to_close = fds_to_close;
2799 fix_assignment_words (simple_command->words);
2800 words = expand_words (simple_command->words);
2801 current_fds_to_close = (struct fd_bitmap *)NULL;
2804 words = copy_word_list (simple_command->words);
2806 /* It is possible for WORDS not to have anything left in it.
2807 Perhaps all the words consisted of `$foo', and there was
2808 no variable `$foo'. */
2811 this_command_name = 0;
2812 result = execute_null_command (simple_command->redirects,
2814 already_forked ? 0 : async);
2819 bind_lastarg ((char *)NULL);
2820 set_pipestatus_from_exit (result);
2825 lastarg = (char *)NULL;
2827 begin_unwind_frame ("simple-command");
2829 if (echo_command_at_execute)
2830 xtrace_print_word_list (words, 1);
2832 builtin = (sh_builtin_func_t *)NULL;
2833 func = (SHELL_VAR *)NULL;
2834 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2836 /* Posix.2 says special builtins are found before functions. We
2837 don't set builtin_is_special anywhere other than here, because
2838 this path is followed only when the `command' builtin is *not*
2839 being used, and we don't want to exit the shell if a special
2840 builtin executed with `command builtin' fails. `command' is not
2841 a special builtin. */
2842 if (posixly_correct)
2844 builtin = find_special_builtin (words->word->word);
2846 builtin_is_special = 1;
2849 func = find_function (words->word->word);
2852 /* In POSIX mode, assignment errors in the temporary environment cause a
2853 non-interactive shell to exit. */
2854 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
2856 last_command_exit_value = EXECUTION_FAILURE;
2857 jump_to_top_level (ERREXIT);
2860 add_unwind_protect (dispose_words, words);
2863 /* Bind the last word in this command to "$_" after execution. */
2864 for (lastword = words; lastword->next; lastword = lastword->next)
2866 lastarg = lastword->word->word;
2868 #if defined (JOB_CONTROL)
2869 /* Is this command a job control related thing? */
2870 if (words->word->word[0] == '%' && already_forked == 0)
2872 this_command_name = async ? "bg" : "fg";
2873 last_shell_builtin = this_shell_builtin;
2874 this_shell_builtin = builtin_address (this_command_name);
2875 result = (*this_shell_builtin) (words);
2879 /* One other possiblilty. The user may want to resume an existing job.
2880 If they do, find out whether this word is a candidate for a running
2882 if (job_control && already_forked == 0 && async == 0 &&
2883 !first_word_quoted &&
2885 words->word->word[0] &&
2886 !simple_command->redirects &&
2887 pipe_in == NO_PIPE &&
2888 pipe_out == NO_PIPE &&
2889 (temp = get_string_value ("auto_resume")))
2891 int job, jflags, started_status;
2893 jflags = JM_STOPPED|JM_FIRSTMATCH;
2894 if (STREQ (temp, "exact"))
2896 else if (STREQ (temp, "substring"))
2897 jflags |= JM_SUBSTRING;
2899 jflags |= JM_PREFIX;
2900 job = get_job_by_name (words->word->word, jflags);
2903 run_unwind_frame ("simple-command");
2904 this_command_name = "fg";
2905 last_shell_builtin = this_shell_builtin;
2906 this_shell_builtin = builtin_address ("fg");
2908 started_status = start_job (job, 1);
2909 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2912 #endif /* JOB_CONTROL */
2914 /* Remember the name of this command globally. */
2915 this_command_name = words->word->word;
2919 /* This command could be a shell builtin or a user-defined function.
2920 We have already found special builtins by this time, so we do not
2921 set builtin_is_special. If this is a function or builtin, and we
2922 have pipes, then fork a subshell in here. Otherwise, just execute
2923 the command directly. */
2924 if (func == 0 && builtin == 0)
2925 builtin = find_shell_builtin (this_command_name);
2927 last_shell_builtin = this_shell_builtin;
2928 this_shell_builtin = builtin;
2930 if (builtin || func)
2934 /* reset_terminating_signals (); */ /* XXX */
2935 /* Cancel traps, in trap.c. */
2936 restore_original_signals ();
2940 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2941 pipe_in == NO_PIPE &&
2942 (stdin_redirects (simple_command->redirects) == 0))
2943 async_redirect_stdin ();
2944 setup_async_signals ();
2948 execute_subshell_builtin_or_function
2949 (words, simple_command->redirects, builtin, func,
2950 pipe_in, pipe_out, async, fds_to_close,
2951 simple_command->flags);
2956 result = execute_builtin_or_function
2957 (words, builtin, func, simple_command->redirects, fds_to_close,
2958 simple_command->flags);
2961 if (result > EX_SHERRBASE)
2963 result = builtin_status (result);
2964 if (builtin_is_special)
2965 special_builtin_failed = 1;
2967 /* In POSIX mode, if there are assignment statements preceding
2968 a special builtin, they persist after the builtin
2970 if (posixly_correct && builtin_is_special && temporary_env)
2971 merge_temporary_env ();
2975 if (result == EX_USAGE)
2976 result = EX_BADUSAGE;
2977 else if (result > EX_SHERRBASE)
2978 result = EXECUTION_FAILURE;
2981 set_pipestatus_from_exit (result);
2987 if (command_line == 0)
2988 command_line = savestring (the_printed_command);
2990 execute_disk_command (words, simple_command->redirects, command_line,
2991 pipe_in, pipe_out, async, fds_to_close,
2992 simple_command->flags);
2995 bind_lastarg (lastarg);
2996 FREE (command_line);
2997 dispose_words (words);
2998 discard_unwind_frame ("simple-command");
2999 this_command_name = (char *)NULL; /* points to freed memory now */
3003 /* Translate the special builtin exit statuses. We don't really need a
3004 function for this; it's a placeholder for future work. */
3006 builtin_status (result)
3020 r = EXECUTION_FAILURE;
3023 r = EXECUTION_SUCCESS;
3030 execute_builtin (builtin, words, flags, subshell)
3031 sh_builtin_func_t *builtin;
3033 int flags, subshell;
3035 int old_e_flag, result, eval_unwind;
3038 old_e_flag = exit_immediately_on_error;
3039 /* The eval builtin calls parse_and_execute, which does not know about
3040 the setting of flags, and always calls the execution functions with
3041 flags that will exit the shell on an error if -e is set. If the
3042 eval builtin is being called, and we're supposed to ignore the exit
3043 value of the command, we turn the -e flag off ourselves, then
3044 restore it when the command completes. */
3045 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
3047 begin_unwind_frame ("eval_builtin");
3048 unwind_protect_int (exit_immediately_on_error);
3049 exit_immediately_on_error = 0;
3055 /* The temporary environment for a builtin is supposed to apply to
3056 all commands executed by that builtin. Currently, this is a
3057 problem only with the `unset', `source' and `eval' builtins. */
3059 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
3064 begin_unwind_frame ("builtin_env");
3068 push_scope (VC_BLTNENV, temporary_env);
3070 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
3071 temporary_env = (HASH_TABLE *)NULL;
3075 /* `return' does a longjmp() back to a saved environment in execute_function.
3076 If a variable assignment list preceded the command, and the shell is
3077 running in POSIX mode, we need to merge that into the shell_variables
3078 table, since `return' is a POSIX special builtin. */
3079 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3081 begin_unwind_frame ("return_temp_env");
3082 add_unwind_protect (merge_temporary_env, (char *)NULL);
3085 result = ((*builtin) (words->next));
3087 /* This shouldn't happen, but in case `return' comes back instead of
3088 longjmp'ing, we need to unwind. */
3089 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3090 discard_unwind_frame ("return_temp_env");
3092 if (subshell == 0 && isbltinenv)
3093 run_unwind_frame ("builtin_env");
3097 exit_immediately_on_error += old_e_flag;
3098 discard_unwind_frame ("eval_builtin");
3105 execute_function (var, words, flags, fds_to_close, async, subshell)
3109 struct fd_bitmap *fds_to_close;
3110 int async, subshell;
3112 int return_val, result;
3113 COMMAND *tc, *fc, *save_current;
3114 char *debug_trap, *error_trap, *return_trap;
3115 #if defined (ARRAY_VARS)
3116 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
3117 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
3119 FUNCTION_DEF *shell_fn;
3121 static int funcnest = 0;
3125 #if defined (ARRAY_VARS)
3126 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
3127 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
3128 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
3131 tc = (COMMAND *)copy_command (function_cell (var));
3132 if (tc && (flags & CMD_IGNORE_RETURN))
3133 tc->flags |= CMD_IGNORE_RETURN;
3137 begin_unwind_frame ("function_calling");
3138 push_context (var->name, subshell, temporary_env);
3139 add_unwind_protect (pop_context, (char *)NULL);
3140 unwind_protect_int (line_number);
3141 unwind_protect_int (return_catch_flag);
3142 unwind_protect_jmp_buf (return_catch);
3143 add_unwind_protect (dispose_command, (char *)tc);
3144 unwind_protect_pointer (this_shell_function);
3145 unwind_protect_int (loop_level);
3148 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
3150 temporary_env = (HASH_TABLE *)NULL;
3152 this_shell_function = var;
3153 make_funcname_visible (1);
3155 debug_trap = TRAP_STRING(DEBUG_TRAP);
3156 error_trap = TRAP_STRING(ERROR_TRAP);
3157 return_trap = TRAP_STRING(RETURN_TRAP);
3159 /* The order of the unwind protects for debug_trap, error_trap and
3160 return_trap is important here! unwind-protect commands are run
3161 in reverse order of registration. If this causes problems, take
3162 out the xfree unwind-protect calls and live with the small memory leak. */
3164 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3165 if the function has the trace attribute set, it inherits the DEBUG trap */
3166 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3170 debug_trap = savestring (debug_trap);
3171 add_unwind_protect (xfree, debug_trap);
3172 add_unwind_protect (set_debug_trap, debug_trap);
3174 restore_default_signal (DEBUG_TRAP);
3177 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3178 if (error_trap && error_trace_mode == 0)
3182 error_trap = savestring (error_trap);
3183 add_unwind_protect (xfree, error_trap);
3184 add_unwind_protect (set_error_trap, error_trap);
3186 restore_default_signal (ERROR_TRAP);
3189 /* Shell functions inherit the RETURN trap if function tracing is on
3190 globally or on individually for this function. */
3192 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3194 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
3199 return_trap = savestring (return_trap);
3200 add_unwind_protect (xfree, return_trap);
3201 add_unwind_protect (set_return_trap, return_trap);
3203 restore_default_signal (RETURN_TRAP);
3207 #if defined (ARRAY_VARS)
3208 /* This is quite similar to the code in shell.c and elsewhere. */
3209 shell_fn = find_function_def (this_shell_function->name);
3210 sfile = shell_fn ? shell_fn->source_file : "";
3211 array_push (funcname_a, this_shell_function->name);
3213 array_push (bash_source_a, sfile);
3214 t = itos (executing_line_number ());
3215 array_push (bash_lineno_a, t);
3219 /* The temporary environment for a function is supposed to apply to
3220 all commands executed within the function body. */
3222 remember_args (words->next, 1);
3224 /* Update BASH_ARGV and BASH_ARGC */
3226 push_args (words->next);
3228 /* Number of the line on which the function body starts. */
3229 line_number = function_line_number = tc->line;
3231 #if defined (JOB_CONTROL)
3233 stop_pipeline (async, (COMMAND *)NULL);
3238 return_catch_flag++;
3239 return_val = setjmp (return_catch);
3243 result = return_catch_value;
3244 /* Run the RETURN trap in the function's context. */
3245 save_current = currently_executing_command;
3247 currently_executing_command = save_current;
3251 /* Run the debug trap here so we can trap at the start of a function's
3252 execution rather than the execution of the body's first command. */
3253 showing_function_line = 1;
3254 save_current = currently_executing_command;
3255 result = run_debug_trap ();
3256 #if defined (DEBUGGER)
3257 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3258 skip the command. */
3259 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
3261 showing_function_line = 0;
3262 currently_executing_command = save_current;
3263 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3265 /* Run the RETURN trap in the function's context */
3266 save_current = currently_executing_command;
3268 currently_executing_command = save_current;
3271 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3273 save_current = currently_executing_command;
3275 currently_executing_command = save_current;
3277 showing_function_line = 0;
3280 /* Restore BASH_ARGC and BASH_ARGV */
3285 run_unwind_frame ("function_calling");
3288 #if defined (ARRAY_VARS)
3289 /* These two variables cannot be unset, and cannot be affected by the
3291 array_pop (bash_source_a);
3292 array_pop (bash_lineno_a);
3294 /* FUNCNAME can be unset, and so can potentially be changed by the
3296 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
3297 if (nfv == funcname_v)
3298 array_pop (funcname_a);
3301 if (variable_context == 0 || this_shell_function == 0)
3302 make_funcname_visible (0);
3307 /* A convenience routine for use by other parts of the shell to execute
3308 a particular shell function. */
3310 execute_shell_function (var, words)
3315 struct fd_bitmap *bitmap;
3317 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
3318 begin_unwind_frame ("execute-shell-function");
3319 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
3321 ret = execute_function (var, words, 0, bitmap, 0, 0);
3323 dispose_fd_bitmap (bitmap);
3324 discard_unwind_frame ("execute-shell-function");
3329 /* Execute a shell builtin or function in a subshell environment. This
3330 routine does not return; it only calls exit(). If BUILTIN is non-null,
3331 it points to a function to call to execute a shell builtin; otherwise
3332 VAR points at the body of a function to execute. WORDS is the arguments
3333 to the command, REDIRECTS specifies redirections to perform before the
3334 command is executed. */
3336 execute_subshell_builtin_or_function (words, redirects, builtin, var,
3337 pipe_in, pipe_out, async, fds_to_close,
3340 REDIRECT *redirects;
3341 sh_builtin_func_t *builtin;
3343 int pipe_in, pipe_out, async;
3344 struct fd_bitmap *fds_to_close;
3348 #if defined (JOB_CONTROL)
3351 jobs_hack = (builtin == jobs_builtin) &&
3352 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
3355 /* A subshell is neither a login shell nor interactive. */
3356 login_shell = interactive = 0;
3358 subshell_environment = SUBSHELL_ASYNC;
3360 maybe_make_export_env (); /* XXX - is this needed? */
3362 #if defined (JOB_CONTROL)
3363 /* Eradicate all traces of job control after we fork the subshell, so
3364 all jobs begun by this subshell are in the same process group as
3365 the shell itself. */
3367 /* Allow the output of `jobs' to be piped. */
3369 kill_current_pipeline ();
3371 without_job_control ();
3373 set_sigchld_handler ();
3374 #endif /* JOB_CONTROL */
3376 set_sigint_handler ();
3379 close_fd_bitmap (fds_to_close);
3381 do_piping (pipe_in, pipe_out);
3383 if (do_redirections (redirects, RX_ACTIVE) != 0)
3384 exit (EXECUTION_FAILURE);
3388 /* Give builtins a place to jump back to on failure,
3389 so we don't go back up to main(). */
3390 result = setjmp (top_level);
3392 if (result == EXITPROG)
3393 exit (last_command_exit_value);
3395 exit (EXECUTION_FAILURE);
3398 r = execute_builtin (builtin, words, flags, 1);
3405 exit (execute_function (var, words, flags, fds_to_close, async, 1));
3408 /* Execute a builtin or function in the current shell context. If BUILTIN
3409 is non-null, it is the builtin command to execute, otherwise VAR points
3410 to the body of a function. WORDS are the command's arguments, REDIRECTS
3411 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3412 file descriptors to close.
3414 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3415 not undone before this function returns. */
3417 execute_builtin_or_function (words, builtin, var, redirects,
3418 fds_to_close, flags)
3420 sh_builtin_func_t *builtin;
3422 REDIRECT *redirects;
3423 struct fd_bitmap *fds_to_close;
3427 REDIRECT *saved_undo_list;
3428 sh_builtin_func_t *saved_this_shell_builtin;
3430 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
3432 cleanup_redirects (redirection_undo_list);
3433 redirection_undo_list = (REDIRECT *)NULL;
3434 dispose_exec_redirects ();
3435 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3438 saved_this_shell_builtin = this_shell_builtin;
3439 saved_undo_list = redirection_undo_list;
3441 /* Calling the "exec" builtin changes redirections forever. */
3442 if (builtin == exec_builtin)
3444 dispose_redirects (saved_undo_list);
3445 saved_undo_list = exec_redirection_undo_list;
3446 exec_redirection_undo_list = (REDIRECT *)NULL;
3449 dispose_exec_redirects ();
3451 if (saved_undo_list)
3453 begin_unwind_frame ("saved redirects");
3454 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3457 redirection_undo_list = (REDIRECT *)NULL;
3460 result = execute_builtin (builtin, words, flags, 0);
3462 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3464 /* We do this before undoing the effects of any redirections. */
3465 if (ferror (stdout))
3468 /* If we are executing the `command' builtin, but this_shell_builtin is
3469 set to `exec_builtin', we know that we have something like
3470 `command exec [redirection]', since otherwise `exec' would have
3471 overwritten the shell and we wouldn't get here. In this case, we
3472 want to behave as if the `command' builtin had not been specified
3473 and preserve the redirections. */
3474 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3476 if (saved_undo_list)
3477 dispose_redirects (saved_undo_list);
3478 redirection_undo_list = exec_redirection_undo_list;
3479 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3480 discard_unwind_frame ("saved_redirects");
3483 if (saved_undo_list)
3485 redirection_undo_list = saved_undo_list;
3486 discard_unwind_frame ("saved redirects");
3489 if (redirection_undo_list)
3491 cleanup_redirects (redirection_undo_list);
3492 redirection_undo_list = (REDIRECT *)NULL;
3499 setup_async_signals ()
3501 #if defined (__BEOS__)
3502 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3505 #if defined (JOB_CONTROL)
3506 if (job_control == 0)
3509 set_signal_handler (SIGINT, SIG_IGN);
3510 set_signal_ignored (SIGINT);
3511 set_signal_handler (SIGQUIT, SIG_IGN);
3512 set_signal_ignored (SIGQUIT);
3516 /* Execute a simple command that is hopefully defined in a disk file
3521 3) look up the command
3524 6) If the execve failed, see if the file has executable mode set.
3525 If so, and it isn't a directory, then execute its contents as
3528 Note that the filename hashing stuff has to take place up here,
3529 in the parent. This is probably why the Bourne style shells
3530 don't handle it, since that would require them to go through
3531 this gnarly hair, for no good reason.
3533 NOTE: callers expect this to fork or exit(). */
3535 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3536 async, fds_to_close, cmdflags)
3538 REDIRECT *redirects;
3540 int pipe_in, pipe_out, async;
3541 struct fd_bitmap *fds_to_close;
3544 char *pathname, *command, **args;
3548 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3549 pathname = words->word->word;
3551 #if defined (RESTRICTED_SHELL)
3552 command = (char *)NULL;
3553 if (restricted && xstrchr (pathname, '/'))
3555 internal_error (_("%s: restricted: cannot specify `/' in command names"),
3557 last_command_exit_value = EXECUTION_FAILURE;
3559 /* If we're not going to fork below, we must already be in a child
3560 process or a context in which it's safe to call exit(2). */
3561 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3562 exit (last_command_exit_value);
3566 #endif /* RESTRICTED_SHELL */
3568 command = search_for_command (pathname);
3572 maybe_make_export_env ();
3573 put_command_name_into_env (command);
3576 /* We have to make the child before we check for the non-existence
3577 of COMMAND, since we want the error messages to be redirected. */
3578 /* If we can get away without forking and there are no pipes to deal with,
3579 don't bother to fork, just directly exec the command. */
3580 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3583 pid = make_child (savestring (command_line), async);
3587 int old_interactive;
3590 /* This has been disabled for the time being. */
3591 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3592 if (posixly_correct == 0)
3593 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
3597 /* Cancel traps, in trap.c. */
3598 restore_original_signals ();
3600 /* restore_original_signals may have undone the work done
3601 by make_child to ensure that SIGINT and SIGQUIT are ignored
3602 in asynchronous children. */
3605 if ((cmdflags & CMD_STDIN_REDIR) &&
3606 pipe_in == NO_PIPE &&
3607 (stdin_redirects (redirects) == 0))
3608 async_redirect_stdin ();
3609 setup_async_signals ();
3612 /* This functionality is now provided by close-on-exec of the
3613 file descriptors manipulated by redirection and piping.
3614 Some file descriptors still need to be closed in all children
3615 because of the way bash does pipes; fds_to_close is a
3616 bitmap of all such file descriptors. */
3618 close_fd_bitmap (fds_to_close);
3620 do_piping (pipe_in, pipe_out);
3622 old_interactive = interactive;
3626 subshell_environment = SUBSHELL_FORK;
3628 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
3630 #if defined (PROCESS_SUBSTITUTION)
3631 /* Try to remove named pipes that may have been created as the
3632 result of redirections. */
3633 unlink_fifo_list ();
3634 #endif /* PROCESS_SUBSTITUTION */
3635 exit (EXECUTION_FAILURE);
3639 interactive = old_interactive;
3643 internal_error (_("%s: command not found"), pathname);
3644 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3647 /* Execve expects the command name to be in args[0]. So we
3648 leave it there, in the same format that the user used to
3650 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
3651 exit (shell_execve (command, args, export_env));
3656 /* Make sure that the pipes are closed in the parent. */
3657 close_pipes (pipe_in, pipe_out);
3658 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3659 unlink_fifo_list ();
3665 /* CPP defines to decide whether a particular index into the #! line
3666 corresponds to a valid interpreter name or argument character, or
3667 whitespace. The MSDOS define is to allow \r to be treated the same
3670 #if !defined (MSDOS)
3671 # define STRINGCHAR(ind) \
3672 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3673 # define WHITECHAR(ind) \
3674 (ind < sample_len && whitespace (sample[ind]))
3676 # define STRINGCHAR(ind) \
3677 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3678 # define WHITECHAR(ind) \
3679 (ind < sample_len && whitespace (sample[ind]))
3683 getinterp (sample, sample_len, endp)
3685 int sample_len, *endp;
3691 /* Find the name of the interpreter to exec. */
3692 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
3695 for (start = i; STRINGCHAR(i); i++)
3698 execname = substring (sample, start, i);
3705 #if !defined (HAVE_HASH_BANG_EXEC)
3706 /* If the operating system on which we're running does not handle
3707 the #! executable format, then help out. SAMPLE is the text read
3708 from the file, SAMPLE_LEN characters. COMMAND is the name of
3709 the script; it and ARGS, the arguments given by the user, will
3710 become arguments to the specified interpreter. ENV is the environment
3711 to pass to the interpreter.
3713 The word immediately following the #! is the interpreter to execute.
3714 A single argument to the interpreter is allowed. */
3717 execute_shell_script (sample, sample_len, command, args, env)
3723 char *execname, *firstarg;
3724 int i, start, size_increment, larry;
3726 /* Find the name of the interpreter to exec. */
3727 execname = getinterp (sample, sample_len, &i);
3730 /* Now the argument, if any. */
3731 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3734 /* If there is more text on the line, then it is an argument for the
3739 for (start = i; STRINGCHAR(i); i++)
3741 firstarg = substring ((char *)sample, start, i);
3745 larry = strvec_len (args) + size_increment;
3746 args = strvec_resize (args, larry + 1);
3748 for (i = larry - 1; i; i--)
3749 args[i] = args[i - size_increment];
3760 args[larry] = (char *)NULL;
3762 return (shell_execve (execname, args, env));
3767 #endif /* !HAVE_HASH_BANG_EXEC */
3770 initialize_subshell ()
3773 /* Forget about any aliases that we knew of. We are in a subshell. */
3774 delete_all_aliases ();
3777 #if defined (HISTORY)
3778 /* Forget about the history lines we have read. This is a non-interactive
3780 history_lines_this_session = 0;
3783 #if defined (JOB_CONTROL)
3784 /* Forget about the way job control was working. We are in a subshell. */
3785 without_job_control ();
3786 set_sigchld_handler ();
3788 #endif /* JOB_CONTROL */
3790 /* Reset the values of the shell flags and options. */
3791 reset_shell_flags ();
3792 reset_shell_options ();
3793 reset_shopt_options ();
3795 /* Zero out builtin_env, since this could be a shell script run from a
3796 sourced file with a temporary environment supplied to the `source/.'
3797 builtin. Such variables are not supposed to be exported (empirical
3798 testing with sh and ksh). Just throw it away; don't worry about a
3800 if (vc_isbltnenv (shell_variables))
3801 shell_variables = shell_variables->down;
3803 clear_unwind_protect_list (0);
3805 /* We're no longer inside a shell function. */
3806 variable_context = return_catch_flag = 0;
3808 /* If we're not interactive, close the file descriptor from which we're
3809 reading the current shell script. */
3810 if (interactive_shell == 0)
3811 unset_bash_input (0);
3814 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3815 # define SETOSTYPE(x) __setostype(x)
3817 # define SETOSTYPE(x)
3820 #define READ_SAMPLE_BUF(file, buf, len) \
3823 fd = open(file, O_RDONLY); \
3826 len = read (fd, buf, 80); \
3834 /* Call execve (), handling interpreting shell scripts, and handling
3837 shell_execve (command, args, env)
3846 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3847 execve (command, args, env);
3848 i = errno; /* error from execve() */
3851 /* If we get to this point, then start checking out the file.
3852 Maybe it is something we can hack ourselves. */
3855 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3856 internal_error (_("%s: is a directory"), command);
3857 else if (executable_file (command) == 0)
3860 file_error (command);
3862 /* errors not involving the path argument to execve. */
3863 else if (i == E2BIG || i == ENOMEM)
3866 file_error (command);
3870 /* The file has the execute bits set, but the kernel refuses to
3871 run it for some reason. See why. */
3872 #if defined (HAVE_HASH_BANG_EXEC)
3873 READ_SAMPLE_BUF (command, sample, sample_len);
3874 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3879 interp = getinterp (sample, sample_len, (int *)NULL);
3880 ilen = strlen (interp);
3882 if (interp[ilen - 1] == '\r')
3884 interp = xrealloc (interp, ilen + 2);
3885 interp[ilen - 1] = '^';
3887 interp[ilen + 1] = '\0';
3889 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
3895 file_error (command);
3897 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3900 /* This file is executable.
3901 If it begins with #!, then help out people with losing operating
3902 systems. Otherwise, check to see if it is a binary file by seeing
3903 if the contents of the first line (or up to 80 characters) are in the
3904 ASCII set. If it's a text file, execute the contents as shell commands,
3905 otherwise return 126 (EX_BINARY_FILE). */
3906 READ_SAMPLE_BUF (command, sample, sample_len);
3908 if (sample_len == 0)
3909 return (EXECUTION_SUCCESS);
3911 /* Is this supposed to be an executable script?
3912 If so, the format of the line is "#! interpreter [argument]".
3913 A single argument is allowed. The BSD kernel restricts
3914 the length of the entire line to 32 characters (32 bytes
3915 being the size of the BSD exec header), but we allow 80
3919 #if !defined (HAVE_HASH_BANG_EXEC)
3920 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3921 return (execute_shell_script (sample, sample_len, command, args, env));
3924 if (check_binary_file (sample, sample_len))
3926 internal_error (_("%s: cannot execute binary file"), command);
3927 return (EX_BINARY_FILE);
3931 /* We have committed to attempting to execute the contents of this file
3932 as shell commands. */
3934 initialize_subshell ();
3936 set_sigint_handler ();
3938 /* Insert the name of this shell into the argument list. */
3939 larray = strvec_len (args) + 1;
3940 args = strvec_resize (args, larray + 1);
3942 for (i = larray - 1; i; i--)
3943 args[i] = args[i - 1];
3945 args[0] = shell_name;
3947 args[larray] = (char *)NULL;
3949 if (args[0][0] == '-')
3952 #if defined (RESTRICTED_SHELL)
3954 change_flag ('r', FLAG_OFF);
3959 /* Can't free subshell_argv[0]; that is shell_name. */
3960 for (i = 1; i < subshell_argc; i++)
3961 free (subshell_argv[i]);
3962 free (subshell_argv);
3965 dispose_command (currently_executing_command); /* XXX */
3966 currently_executing_command = (COMMAND *)NULL;
3968 subshell_argc = larray;
3969 subshell_argv = args;
3970 subshell_envp = env;
3972 unbind_args (); /* remove the positional parameters */
3974 longjmp (subshell_top_level, 1);
3979 execute_intern_function (name, function)
3985 if (check_identifier (name, posixly_correct) == 0)
3987 if (posixly_correct && interactive_shell == 0)
3989 last_command_exit_value = EX_USAGE;
3990 jump_to_top_level (ERREXIT);
3992 return (EXECUTION_FAILURE);
3995 var = find_function (name->word);
3996 if (var && (readonly_p (var) || noassign_p (var)))
3998 if (readonly_p (var))
3999 internal_error (_("%s: readonly function"), var->name);
4000 return (EXECUTION_FAILURE);
4003 bind_function (name->word, function);
4004 return (EXECUTION_SUCCESS);
4007 #if defined (INCLUDE_UNUSED)
4008 #if defined (PROCESS_SUBSTITUTION)
4012 register int i, fd_table_size;
4014 fd_table_size = getdtablesize ();
4015 if (fd_table_size > 256) /* clamp to a reasonable value */
4016 fd_table_size = 256;
4018 for (i = 3; i < fd_table_size; i++)
4021 #endif /* PROCESS_SUBSTITUTION */
4025 close_pipes (in, out)
4035 dup_error (oldd, newd)
4038 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
4041 /* Redirect input and output to be from and to the specified pipes.
4042 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4044 do_piping (pipe_in, pipe_out)
4045 int pipe_in, pipe_out;
4047 if (pipe_in != NO_PIPE)
4049 if (dup2 (pipe_in, 0) < 0)
4050 dup_error (pipe_in, 0);
4054 if (pipe_out != NO_PIPE)
4056 if (pipe_out != REDIRECT_BOTH)
4058 if (dup2 (pipe_out, 1) < 0)
4059 dup_error (pipe_out, 1);
4060 if (pipe_out == 0 || pipe_out > 1)
4065 if (dup2 (1, 2) < 0)