1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2007 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 static int line_number_for_err_trap;
219 /* For catching RETURN in a function. */
220 int return_catch_flag;
221 int return_catch_value;
222 procenv_t return_catch;
224 /* The value returned by the last synchronous command. */
225 int last_command_exit_value;
227 /* Whether or not the last command (corresponding to last_command_exit_value)
228 was terminated by a signal, and, if so, which one. */
229 int last_command_exit_signal;
231 /* The list of redirections to perform which will undo the redirections
232 that I made in the shell. */
233 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
235 /* The list of redirections to perform which will undo the internal
236 redirections performed by the `exec' builtin. These are redirections
237 that must be undone even when exec discards redirection_undo_list. */
238 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
240 /* Non-zero if we have just forked and are currently running in a subshell
242 int subshell_environment;
244 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
245 int subshell_level = 0;
247 /* Currently-executing shell function. */
248 SHELL_VAR *this_shell_function;
250 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
251 int match_ignore_case = 0;
253 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
255 #define FD_BITMAP_DEFAULT_SIZE 32
257 /* Functions to allocate and deallocate the structures used to pass
258 information from the shell to its children about file descriptors
264 struct fd_bitmap *ret;
266 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
272 ret->bitmap = (char *)xmalloc (size);
273 memset (ret->bitmap, '\0', size);
276 ret->bitmap = (char *)NULL;
281 dispose_fd_bitmap (fdbp)
282 struct fd_bitmap *fdbp;
289 close_fd_bitmap (fdbp)
290 struct fd_bitmap *fdbp;
296 for (i = 0; i < fdbp->size; i++)
305 /* Return the line number of the currently executing command. */
307 executing_line_number ()
309 if (executing && showing_function_line == 0 &&
310 (variable_context == 0 || interactive_shell == 0) &&
311 currently_executing_command)
313 #if defined (COND_COMMAND)
314 if (currently_executing_command->type == cm_cond)
315 return currently_executing_command->value.Cond->line;
317 #if defined (DPAREN_ARITHMETIC)
318 else if (currently_executing_command->type == cm_arith)
319 return currently_executing_command->value.Arith->line;
321 #if defined (ARITH_FOR_COMMAND)
322 else if (currently_executing_command->type == cm_arith_for)
323 return currently_executing_command->value.ArithFor->line;
332 /* Execute the command passed in COMMAND. COMMAND is exactly what
333 read_command () places into GLOBAL_COMMAND. See "command.h" for the
334 details of the command structure.
336 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
337 return values. Executing a command with nothing in it returns
338 EXECUTION_SUCCESS. */
340 execute_command (command)
343 struct fd_bitmap *bitmap;
346 current_fds_to_close = (struct fd_bitmap *)NULL;
347 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
348 begin_unwind_frame ("execute-command");
349 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
351 /* Just do the command, but not asynchronously. */
352 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
354 dispose_fd_bitmap (bitmap);
355 discard_unwind_frame ("execute-command");
357 #if defined (PROCESS_SUBSTITUTION)
358 /* don't unlink fifos if we're in a shell function; wait until the function
360 if (variable_context == 0)
362 #endif /* PROCESS_SUBSTITUTION */
368 /* Return 1 if TYPE is a shell control structure type. */
370 shell_control_structure (type)
371 enum command_type type;
375 #if defined (ARITH_FOR_COMMAND)
378 #if defined (SELECT_COMMAND)
381 #if defined (DPAREN_ARITHMETIC)
384 #if defined (COND_COMMAND)
393 case cm_function_def:
401 /* A function to use to unwind_protect the redirection undo list
404 cleanup_redirects (list)
407 do_redirections (list, RX_ACTIVE);
408 dispose_redirects (list);
412 /* Function to unwind_protect the redirections for functions and builtins. */
414 cleanup_func_redirects (list)
417 do_redirections (list, RX_ACTIVE);
422 dispose_exec_redirects ()
424 if (exec_redirection_undo_list)
426 dispose_redirects (exec_redirection_undo_list);
427 exec_redirection_undo_list = (REDIRECT *)NULL;
431 #if defined (JOB_CONTROL)
432 /* A function to restore the signal mask to its proper value when the shell
433 is interrupted or errors occur while creating a pipeline. */
435 restore_signal_mask (set)
438 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
440 #endif /* JOB_CONTROL */
443 /* A debugging function that can be called from gdb, for instance. */
448 int f, fd_table_size;
450 fd_table_size = getdtablesize ();
452 fprintf (stderr, "pid %ld open files:", (long)getpid ());
453 for (i = 3; i < fd_table_size; i++)
455 if ((f = fcntl (i, F_GETFD, 0)) != -1)
456 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
458 fprintf (stderr, "\n");
463 async_redirect_stdin ()
467 fd = open ("/dev/null", O_RDONLY);
474 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
477 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
479 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
480 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
481 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
482 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
483 from and where it goes. They can have the value of NO_PIPE, which means
485 FDS_TO_CLOSE is a list of file descriptors to close once the child has
486 been forked. This list often contains the unusable sides of pipes, etc.
488 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
489 return values. Executing a command with nothing in it returns
490 EXECUTION_SUCCESS. */
492 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
496 int pipe_in, pipe_out;
497 struct fd_bitmap *fds_to_close;
499 int exec_result, invert, ignore_return, was_error_trap;
500 REDIRECT *my_undo_list, *exec_undo_list;
501 volatile int last_pid;
502 volatile int save_line_number;
505 if (command == 0 || breaking || continuing || read_but_dont_execute)
506 return (EXECUTION_SUCCESS);
508 if (breaking || continuing)
509 return (last_command_exit_value);
510 if (command == 0 || read_but_dont_execute)
511 return (EXECUTION_SUCCESS);
515 run_pending_traps ();
518 if (running_trap == 0)
520 currently_executing_command = command;
522 invert = (command->flags & CMD_INVERT_RETURN) != 0;
524 /* If we're inverting the return value and `set -e' has been executed,
525 we don't want a failing command to inadvertently cause the shell
527 if (exit_immediately_on_error && invert) /* XXX */
528 command->flags |= CMD_IGNORE_RETURN; /* XXX */
530 exec_result = EXECUTION_SUCCESS;
532 /* If a command was being explicitly run in a subshell, or if it is
533 a shell control-structure, and it has a pipe, then we do the command
535 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
536 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
538 if (command->type == cm_subshell ||
539 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
540 (shell_control_structure (command->type) &&
541 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
545 /* Fork a subshell, turn off the subshell bit, turn off job
546 control and call execute_command () on the command again. */
547 paren_pid = make_child (savestring (make_command_string (command)),
550 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
554 close_pipes (pipe_in, pipe_out);
556 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
559 /* If we are part of a pipeline, and not the end of the pipeline,
560 then we should simply return and let the last command in the
561 pipe be waited for. If we are not in a pipeline, or are the
562 last command in the pipeline, then we wait for the subshell
563 and return its exit status as usual. */
564 if (pipe_out != NO_PIPE)
565 return (EXECUTION_SUCCESS);
567 stop_pipeline (asynchronous, (COMMAND *)NULL);
569 if (asynchronous == 0)
571 last_command_exit_value = wait_for (paren_pid);
573 /* If we have to, invert the return value. */
575 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
577 : EXECUTION_SUCCESS);
579 exec_result = last_command_exit_value;
581 return (last_command_exit_value = exec_result);
585 DESCRIBE_PID (paren_pid);
587 run_pending_traps ();
589 return (EXECUTION_SUCCESS);
594 #if defined (COMMAND_TIMING)
595 if (command->flags & CMD_TIME_PIPELINE)
599 command->flags |= CMD_FORCE_SUBSHELL;
600 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
604 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
606 if (running_trap == 0)
608 currently_executing_command = (COMMAND *)NULL;
610 return (exec_result);
612 #endif /* COMMAND_TIMING */
614 if (shell_control_structure (command->type) && command->redirects)
615 stdin_redir = stdin_redirects (command->redirects);
617 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
619 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
621 cleanup_redirects (redirection_undo_list);
622 redirection_undo_list = (REDIRECT *)NULL;
623 dispose_exec_redirects ();
624 return (last_command_exit_value = EXECUTION_FAILURE);
627 if (redirection_undo_list)
629 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
630 dispose_redirects (redirection_undo_list);
631 redirection_undo_list = (REDIRECT *)NULL;
634 my_undo_list = (REDIRECT *)NULL;
636 if (exec_redirection_undo_list)
638 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
639 dispose_redirects (exec_redirection_undo_list);
640 exec_redirection_undo_list = (REDIRECT *)NULL;
643 exec_undo_list = (REDIRECT *)NULL;
645 if (my_undo_list || exec_undo_list)
646 begin_unwind_frame ("loop_redirections");
649 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
652 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
654 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
658 switch (command->type)
662 save_line_number = line_number;
663 /* We can't rely on variables retaining their values across a
664 call to execute_simple_command if a longjmp occurs as the
665 result of a `return' builtin. This is true for sure with gcc. */
666 #if defined (RECYCLES_PIDS)
667 last_made_pid = NO_PID;
669 last_pid = last_made_pid;
670 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
672 if (ignore_return && command->value.Simple)
673 command->value.Simple->flags |= CMD_IGNORE_RETURN;
674 if (command->flags & CMD_STDIN_REDIR)
675 command->value.Simple->flags |= CMD_STDIN_REDIR;
677 line_number_for_err_trap = line_number = command->value.Simple->line;
679 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
680 asynchronous, fds_to_close);
681 line_number = save_line_number;
683 /* The temporary environment should be used for only the simple
684 command immediately following its definition. */
685 dispose_used_env_vars ();
687 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
688 /* Reclaim memory allocated with alloca () on machines which
689 may be using the alloca emulation code. */
691 #endif /* (ultrix && mips) || C_ALLOCA */
693 /* If we forked to do the command, then we must wait_for ()
696 /* XXX - this is something to watch out for if there are problems
697 when the shell is compiled without job control. */
698 if (already_making_children && pipe_out == NO_PIPE &&
699 last_made_pid != last_pid)
701 stop_pipeline (asynchronous, (COMMAND *)NULL);
705 DESCRIBE_PID (last_made_pid);
708 #if !defined (JOB_CONTROL)
709 /* Do not wait for asynchronous processes started from
711 if (last_made_pid != last_asynchronous_pid)
713 /* When executing a shell function that executes other
714 commands, this causes the last simple command in
715 the function to be waited for twice. This also causes
716 subshells forked to execute builtin commands (e.g., in
717 pipelines) to be waited for twice. */
718 exec_result = wait_for (last_made_pid);
722 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
724 last_command_exit_value = exec_result;
728 if (ignore_return == 0 && invert == 0 &&
729 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
730 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
732 last_command_exit_value = exec_result;
733 run_pending_traps ();
734 jump_to_top_level (ERREXIT);
741 command->value.For->flags |= CMD_IGNORE_RETURN;
742 exec_result = execute_for_command (command->value.For);
745 #if defined (ARITH_FOR_COMMAND)
748 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
749 exec_result = execute_arith_for_command (command->value.ArithFor);
753 #if defined (SELECT_COMMAND)
756 command->value.Select->flags |= CMD_IGNORE_RETURN;
757 exec_result = execute_select_command (command->value.Select);
763 command->value.Case->flags |= CMD_IGNORE_RETURN;
764 exec_result = execute_case_command (command->value.Case);
769 command->value.While->flags |= CMD_IGNORE_RETURN;
770 exec_result = execute_while_command (command->value.While);
775 command->value.While->flags |= CMD_IGNORE_RETURN;
776 exec_result = execute_until_command (command->value.While);
781 command->value.If->flags |= CMD_IGNORE_RETURN;
782 exec_result = execute_if_command (command->value.If);
787 /* This code can be executed from either of two paths: an explicit
788 '{}' command, or via a function call. If we are executed via a
789 function call, we have already taken care of the function being
790 executed in the background (down there in execute_simple_command ()),
791 and this command should *not* be marked as asynchronous. If we
792 are executing a regular '{}' group command, and asynchronous == 1,
793 we must want to execute the whole command in the background, so we
794 need a subshell, and we want the stuff executed in that subshell
795 (this group command) to be executed in the foreground of that
796 subshell (i.e. there will not be *another* subshell forked).
798 What we do is to force a subshell if asynchronous, and then call
799 execute_command_internal again with asynchronous still set to 1,
800 but with the original group command, so the printed command will
803 The code above that handles forking off subshells will note that
804 both subshell and async are on, and turn off async in the child
805 after forking the subshell (but leave async set in the parent, so
806 the normal call to describe_pid is made). This turning off
807 async is *crucial*; if it is not done, this will fall into an
808 infinite loop of executions through this spot in subshell after
809 subshell until the process limit is exhausted. */
813 command->flags |= CMD_FORCE_SUBSHELL;
815 execute_command_internal (command, 1, pipe_in, pipe_out,
820 if (ignore_return && command->value.Group->command)
821 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
823 execute_command_internal (command->value.Group->command,
824 asynchronous, pipe_in, pipe_out,
830 exec_result = execute_connection (command, asynchronous,
831 pipe_in, pipe_out, fds_to_close);
834 #if defined (DPAREN_ARITHMETIC)
837 command->value.Arith->flags |= CMD_IGNORE_RETURN;
838 exec_result = execute_arith_command (command->value.Arith);
842 #if defined (COND_COMMAND)
845 command->value.Cond->flags |= CMD_IGNORE_RETURN;
846 save_line_number = line_number;
847 exec_result = execute_cond_command (command->value.Cond);
848 line_number = save_line_number;
852 case cm_function_def:
853 exec_result = execute_intern_function (command->value.Function_def->name,
854 command->value.Function_def->command);
858 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
863 do_redirections (my_undo_list, RX_ACTIVE);
864 dispose_redirects (my_undo_list);
868 dispose_redirects (exec_undo_list);
870 if (my_undo_list || exec_undo_list)
871 discard_unwind_frame ("loop_redirections");
873 /* Invert the return value if we have to */
875 exec_result = (exec_result == EXECUTION_SUCCESS)
879 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
880 /* This is where we set PIPESTATUS from the exit status of the appropriate
881 compound commands (the ones that look enough like simple commands to
882 cause confusion). We might be able to optimize by not doing this if
883 subshell_environment != 0. */
884 switch (command->type)
886 # if defined (DPAREN_ARITHMETIC)
889 # if defined (COND_COMMAND)
892 set_pipestatus_from_exit (exec_result);
897 last_command_exit_value = exec_result;
898 run_pending_traps ();
900 if (running_trap == 0)
902 currently_executing_command = (COMMAND *)NULL;
903 return (last_command_exit_value);
906 #if defined (COMMAND_TIMING)
908 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
909 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
910 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
911 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
914 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
915 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
917 static int precs[] = { 0, 100, 10, 1 };
919 /* Expand one `%'-prefixed escape sequence from a time format string. */
921 mkfmt (buf, prec, lng, sec, sec_fraction)
928 char abuf[INT_STRLEN_BOUND(time_t) + 1];
932 abuf[sizeof(abuf) - 1] = '\0';
934 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
939 aind = sizeof(abuf) - 2;
941 abuf[aind--] = (min % 10) + '0';
945 buf[ind++] = abuf[aind++];
949 /* Now add the seconds. */
950 aind = sizeof (abuf) - 2;
952 abuf[aind--] = (sec % 10) + '0';
956 buf[ind++] = abuf[aind++];
958 /* We want to add a decimal point and PREC places after it if PREC is
959 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
964 for (aind = 1; aind <= prec; aind++)
966 buf[ind++] = (sec_fraction / precs[aind]) + '0';
967 sec_fraction %= precs[aind];
978 /* Interpret the format string FORMAT, interpolating the following escape
982 where the optional `prec' is a precision, meaning the number of
983 characters after the decimal point, the optional `l' means to format
984 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
985 and the last character is one of
987 R number of seconds of `real' time
988 U number of seconds of `user' time
989 S number of seconds of `system' time
991 An occurrence of `%%' in the format string is translated to a `%'. The
992 result is printed to FP, a pointer to a FILE. The other variables are
993 the seconds and thousandths of a second of real, user, and system time,
996 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1007 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1012 len = strlen (format);
1013 ssize = (len + 64) - (len % 64);
1014 str = (char *)xmalloc (ssize);
1017 for (s = format; *s; s++)
1019 if (*s != '%' || s[1] == '\0')
1021 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1024 else if (s[1] == '%')
1027 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1030 else if (s[1] == 'P')
1036 sum_frac = (cpu % 100) * 10;
1037 len = mkfmt (ts, 2, 0, sum, sum_frac);
1038 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1039 strcpy (str + sindex, ts);
1044 prec = 3; /* default is three places past the decimal point. */
1045 lng = 0; /* default is to not use minutes or append `s' */
1047 if (DIGIT (*s)) /* `precision' */
1050 if (prec > 3) prec = 3;
1052 if (*s == 'l') /* `length extender' */
1057 if (*s == 'R' || *s == 'E')
1058 len = mkfmt (ts, prec, lng, rs, rsf);
1060 len = mkfmt (ts, prec, lng, us, usf);
1062 len = mkfmt (ts, prec, lng, ss, ssf);
1065 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1069 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1070 strcpy (str + sindex, ts);
1076 fprintf (fp, "%s\n", str);
1083 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1085 int asynchronous, pipe_in, pipe_out;
1086 struct fd_bitmap *fds_to_close;
1088 int rv, posix_time, old_flags;
1094 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1095 struct timeval real, user, sys;
1096 struct timeval before, after;
1097 # if defined (HAVE_STRUCT_TIMEZONE)
1098 struct timezone dtz; /* posix doesn't define this */
1100 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1102 # if defined (HAVE_TIMES)
1103 clock_t tbefore, tafter, real, user, sys;
1104 struct tms before, after;
1108 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1109 # if defined (HAVE_STRUCT_TIMEZONE)
1110 gettimeofday (&before, &dtz);
1112 gettimeofday (&before, (void *)NULL);
1113 # endif /* !HAVE_STRUCT_TIMEZONE */
1114 getrusage (RUSAGE_SELF, &selfb);
1115 getrusage (RUSAGE_CHILDREN, &kidsb);
1117 # if defined (HAVE_TIMES)
1118 tbefore = times (&before);
1122 posix_time = (command->flags & CMD_TIME_POSIX);
1124 old_flags = command->flags;
1125 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1126 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1127 command->flags = old_flags;
1130 rsf = usf = ssf = cpu = 0;
1132 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1133 # if defined (HAVE_STRUCT_TIMEZONE)
1134 gettimeofday (&after, &dtz);
1136 gettimeofday (&after, (void *)NULL);
1137 # endif /* !HAVE_STRUCT_TIMEZONE */
1138 getrusage (RUSAGE_SELF, &selfa);
1139 getrusage (RUSAGE_CHILDREN, &kidsa);
1141 difftimeval (&real, &before, &after);
1142 timeval_to_secs (&real, &rs, &rsf);
1144 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1145 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1146 timeval_to_secs (&user, &us, &usf);
1148 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1149 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1150 timeval_to_secs (&sys, &ss, &ssf);
1152 cpu = timeval_to_cpu (&real, &user, &sys);
1154 # if defined (HAVE_TIMES)
1155 tafter = times (&after);
1157 real = tafter - tbefore;
1158 clock_t_to_secs (real, &rs, &rsf);
1160 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1161 clock_t_to_secs (user, &us, &usf);
1163 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1164 clock_t_to_secs (sys, &ss, &ssf);
1166 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1170 rsf = usf = ssf = cpu = 0;
1175 time_format = POSIX_TIMEFORMAT;
1176 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1177 time_format = BASH_TIMEFORMAT;
1179 if (time_format && *time_format)
1180 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1184 #endif /* COMMAND_TIMING */
1186 /* Execute a command that's supposed to be in a subshell. This must be
1187 called after make_child and we must be running in the child process.
1188 The caller will return or exit() immediately with the value this returns. */
1190 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1193 int pipe_in, pipe_out;
1194 struct fd_bitmap *fds_to_close;
1196 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1200 USE_VAR(user_subshell);
1203 USE_VAR(asynchronous);
1206 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1207 pipe_in == NO_PIPE &&
1208 stdin_redirects (command->redirects) == 0);
1210 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1211 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1213 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1215 /* If a command is asynchronous in a subshell (like ( foo ) & or
1216 the special case of an asynchronous GROUP command where the
1217 the subshell bit is turned on down in case cm_group: below),
1218 turn off `asynchronous', so that two subshells aren't spawned.
1219 XXX - asynchronous used to be set to 0 in this block, but that
1220 means that setup_async_signals was never run. Now it's set to
1221 0 after subshell_environment is set appropriately and setup_async_signals
1224 This seems semantically correct to me. For example,
1225 ( foo ) & seems to say ``do the command `foo' in a subshell
1226 environment, but don't wait for that subshell to finish'',
1227 and "{ foo ; bar ; } &" seems to me to be like functions or
1228 builtins in the background, which executed in a subshell
1229 environment. I just don't see the need to fork two subshells. */
1231 /* Don't fork again, we are already in a subshell. A `doubly
1232 async' shell is not interactive, however. */
1235 #if defined (JOB_CONTROL)
1236 /* If a construct like ( exec xxx yyy ) & is given while job
1237 control is active, we want to prevent exec from putting the
1238 subshell back into the original process group, carefully
1239 undoing all the work we just did in make_child. */
1241 #endif /* JOB_CONTROL */
1242 ois = interactive_shell;
1243 interactive_shell = 0;
1244 /* This test is to prevent alias expansion by interactive shells that
1245 run `(command) &' but to allow scripts that have enabled alias
1246 expansion with `shopt -s expand_alias' to continue to expand
1248 if (ois != interactive_shell)
1252 /* Subshells are neither login nor interactive. */
1253 login_shell = interactive = 0;
1256 subshell_environment = SUBSHELL_PAREN;
1259 subshell_environment = 0; /* XXX */
1261 subshell_environment |= SUBSHELL_ASYNC;
1262 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1263 subshell_environment |= SUBSHELL_PIPE;
1266 reset_terminating_signals (); /* in sig.c */
1267 /* Cancel traps, in trap.c. */
1268 restore_original_signals ();
1270 /* Make sure restore_original_signals doesn't undo the work done by
1271 make_child to ensure that asynchronous children are immune to SIGINT
1272 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1276 setup_async_signals ();
1280 #if defined (JOB_CONTROL)
1281 set_sigchld_handler ();
1282 #endif /* JOB_CONTROL */
1284 set_sigint_handler ();
1286 #if defined (JOB_CONTROL)
1287 /* Delete all traces that there were any jobs running. This is
1288 only for subshells. */
1289 without_job_control ();
1290 #endif /* JOB_CONTROL */
1293 close_fd_bitmap (fds_to_close);
1295 do_piping (pipe_in, pipe_out);
1297 /* If this is a user subshell, set a flag if stdin was redirected.
1298 This is used later to decide whether to redirect fd 0 to
1299 /dev/null for async commands in the subshell. This adds more
1300 sh compatibility, but I'm not sure it's the right thing to do. */
1303 stdin_redir = stdin_redirects (command->redirects);
1304 restore_default_signal (0);
1307 /* If this is an asynchronous command (command &), we want to
1308 redirect the standard input from /dev/null in the absence of
1309 any specific redirection involving stdin. */
1310 if (should_redir_stdin && stdin_redir == 0)
1311 async_redirect_stdin ();
1313 /* Do redirections, then dispose of them before recursive call. */
1314 if (command->redirects)
1316 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1317 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1319 dispose_redirects (command->redirects);
1320 command->redirects = (REDIRECT *)NULL;
1323 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1325 if (command->flags & CMD_TIME_PIPELINE)
1326 tcom->flags |= CMD_TIME_PIPELINE;
1327 if (command->flags & CMD_TIME_POSIX)
1328 tcom->flags |= CMD_TIME_POSIX;
1330 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1331 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1332 tcom->flags |= CMD_IGNORE_RETURN;
1334 /* If this is a simple command, tell execute_disk_command that it
1335 might be able to get away without forking and simply exec.
1336 This means things like ( sleep 10 ) will only cause one fork.
1337 If we're timing the command or inverting its return value, however,
1338 we cannot do this optimization. */
1339 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1340 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1341 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1343 tcom->flags |= CMD_NO_FORK;
1344 if (tcom->type == cm_simple)
1345 tcom->value.Simple->flags |= CMD_NO_FORK;
1348 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1349 tcom->flags &= ~CMD_INVERT_RETURN;
1351 /* If we're inside a function while executing this subshell, we
1352 need to handle a possible `return'. */
1354 if (return_catch_flag)
1355 function_value = setjmp (return_catch);
1358 return_code = return_catch_value;
1360 return_code = execute_command_internal (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1362 /* If we are asked to, invert the return value. */
1364 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1365 : EXECUTION_SUCCESS;
1367 /* If we were explicitly placed in a subshell with (), we need
1368 to do the `shell cleanup' things, such as running traps[0]. */
1369 if (user_subshell && signal_is_trapped (0))
1371 last_command_exit_value = return_code;
1372 return_code = run_exit_trap ();
1376 return (return_code);
1381 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1383 int asynchronous, pipe_in, pipe_out;
1384 struct fd_bitmap *fds_to_close;
1386 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1388 struct fd_bitmap *fd_bitmap;
1390 #if defined (JOB_CONTROL)
1392 BLOCK_CHILD (set, oset);
1393 #endif /* JOB_CONTROL */
1395 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1400 while (cmd && cmd->type == cm_connection &&
1401 cmd->value.Connection && cmd->value.Connection->connector == '|')
1403 /* Make a pipeline between the two commands. */
1404 if (pipe (fildes) < 0)
1406 sys_error ("pipe error");
1407 #if defined (JOB_CONTROL)
1408 terminate_current_pipeline ();
1409 kill_current_pipeline ();
1410 UNBLOCK_CHILD (oset);
1411 #endif /* JOB_CONTROL */
1412 last_command_exit_value = EXECUTION_FAILURE;
1413 /* The unwind-protects installed below will take care
1414 of closing all of the open file descriptors. */
1415 throw_to_top_level ();
1416 return (EXECUTION_FAILURE); /* XXX */
1419 /* Here is a problem: with the new file close-on-exec
1420 code, the read end of the pipe (fildes[0]) stays open
1421 in the first process, so that process will never get a
1422 SIGPIPE. There is no way to signal the first process
1423 that it should close fildes[0] after forking, so it
1424 remains open. No SIGPIPE is ever sent because there
1425 is still a file descriptor open for reading connected
1426 to the pipe. We take care of that here. This passes
1427 around a bitmap of file descriptors that must be
1428 closed after making a child process in execute_simple_command. */
1430 /* We need fd_bitmap to be at least as big as fildes[0].
1431 If fildes[0] is less than fds_to_close->size, then
1432 use fds_to_close->size. */
1433 new_bitmap_size = (fildes[0] < fds_to_close->size)
1434 ? fds_to_close->size
1437 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1439 /* Now copy the old information into the new bitmap. */
1440 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1442 /* And mark the pipe file descriptors to be closed. */
1443 fd_bitmap->bitmap[fildes[0]] = 1;
1445 /* In case there are pipe or out-of-processes errors, we
1446 want all these file descriptors to be closed when
1447 unwind-protects are run, and the storage used for the
1448 bitmaps freed up. */
1449 begin_unwind_frame ("pipe-file-descriptors");
1450 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1451 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1453 add_unwind_protect (close, prev);
1454 dummyfd = fildes[1];
1455 add_unwind_protect (close, dummyfd);
1457 #if defined (JOB_CONTROL)
1458 add_unwind_protect (restore_signal_mask, &oset);
1459 #endif /* JOB_CONTROL */
1461 if (ignore_return && cmd->value.Connection->first)
1462 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1463 execute_command_internal (cmd->value.Connection->first, asynchronous,
1464 prev, fildes[1], fd_bitmap);
1472 dispose_fd_bitmap (fd_bitmap);
1473 discard_unwind_frame ("pipe-file-descriptors");
1475 cmd = cmd->value.Connection->second;
1478 /* Now execute the rightmost command in the pipeline. */
1479 if (ignore_return && cmd)
1480 cmd->flags |= CMD_IGNORE_RETURN;
1481 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1486 #if defined (JOB_CONTROL)
1487 UNBLOCK_CHILD (oset);
1490 return (exec_result);
1494 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1496 int asynchronous, pipe_in, pipe_out;
1497 struct fd_bitmap *fds_to_close;
1500 COMMAND *tc, *second;
1501 int ignore_return, exec_result;
1503 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1505 switch (command->value.Connection->connector)
1507 /* Do the first command asynchronously. */
1509 tc = command->value.Connection->first;
1511 return (EXECUTION_SUCCESS);
1516 tc->flags |= CMD_IGNORE_RETURN;
1517 tc->flags |= CMD_AMPERSAND;
1519 /* If this shell was compiled without job control support,
1520 if we are currently in a subshell via `( xxx )', or if job
1521 control is not active then the standard input for an
1522 asynchronous command is forced to /dev/null. */
1523 #if defined (JOB_CONTROL)
1524 if ((subshell_environment || !job_control) && !stdin_redir)
1527 #endif /* JOB_CONTROL */
1528 tc->flags |= CMD_STDIN_REDIR;
1530 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1532 if (tc->flags & CMD_STDIN_REDIR)
1533 tc->flags &= ~CMD_STDIN_REDIR;
1535 second = command->value.Connection->second;
1539 second->flags |= CMD_IGNORE_RETURN;
1541 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1546 /* Just call execute command on both sides. */
1550 if (command->value.Connection->first)
1551 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1552 if (command->value.Connection->second)
1553 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1556 execute_command (command->value.Connection->first);
1558 exec_result = execute_command_internal (command->value.Connection->second,
1559 asynchronous, pipe_in, pipe_out,
1564 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1571 /* If we have something like `a && b &' or `a || b &', run the
1572 && or || stuff in a subshell. Force a subshell and just call
1573 execute_command_internal again. Leave asynchronous on
1574 so that we get a report from the parent shell about the
1576 command->flags |= CMD_FORCE_SUBSHELL;
1577 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1581 /* Execute the first command. If the result of that is successful
1582 and the connector is AND_AND, or the result is not successful
1583 and the connector is OR_OR, then execute the second command,
1584 otherwise return. */
1586 if (command->value.Connection->first)
1587 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1589 exec_result = execute_command (command->value.Connection->first);
1591 if (((command->value.Connection->connector == AND_AND) &&
1592 (exec_result == EXECUTION_SUCCESS)) ||
1593 ((command->value.Connection->connector == OR_OR) &&
1594 (exec_result != EXECUTION_SUCCESS)))
1596 if (ignore_return && command->value.Connection->second)
1597 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1599 exec_result = execute_command (command->value.Connection->second);
1604 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1605 jump_to_top_level (DISCARD);
1606 exec_result = EXECUTION_FAILURE;
1615 if (!interactive_shell) \
1616 reap_dead_jobs (); \
1620 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1623 execute_for_command (for_command)
1624 FOR_COM *for_command;
1626 register WORD_LIST *releaser, *list;
1629 int retval, save_line_number;
1631 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1634 save_line_number = line_number;
1635 if (check_identifier (for_command->name, 1) == 0)
1637 if (posixly_correct && interactive_shell == 0)
1639 last_command_exit_value = EX_USAGE;
1640 jump_to_top_level (ERREXIT);
1642 return (EXECUTION_FAILURE);
1646 identifier = for_command->name->word;
1648 list = releaser = expand_words_no_vars (for_command->map_list);
1650 begin_unwind_frame ("for");
1651 add_unwind_protect (dispose_words, releaser);
1654 if (lexical_scoping)
1656 old_value = copy_variable (find_variable (identifier));
1658 add_unwind_protect (dispose_variable, old_value);
1662 if (for_command->flags & CMD_IGNORE_RETURN)
1663 for_command->action->flags |= CMD_IGNORE_RETURN;
1665 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1669 line_number = for_command->line;
1671 /* Remember what this command looks like, for debugger. */
1672 command_string_index = 0;
1673 print_for_command_head (for_command);
1675 if (echo_command_at_execute)
1676 xtrace_print_for_command_head (for_command);
1678 /* Save this command unless it's a trap command and we're not running
1681 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
1683 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
1686 FREE (the_printed_command_except_trap);
1687 the_printed_command_except_trap = savestring (the_printed_command);
1690 retval = run_debug_trap ();
1691 #if defined (DEBUGGER)
1692 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1693 skip the command. */
1694 if (debugging_mode && retval != EXECUTION_SUCCESS)
1698 this_command_name = (char *)NULL;
1699 v = bind_variable (identifier, list->word->word, 0);
1700 if (readonly_p (v) || noassign_p (v))
1702 line_number = save_line_number;
1703 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1705 last_command_exit_value = EXECUTION_FAILURE;
1706 jump_to_top_level (FORCE_EOF);
1710 dispose_words (releaser);
1711 discard_unwind_frame ("for");
1713 return (EXECUTION_FAILURE);
1716 retval = execute_command (for_command->action);
1735 line_number = save_line_number;
1738 if (lexical_scoping)
1741 unbind_variable (identifier);
1744 SHELL_VAR *new_value;
1746 new_value = bind_variable (identifier, value_cell(old_value), 0);
1747 new_value->attributes = old_value->attributes;
1748 dispose_variable (old_value);
1753 dispose_words (releaser);
1754 discard_unwind_frame ("for");
1758 #if defined (ARITH_FOR_COMMAND)
1759 /* Execute an arithmetic for command. The syntax is
1761 for (( init ; step ; test ))
1766 The execution should be exactly equivalent to
1769 while eval \(\( test \)\) ; do
1775 eval_arith_for_expr (l, okp)
1783 new = expand_words_no_vars (l);
1786 if (echo_command_at_execute)
1787 xtrace_print_arith_cmd (new);
1788 this_command_name = "(("; /* )) for expression error messages */
1790 command_string_index = 0;
1791 print_arith_command (new);
1792 if (signal_in_progress (DEBUG_TRAP) == 0)
1794 FREE (the_printed_command_except_trap);
1795 the_printed_command_except_trap = savestring (the_printed_command);
1798 r = run_debug_trap ();
1799 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1800 skip the command. */
1801 #if defined (DEBUGGER)
1802 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
1803 expresult = evalexp (new->word->word, okp);
1811 expresult = evalexp (new->word->word, okp);
1813 dispose_words (new);
1825 execute_arith_for_command (arith_for_command)
1826 ARITH_FOR_COM *arith_for_command;
1829 int expok, body_status, arith_lineno, save_lineno;
1831 body_status = EXECUTION_SUCCESS;
1833 save_lineno = line_number;
1835 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1836 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1838 this_command_name = "(("; /* )) for expression error messages */
1840 /* save the starting line number of the command so we can reset
1841 line_number before executing each expression -- for $LINENO
1842 and the DEBUG trap. */
1843 line_number = arith_lineno = arith_for_command->line;
1844 if (variable_context && interactive_shell)
1845 line_number -= function_line_number;
1847 /* Evaluate the initialization expression. */
1848 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1851 line_number = save_lineno;
1852 return (EXECUTION_FAILURE);
1857 /* Evaluate the test expression. */
1858 line_number = arith_lineno;
1859 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1860 line_number = save_lineno;
1864 body_status = EXECUTION_FAILURE;
1871 /* Execute the body of the arithmetic for command. */
1873 body_status = execute_command (arith_for_command->action);
1876 /* Handle any `break' or `continue' commands executed by the body. */
1890 /* Evaluate the step expression. */
1891 line_number = arith_lineno;
1892 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1893 line_number = save_lineno;
1897 body_status = EXECUTION_FAILURE;
1903 line_number = save_lineno;
1905 return (body_status);
1909 #if defined (SELECT_COMMAND)
1910 static int LINES, COLS, tabsize;
1912 #define RP_SPACE ") "
1913 #define RP_SPACE_LEN 2
1915 /* XXX - does not handle numbers > 1000000 at all. */
1916 #define NUMBER_LEN(s) \
1920 : ((s < 10000) ? 4 \
1921 : ((s < 100000) ? 5 \
1925 print_index_and_element (len, ind, list)
1929 register WORD_LIST *l;
1934 for (i = ind, l = list; l && --i; l = l->next)
1936 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1937 return (STRLEN (l->word->word));
1946 if ((to / tabsize) > (from / tabsize))
1948 putc ('\t', stderr);
1949 from += tabsize - from % tabsize;
1960 print_select_list (list, list_len, max_elem_len, indices_len)
1962 int list_len, max_elem_len, indices_len;
1964 int ind, row, elem_len, pos, cols, rows;
1965 int first_column_indices_len, other_indices_len;
1969 putc ('\n', stderr);
1973 cols = max_elem_len ? COLS / max_elem_len : 1;
1976 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1977 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1985 first_column_indices_len = NUMBER_LEN (rows);
1986 other_indices_len = indices_len;
1988 for (row = 0; row < rows; row++)
1994 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1995 elem_len = print_index_and_element (indices_len, ind + 1, list);
1996 elem_len += indices_len + RP_SPACE_LEN;
1998 if (ind >= list_len)
2000 indent (pos + elem_len, pos + max_elem_len);
2001 pos += max_elem_len;
2003 putc ('\n', stderr);
2007 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2008 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2009 If the number is between 1 and LIST_LEN, return that selection. If EOF
2010 is read, return a null string. If a blank line is entered, or an invalid
2011 number is entered, the loop is executed again. */
2013 select_query (list, list_len, prompt, print_menu)
2019 int max_elem_len, indices_len, len;
2022 char *repl_string, *t;
2024 t = get_string_value ("LINES");
2025 LINES = (t && *t) ? atoi (t) : 24;
2026 t = get_string_value ("COLUMNS");
2027 COLS = (t && *t) ? atoi (t) : 80;
2030 t = get_string_value ("TABSIZE");
2031 tabsize = (t && *t) ? atoi (t) : 8;
2039 for (l = list; l; l = l->next)
2041 len = STRLEN (l->word->word);
2042 if (len > max_elem_len)
2045 indices_len = NUMBER_LEN (list_len);
2046 max_elem_len += indices_len + RP_SPACE_LEN + 2;
2051 print_select_list (list, list_len, max_elem_len, indices_len);
2052 fprintf (stderr, "%s", prompt);
2056 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
2059 return ((char *)NULL);
2061 repl_string = get_string_value ("REPLY");
2062 if (*repl_string == 0)
2067 if (legal_number (repl_string, &reply) == 0)
2069 if (reply < 1 || reply > list_len)
2072 for (l = list; l && --reply; l = l->next)
2074 return (l->word->word);
2078 /* Execute a SELECT command. The syntax is:
2079 SELECT word IN list DO command_list DONE
2080 Only `break' or `return' in command_list will terminate
2083 execute_select_command (select_command)
2084 SELECT_COM *select_command;
2086 WORD_LIST *releaser, *list;
2088 char *identifier, *ps3_prompt, *selection;
2089 int retval, list_len, show_menu, save_line_number;
2091 if (check_identifier (select_command->name, 1) == 0)
2092 return (EXECUTION_FAILURE);
2094 save_line_number = line_number;
2095 line_number = select_command->line;
2097 command_string_index = 0;
2098 print_select_command_head (select_command);
2100 if (echo_command_at_execute)
2101 xtrace_print_select_command_head (select_command);
2104 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2106 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2109 FREE (the_printed_command_except_trap);
2110 the_printed_command_except_trap = savestring (the_printed_command);
2113 retval = run_debug_trap ();
2114 #if defined (DEBUGGER)
2115 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2116 skip the command. */
2117 if (debugging_mode && retval != EXECUTION_SUCCESS)
2118 return (EXECUTION_SUCCESS);
2122 identifier = select_command->name->word;
2124 /* command and arithmetic substitution, parameter and variable expansion,
2125 word splitting, pathname expansion, and quote removal. */
2126 list = releaser = expand_words_no_vars (select_command->map_list);
2127 list_len = list_length (list);
2128 if (list == 0 || list_len == 0)
2131 dispose_words (list);
2132 line_number = save_line_number;
2133 return (EXECUTION_SUCCESS);
2136 begin_unwind_frame ("select");
2137 add_unwind_protect (dispose_words, releaser);
2139 if (select_command->flags & CMD_IGNORE_RETURN)
2140 select_command->action->flags |= CMD_IGNORE_RETURN;
2142 retval = EXECUTION_SUCCESS;
2147 line_number = select_command->line;
2148 ps3_prompt = get_string_value ("PS3");
2149 if (ps3_prompt == 0)
2153 selection = select_query (list, list_len, ps3_prompt, show_menu);
2157 /* select_query returns EXECUTION_FAILURE if the read builtin
2158 fails, so we want to return failure in this case. */
2159 retval = EXECUTION_FAILURE;
2163 v = bind_variable (identifier, selection, 0);
2164 if (readonly_p (v) || noassign_p (v))
2166 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2168 last_command_exit_value = EXECUTION_FAILURE;
2169 jump_to_top_level (FORCE_EOF);
2173 dispose_words (releaser);
2174 discard_unwind_frame ("select");
2176 line_number = save_line_number;
2177 return (EXECUTION_FAILURE);
2181 retval = execute_command (select_command->action);
2199 #if defined (KSH_COMPATIBLE_SELECT)
2201 selection = get_string_value ("REPLY");
2202 if (selection && *selection == '\0')
2208 line_number = save_line_number;
2210 dispose_words (releaser);
2211 discard_unwind_frame ("select");
2214 #endif /* SELECT_COMMAND */
2216 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2217 The pattern_list is a linked list of pattern clauses; each clause contains
2218 some patterns to compare word_desc against, and an associated command to
2221 execute_case_command (case_command)
2222 CASE_COM *case_command;
2224 register WORD_LIST *list;
2225 WORD_LIST *wlist, *es;
2226 PATTERN_LIST *clauses;
2227 char *word, *pattern;
2228 int retval, match, ignore_return, save_line_number;
2230 save_line_number = line_number;
2231 line_number = case_command->line;
2233 command_string_index = 0;
2234 print_case_command_head (case_command);
2236 if (echo_command_at_execute)
2237 xtrace_print_case_command_head (case_command);
2240 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2242 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2245 FREE (the_printed_command_except_trap);
2246 the_printed_command_except_trap = savestring (the_printed_command);
2249 retval = run_debug_trap();
2250 #if defined (DEBUGGER)
2251 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2252 skip the command. */
2253 if (debugging_mode && retval != EXECUTION_SUCCESS)
2255 line_number = save_line_number;
2256 return (EXECUTION_SUCCESS);
2260 wlist = expand_word_unsplit (case_command->word, 0);
2261 word = wlist ? string_list (wlist) : savestring ("");
2262 dispose_words (wlist);
2264 retval = EXECUTION_SUCCESS;
2265 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2267 begin_unwind_frame ("case");
2268 add_unwind_protect ((Function *)xfree, word);
2270 #define EXIT_CASE() goto exit_case_command
2272 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2275 for (list = clauses->patterns; list; list = list->next)
2277 es = expand_word_leave_quoted (list->word, 0);
2279 if (es && es->word && es->word->word && *(es->word->word))
2280 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2283 pattern = (char *)xmalloc (1);
2287 /* Since the pattern does not undergo quote removal (as per
2288 Posix.2, section 3.9.4.3), the strmatch () call must be able
2289 to recognize backslashes as escape characters. */
2290 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
2297 if (clauses->action && ignore_return)
2298 clauses->action->flags |= CMD_IGNORE_RETURN;
2299 retval = execute_command (clauses->action);
2309 discard_unwind_frame ("case");
2310 line_number = save_line_number;
2317 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2318 Repeatedly execute action while executing test produces
2319 EXECUTION_SUCCESS. */
2321 execute_while_command (while_command)
2322 WHILE_COM *while_command;
2324 return (execute_while_or_until (while_command, CMD_WHILE));
2327 /* UNTIL is just like WHILE except that the test result is negated. */
2329 execute_until_command (while_command)
2330 WHILE_COM *while_command;
2332 return (execute_while_or_until (while_command, CMD_UNTIL));
2335 /* The body for both while and until. The only difference between the
2336 two is that the test value is treated differently. TYPE is
2337 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2338 be EXECUTION_SUCCESS if no commands in the body are executed, and
2339 the status of the last command executed in the body otherwise. */
2341 execute_while_or_until (while_command, type)
2342 WHILE_COM *while_command;
2345 int return_value, body_status;
2347 body_status = EXECUTION_SUCCESS;
2350 while_command->test->flags |= CMD_IGNORE_RETURN;
2351 if (while_command->flags & CMD_IGNORE_RETURN)
2352 while_command->action->flags |= CMD_IGNORE_RETURN;
2356 return_value = execute_command (while_command->test);
2359 /* Need to handle `break' in the test when we would break out of the
2360 loop. The job control code will set `breaking' to loop_level
2361 when a job in a loop is stopped with SIGTSTP. If the stopped job
2362 is in the loop test, `breaking' will not be reset unless we do
2363 this, and the shell will cease to execute commands. */
2364 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2370 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2378 body_status = execute_command (while_command->action);
2396 return (body_status);
2399 /* IF test THEN command [ELSE command].
2400 IF also allows ELIF in the place of ELSE IF, but
2401 the parser makes *that* stupidity transparent. */
2403 execute_if_command (if_command)
2406 int return_value, save_line_number;
2408 save_line_number = line_number;
2409 if_command->test->flags |= CMD_IGNORE_RETURN;
2410 return_value = execute_command (if_command->test);
2411 line_number = save_line_number;
2413 if (return_value == EXECUTION_SUCCESS)
2417 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2418 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2420 return (execute_command (if_command->true_case));
2426 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2427 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2429 return (execute_command (if_command->false_case));
2433 #if defined (DPAREN_ARITHMETIC)
2435 execute_arith_command (arith_command)
2436 ARITH_COM *arith_command;
2438 int expok, save_line_number, retval;
2445 save_line_number = line_number;
2446 this_command_name = "(("; /* )) */
2447 line_number = arith_command->line;
2448 /* If we're in a function, update the line number information. */
2449 if (variable_context && interactive_shell)
2450 line_number -= function_line_number;
2452 command_string_index = 0;
2453 print_arith_command (arith_command->exp);
2455 if (signal_in_progress (DEBUG_TRAP) == 0)
2457 FREE (the_printed_command_except_trap);
2458 the_printed_command_except_trap = savestring (the_printed_command);
2461 /* Run the debug trap before each arithmetic command, but do it after we
2462 update the line number information and before we expand the various
2463 words in the expression. */
2464 retval = run_debug_trap ();
2465 #if defined (DEBUGGER)
2466 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2467 skip the command. */
2468 if (debugging_mode && retval != EXECUTION_SUCCESS)
2470 line_number = save_line_number;
2471 return (EXECUTION_SUCCESS);
2475 new = expand_words_no_vars (arith_command->exp);
2477 /* If we're tracing, make a new word list with `((' at the front and `))'
2478 at the back and print it. */
2479 if (echo_command_at_execute)
2480 xtrace_print_arith_cmd (new);
2484 exp = new->next ? string_list (new) : new->word->word;
2485 expresult = evalexp (exp, &expok);
2486 line_number = save_line_number;
2487 if (exp != new->word->word)
2489 dispose_words (new);
2498 return (EXECUTION_FAILURE);
2500 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2502 #endif /* DPAREN_ARITHMETIC */
2504 #if defined (COND_COMMAND)
2506 static char *nullstr = "";
2509 execute_cond_node (cond)
2512 int result, invert, patmatch, rmatch, mflags;
2515 invert = (cond->flags & CMD_INVERT_RETURN);
2517 if (cond->type == COND_EXPR)
2518 result = execute_cond_node (cond->left);
2519 else if (cond->type == COND_OR)
2521 result = execute_cond_node (cond->left);
2522 if (result != EXECUTION_SUCCESS)
2523 result = execute_cond_node (cond->right);
2525 else if (cond->type == COND_AND)
2527 result = execute_cond_node (cond->left);
2528 if (result == EXECUTION_SUCCESS)
2529 result = execute_cond_node (cond->right);
2531 else if (cond->type == COND_UNARY)
2533 arg1 = cond_expand_word (cond->left->op, 0);
2536 if (echo_command_at_execute)
2537 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2538 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2539 if (arg1 != nullstr)
2542 else if (cond->type == COND_BINARY)
2545 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2546 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2547 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2548 #if defined (COND_REGEXP)
2549 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
2550 cond->op->word[2] == '\0');
2553 arg1 = cond_expand_word (cond->left->op, 0);
2556 arg2 = cond_expand_word (cond->right->op,
2557 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
2561 if (echo_command_at_execute)
2562 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2564 #if defined (COND_REGEXP)
2567 mflags = SHMAT_PWARN;
2568 #if defined (ARRAY_VARS)
2569 mflags |= SHMAT_SUBEXP;
2572 result = sh_regmatch (arg1, arg2, mflags);
2575 #endif /* COND_REGEXP */
2580 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2582 : EXECUTION_FAILURE;
2585 if (arg1 != nullstr)
2587 if (arg2 != nullstr)
2592 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2593 jump_to_top_level (DISCARD);
2594 result = EXECUTION_FAILURE;
2598 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2604 execute_cond_command (cond_command)
2605 COND_COM *cond_command;
2607 int retval, save_line_number;
2609 retval = EXECUTION_SUCCESS;
2610 save_line_number = line_number;
2612 this_command_name = "[[";
2613 line_number = cond_command->line;
2614 /* If we're in a function, update the line number information. */
2615 if (variable_context && interactive_shell)
2616 line_number -= function_line_number;
2618 command_string_index = 0;
2619 print_cond_command (cond_command);
2621 if (signal_in_progress (DEBUG_TRAP) == 0)
2623 FREE (the_printed_command_except_trap);
2624 the_printed_command_except_trap = savestring (the_printed_command);
2627 /* Run the debug trap before each conditional command, but do it after we
2628 update the line number information. */
2629 retval = run_debug_trap ();
2630 #if defined (DEBUGGER)
2631 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2632 skip the command. */
2633 if (debugging_mode && retval != EXECUTION_SUCCESS)
2635 line_number = save_line_number;
2636 return (EXECUTION_SUCCESS);
2641 debug_print_cond_command (cond_command);
2644 last_command_exit_value = retval = execute_cond_node (cond_command);
2645 line_number = save_line_number;
2648 #endif /* COND_COMMAND */
2658 var = bind_variable ("_", arg, 0);
2659 VUNSETATTR (var, att_exported);
2662 /* Execute a null command. Fork a subshell if the command uses pipes or is
2663 to be run asynchronously. This handles all the side effects that are
2664 supposed to take place. */
2666 execute_null_command (redirects, pipe_in, pipe_out, async)
2667 REDIRECT *redirects;
2668 int pipe_in, pipe_out, async;
2672 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2674 /* We have a null command, but we really want a subshell to take
2675 care of it. Just fork, do piping and redirections, and exit. */
2676 if (make_child ((char *)NULL, async) == 0)
2678 /* Cancel traps, in trap.c. */
2679 restore_original_signals (); /* XXX */
2681 do_piping (pipe_in, pipe_out);
2684 subshell_environment |= SUBSHELL_ASYNC;
2685 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2686 subshell_environment |= SUBSHELL_PIPE;
2688 if (do_redirections (redirects, RX_ACTIVE) == 0)
2689 exit (EXECUTION_SUCCESS);
2691 exit (EXECUTION_FAILURE);
2695 close_pipes (pipe_in, pipe_out);
2696 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2697 unlink_fifo_list ();
2699 return (EXECUTION_SUCCESS);
2704 /* Even if there aren't any command names, pretend to do the
2705 redirections that are specified. The user expects the side
2706 effects to take place. If the redirections fail, then return
2707 failure. Otherwise, if a command substitution took place while
2708 expanding the command or a redirection, return the value of that
2709 substitution. Otherwise, return EXECUTION_SUCCESS. */
2711 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
2712 cleanup_redirects (redirection_undo_list);
2713 redirection_undo_list = (REDIRECT *)NULL;
2716 return (EXECUTION_FAILURE);
2717 else if (last_command_subst_pid != NO_PID)
2718 return (last_command_exit_value);
2720 return (EXECUTION_SUCCESS);
2724 /* This is a hack to suppress word splitting for assignment statements
2725 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2727 fix_assignment_words (words)
2738 for (w = words; w; w = w->next)
2739 if (w->word->flags & W_ASSIGNMENT)
2743 b = builtin_address_internal (words->word->word, 0);
2744 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2746 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
2747 words->word->flags |= W_ASSNBLTIN;
2749 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
2753 /* The meaty part of all the executions. We have to start hacking the
2754 real execution of commands here. Fork a process, set things up,
2755 execute the command. */
2757 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2758 SIMPLE_COM *simple_command;
2759 int pipe_in, pipe_out, async;
2760 struct fd_bitmap *fds_to_close;
2762 WORD_LIST *words, *lastword;
2763 char *command_line, *lastarg, *temp;
2764 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2765 pid_t old_last_async_pid;
2766 sh_builtin_func_t *builtin;
2769 result = EXECUTION_SUCCESS;
2770 special_builtin_failed = builtin_is_special = 0;
2771 command_line = (char *)0;
2773 /* If we're in a function, update the line number information. */
2774 if (variable_context && interactive_shell)
2775 line_number -= function_line_number;
2777 /* Remember what this command line looks like at invocation. */
2778 command_string_index = 0;
2779 print_simple_command (simple_command);
2782 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2784 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2787 FREE (the_printed_command_except_trap);
2788 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
2791 /* Run the debug trap before each simple command, but do it after we
2792 update the line number information. */
2793 result = run_debug_trap ();
2794 #if defined (DEBUGGER)
2795 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2796 skip the command. */
2797 if (debugging_mode && result != EXECUTION_SUCCESS)
2798 return (EXECUTION_SUCCESS);
2802 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2804 last_command_subst_pid = NO_PID;
2805 old_last_async_pid = last_asynchronous_pid;
2807 already_forked = dofork = 0;
2809 /* If we're in a pipeline or run in the background, set DOFORK so we
2810 make the child early, before word expansion. This keeps assignment
2811 statements from affecting the parent shell's environment when they
2813 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2815 /* Something like `%2 &' should restart job 2 in the background, not cause
2816 the shell to fork here. */
2817 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2818 simple_command->words && simple_command->words->word &&
2819 simple_command->words->word->word &&
2820 (simple_command->words->word->word[0] == '%'))
2825 /* Do this now, because execute_disk_command will do it anyway in the
2826 vast majority of cases. */
2827 maybe_make_export_env ();
2829 /* Don't let a DEBUG trap overwrite the command string to be saved with
2830 the process/job associated with this child. */
2831 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
2834 simple_command->flags |= CMD_NO_FORK;
2836 subshell_environment = SUBSHELL_FORK;
2837 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2838 subshell_environment |= SUBSHELL_PIPE;
2840 subshell_environment |= SUBSHELL_ASYNC;
2842 /* We need to do this before piping to handle some really
2843 pathological cases where one of the pipe file descriptors
2846 close_fd_bitmap (fds_to_close);
2848 do_piping (pipe_in, pipe_out);
2849 pipe_in = pipe_out = NO_PIPE;
2851 last_asynchronous_pid = old_last_async_pid;
2855 close_pipes (pipe_in, pipe_out);
2856 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2857 unlink_fifo_list ();
2859 command_line = (char *)NULL; /* don't free this. */
2860 bind_lastarg ((char *)NULL);
2865 /* If we are re-running this as the result of executing the `command'
2866 builtin, do not expand the command words a second time. */
2867 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2869 current_fds_to_close = fds_to_close;
2870 fix_assignment_words (simple_command->words);
2871 words = expand_words (simple_command->words);
2872 current_fds_to_close = (struct fd_bitmap *)NULL;
2875 words = copy_word_list (simple_command->words);
2877 /* It is possible for WORDS not to have anything left in it.
2878 Perhaps all the words consisted of `$foo', and there was
2879 no variable `$foo'. */
2882 this_command_name = 0;
2883 result = execute_null_command (simple_command->redirects,
2885 already_forked ? 0 : async);
2890 bind_lastarg ((char *)NULL);
2891 set_pipestatus_from_exit (result);
2896 lastarg = (char *)NULL;
2898 begin_unwind_frame ("simple-command");
2900 if (echo_command_at_execute)
2901 xtrace_print_word_list (words, 1);
2903 builtin = (sh_builtin_func_t *)NULL;
2904 func = (SHELL_VAR *)NULL;
2905 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2907 /* Posix.2 says special builtins are found before functions. We
2908 don't set builtin_is_special anywhere other than here, because
2909 this path is followed only when the `command' builtin is *not*
2910 being used, and we don't want to exit the shell if a special
2911 builtin executed with `command builtin' fails. `command' is not
2912 a special builtin. */
2913 if (posixly_correct)
2915 builtin = find_special_builtin (words->word->word);
2917 builtin_is_special = 1;
2920 func = find_function (words->word->word);
2923 /* In POSIX mode, assignment errors in the temporary environment cause a
2924 non-interactive shell to exit. */
2925 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
2927 last_command_exit_value = EXECUTION_FAILURE;
2928 jump_to_top_level (ERREXIT);
2931 add_unwind_protect (dispose_words, words);
2934 /* Bind the last word in this command to "$_" after execution. */
2935 for (lastword = words; lastword->next; lastword = lastword->next)
2937 lastarg = lastword->word->word;
2939 #if defined (JOB_CONTROL)
2940 /* Is this command a job control related thing? */
2941 if (words->word->word[0] == '%' && already_forked == 0)
2943 this_command_name = async ? "bg" : "fg";
2944 last_shell_builtin = this_shell_builtin;
2945 this_shell_builtin = builtin_address (this_command_name);
2946 result = (*this_shell_builtin) (words);
2950 /* One other possiblilty. The user may want to resume an existing job.
2951 If they do, find out whether this word is a candidate for a running
2953 if (job_control && already_forked == 0 && async == 0 &&
2954 !first_word_quoted &&
2956 words->word->word[0] &&
2957 !simple_command->redirects &&
2958 pipe_in == NO_PIPE &&
2959 pipe_out == NO_PIPE &&
2960 (temp = get_string_value ("auto_resume")))
2962 int job, jflags, started_status;
2964 jflags = JM_STOPPED|JM_FIRSTMATCH;
2965 if (STREQ (temp, "exact"))
2967 else if (STREQ (temp, "substring"))
2968 jflags |= JM_SUBSTRING;
2970 jflags |= JM_PREFIX;
2971 job = get_job_by_name (words->word->word, jflags);
2974 run_unwind_frame ("simple-command");
2975 this_command_name = "fg";
2976 last_shell_builtin = this_shell_builtin;
2977 this_shell_builtin = builtin_address ("fg");
2979 started_status = start_job (job, 1);
2980 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2983 #endif /* JOB_CONTROL */
2985 /* Remember the name of this command globally. */
2986 this_command_name = words->word->word;
2990 /* This command could be a shell builtin or a user-defined function.
2991 We have already found special builtins by this time, so we do not
2992 set builtin_is_special. If this is a function or builtin, and we
2993 have pipes, then fork a subshell in here. Otherwise, just execute
2994 the command directly. */
2995 if (func == 0 && builtin == 0)
2996 builtin = find_shell_builtin (this_command_name);
2998 last_shell_builtin = this_shell_builtin;
2999 this_shell_builtin = builtin;
3001 if (builtin || func)
3005 /* reset_terminating_signals (); */ /* XXX */
3006 /* Cancel traps, in trap.c. */
3007 restore_original_signals ();
3011 if ((simple_command->flags & CMD_STDIN_REDIR) &&
3012 pipe_in == NO_PIPE &&
3013 (stdin_redirects (simple_command->redirects) == 0))
3014 async_redirect_stdin ();
3015 setup_async_signals ();
3019 execute_subshell_builtin_or_function
3020 (words, simple_command->redirects, builtin, func,
3021 pipe_in, pipe_out, async, fds_to_close,
3022 simple_command->flags);
3027 result = execute_builtin_or_function
3028 (words, builtin, func, simple_command->redirects, fds_to_close,
3029 simple_command->flags);
3032 if (result > EX_SHERRBASE)
3034 result = builtin_status (result);
3035 if (builtin_is_special)
3036 special_builtin_failed = 1;
3038 /* In POSIX mode, if there are assignment statements preceding
3039 a special builtin, they persist after the builtin
3041 if (posixly_correct && builtin_is_special && temporary_env)
3042 merge_temporary_env ();
3046 if (result == EX_USAGE)
3047 result = EX_BADUSAGE;
3048 else if (result > EX_SHERRBASE)
3049 result = EXECUTION_FAILURE;
3052 set_pipestatus_from_exit (result);
3058 if (command_line == 0)
3059 command_line = savestring (the_printed_command_except_trap);
3061 #if defined (PROCESS_SUBSTITUTION)
3062 if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
3063 simple_command->flags &= ~CMD_NO_FORK;
3066 execute_disk_command (words, simple_command->redirects, command_line,
3067 pipe_in, pipe_out, async, fds_to_close,
3068 simple_command->flags);
3071 bind_lastarg (lastarg);
3072 FREE (command_line);
3073 dispose_words (words);
3074 discard_unwind_frame ("simple-command");
3075 this_command_name = (char *)NULL; /* points to freed memory now */
3079 /* Translate the special builtin exit statuses. We don't really need a
3080 function for this; it's a placeholder for future work. */
3082 builtin_status (result)
3096 r = EXECUTION_FAILURE;
3099 r = EXECUTION_SUCCESS;
3106 execute_builtin (builtin, words, flags, subshell)
3107 sh_builtin_func_t *builtin;
3109 int flags, subshell;
3111 int old_e_flag, result, eval_unwind;
3114 old_e_flag = exit_immediately_on_error;
3115 /* The eval builtin calls parse_and_execute, which does not know about
3116 the setting of flags, and always calls the execution functions with
3117 flags that will exit the shell on an error if -e is set. If the
3118 eval builtin is being called, and we're supposed to ignore the exit
3119 value of the command, we turn the -e flag off ourselves, then
3120 restore it when the command completes. */
3121 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
3123 begin_unwind_frame ("eval_builtin");
3124 unwind_protect_int (exit_immediately_on_error);
3125 exit_immediately_on_error = 0;
3131 /* The temporary environment for a builtin is supposed to apply to
3132 all commands executed by that builtin. Currently, this is a
3133 problem only with the `unset', `source' and `eval' builtins. */
3135 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
3140 begin_unwind_frame ("builtin_env");
3144 push_scope (VC_BLTNENV, temporary_env);
3146 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
3147 temporary_env = (HASH_TABLE *)NULL;
3151 /* `return' does a longjmp() back to a saved environment in execute_function.
3152 If a variable assignment list preceded the command, and the shell is
3153 running in POSIX mode, we need to merge that into the shell_variables
3154 table, since `return' is a POSIX special builtin. */
3155 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3157 begin_unwind_frame ("return_temp_env");
3158 add_unwind_protect (merge_temporary_env, (char *)NULL);
3161 result = ((*builtin) (words->next));
3163 /* This shouldn't happen, but in case `return' comes back instead of
3164 longjmp'ing, we need to unwind. */
3165 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3166 discard_unwind_frame ("return_temp_env");
3168 if (subshell == 0 && isbltinenv)
3169 run_unwind_frame ("builtin_env");
3173 exit_immediately_on_error += old_e_flag;
3174 discard_unwind_frame ("eval_builtin");
3181 execute_function (var, words, flags, fds_to_close, async, subshell)
3185 struct fd_bitmap *fds_to_close;
3186 int async, subshell;
3188 int return_val, result;
3189 COMMAND *tc, *fc, *save_current;
3190 char *debug_trap, *error_trap, *return_trap;
3191 #if defined (ARRAY_VARS)
3192 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
3193 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
3195 FUNCTION_DEF *shell_fn;
3197 static int funcnest = 0;
3201 #if defined (ARRAY_VARS)
3202 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
3203 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
3204 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
3207 tc = (COMMAND *)copy_command (function_cell (var));
3208 if (tc && (flags & CMD_IGNORE_RETURN))
3209 tc->flags |= CMD_IGNORE_RETURN;
3213 begin_unwind_frame ("function_calling");
3214 push_context (var->name, subshell, temporary_env);
3215 add_unwind_protect (pop_context, (char *)NULL);
3216 unwind_protect_int (line_number);
3217 unwind_protect_int (return_catch_flag);
3218 unwind_protect_jmp_buf (return_catch);
3219 add_unwind_protect (dispose_command, (char *)tc);
3220 unwind_protect_pointer (this_shell_function);
3221 unwind_protect_int (loop_level);
3224 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
3226 temporary_env = (HASH_TABLE *)NULL;
3228 this_shell_function = var;
3229 make_funcname_visible (1);
3231 debug_trap = TRAP_STRING(DEBUG_TRAP);
3232 error_trap = TRAP_STRING(ERROR_TRAP);
3233 return_trap = TRAP_STRING(RETURN_TRAP);
3235 /* The order of the unwind protects for debug_trap, error_trap and
3236 return_trap is important here! unwind-protect commands are run
3237 in reverse order of registration. If this causes problems, take
3238 out the xfree unwind-protect calls and live with the small memory leak. */
3240 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3241 if the function has the trace attribute set, it inherits the DEBUG trap */
3242 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3246 debug_trap = savestring (debug_trap);
3247 add_unwind_protect (xfree, debug_trap);
3248 add_unwind_protect (set_debug_trap, debug_trap);
3250 restore_default_signal (DEBUG_TRAP);
3253 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3254 if (error_trap && error_trace_mode == 0)
3258 error_trap = savestring (error_trap);
3259 add_unwind_protect (xfree, error_trap);
3260 add_unwind_protect (set_error_trap, error_trap);
3262 restore_default_signal (ERROR_TRAP);
3265 /* Shell functions inherit the RETURN trap if function tracing is on
3266 globally or on individually for this function. */
3268 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3270 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
3275 return_trap = savestring (return_trap);
3276 add_unwind_protect (xfree, return_trap);
3277 add_unwind_protect (set_return_trap, return_trap);
3279 restore_default_signal (RETURN_TRAP);
3283 #if defined (ARRAY_VARS)
3284 /* This is quite similar to the code in shell.c and elsewhere. */
3285 shell_fn = find_function_def (this_shell_function->name);
3286 sfile = shell_fn ? shell_fn->source_file : "";
3287 array_push (funcname_a, this_shell_function->name);
3289 array_push (bash_source_a, sfile);
3290 t = itos (executing_line_number ());
3291 array_push (bash_lineno_a, t);
3295 /* The temporary environment for a function is supposed to apply to
3296 all commands executed within the function body. */
3298 remember_args (words->next, 1);
3300 /* Update BASH_ARGV and BASH_ARGC */
3302 push_args (words->next);
3304 /* Number of the line on which the function body starts. */
3305 line_number = function_line_number = tc->line;
3307 #if defined (JOB_CONTROL)
3309 stop_pipeline (async, (COMMAND *)NULL);
3314 return_catch_flag++;
3315 return_val = setjmp (return_catch);
3319 result = return_catch_value;
3320 /* Run the RETURN trap in the function's context. */
3321 save_current = currently_executing_command;
3323 currently_executing_command = save_current;
3327 /* Run the debug trap here so we can trap at the start of a function's
3328 execution rather than the execution of the body's first command. */
3329 showing_function_line = 1;
3330 save_current = currently_executing_command;
3331 result = run_debug_trap ();
3332 #if defined (DEBUGGER)
3333 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3334 skip the command. */
3335 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
3337 showing_function_line = 0;
3338 currently_executing_command = save_current;
3339 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3341 /* Run the RETURN trap in the function's context */
3342 save_current = currently_executing_command;
3344 currently_executing_command = save_current;
3347 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3349 save_current = currently_executing_command;
3351 currently_executing_command = save_current;
3353 showing_function_line = 0;
3356 /* Restore BASH_ARGC and BASH_ARGV */
3361 run_unwind_frame ("function_calling");
3364 #if defined (ARRAY_VARS)
3365 /* These two variables cannot be unset, and cannot be affected by the
3367 array_pop (bash_source_a);
3368 array_pop (bash_lineno_a);
3370 /* FUNCNAME can be unset, and so can potentially be changed by the
3372 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
3373 if (nfv == funcname_v)
3374 array_pop (funcname_a);
3377 if (variable_context == 0 || this_shell_function == 0)
3378 make_funcname_visible (0);
3383 /* A convenience routine for use by other parts of the shell to execute
3384 a particular shell function. */
3386 execute_shell_function (var, words)
3391 struct fd_bitmap *bitmap;
3393 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
3394 begin_unwind_frame ("execute-shell-function");
3395 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
3397 ret = execute_function (var, words, 0, bitmap, 0, 0);
3399 dispose_fd_bitmap (bitmap);
3400 discard_unwind_frame ("execute-shell-function");
3405 /* Execute a shell builtin or function in a subshell environment. This
3406 routine does not return; it only calls exit(). If BUILTIN is non-null,
3407 it points to a function to call to execute a shell builtin; otherwise
3408 VAR points at the body of a function to execute. WORDS is the arguments
3409 to the command, REDIRECTS specifies redirections to perform before the
3410 command is executed. */
3412 execute_subshell_builtin_or_function (words, redirects, builtin, var,
3413 pipe_in, pipe_out, async, fds_to_close,
3416 REDIRECT *redirects;
3417 sh_builtin_func_t *builtin;
3419 int pipe_in, pipe_out, async;
3420 struct fd_bitmap *fds_to_close;
3423 int result, r, funcvalue;
3424 #if defined (JOB_CONTROL)
3427 jobs_hack = (builtin == jobs_builtin) &&
3428 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
3431 /* A subshell is neither a login shell nor interactive. */
3432 login_shell = interactive = 0;
3435 subshell_environment |= SUBSHELL_ASYNC;
3436 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3437 subshell_environment |= SUBSHELL_PIPE;
3439 maybe_make_export_env (); /* XXX - is this needed? */
3441 #if defined (JOB_CONTROL)
3442 /* Eradicate all traces of job control after we fork the subshell, so
3443 all jobs begun by this subshell are in the same process group as
3444 the shell itself. */
3446 /* Allow the output of `jobs' to be piped. */
3448 kill_current_pipeline ();
3450 without_job_control ();
3452 set_sigchld_handler ();
3453 #endif /* JOB_CONTROL */
3455 set_sigint_handler ();
3458 close_fd_bitmap (fds_to_close);
3460 do_piping (pipe_in, pipe_out);
3462 if (do_redirections (redirects, RX_ACTIVE) != 0)
3463 exit (EXECUTION_FAILURE);
3467 /* Give builtins a place to jump back to on failure,
3468 so we don't go back up to main(). */
3469 result = setjmp (top_level);
3471 /* Give the return builtin a place to jump to when executed in a subshell
3474 if (return_catch_flag && builtin == return_builtin)
3475 funcvalue = setjmp (return_catch);
3477 if (result == EXITPROG)
3478 exit (last_command_exit_value);
3480 exit (EXECUTION_FAILURE);
3482 exit (return_catch_value);
3485 r = execute_builtin (builtin, words, flags, 1);
3492 exit (execute_function (var, words, flags, fds_to_close, async, 1));
3495 /* Execute a builtin or function in the current shell context. If BUILTIN
3496 is non-null, it is the builtin command to execute, otherwise VAR points
3497 to the body of a function. WORDS are the command's arguments, REDIRECTS
3498 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3499 file descriptors to close.
3501 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3502 not undone before this function returns. */
3504 execute_builtin_or_function (words, builtin, var, redirects,
3505 fds_to_close, flags)
3507 sh_builtin_func_t *builtin;
3509 REDIRECT *redirects;
3510 struct fd_bitmap *fds_to_close;
3514 REDIRECT *saved_undo_list;
3515 sh_builtin_func_t *saved_this_shell_builtin;
3517 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
3519 cleanup_redirects (redirection_undo_list);
3520 redirection_undo_list = (REDIRECT *)NULL;
3521 dispose_exec_redirects ();
3522 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3525 saved_this_shell_builtin = this_shell_builtin;
3526 saved_undo_list = redirection_undo_list;
3528 /* Calling the "exec" builtin changes redirections forever. */
3529 if (builtin == exec_builtin)
3531 dispose_redirects (saved_undo_list);
3532 saved_undo_list = exec_redirection_undo_list;
3533 exec_redirection_undo_list = (REDIRECT *)NULL;
3536 dispose_exec_redirects ();
3538 if (saved_undo_list)
3540 begin_unwind_frame ("saved redirects");
3541 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3544 redirection_undo_list = (REDIRECT *)NULL;
3547 result = execute_builtin (builtin, words, flags, 0);
3549 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3551 /* We do this before undoing the effects of any redirections. */
3552 if (ferror (stdout))
3555 /* If we are executing the `command' builtin, but this_shell_builtin is
3556 set to `exec_builtin', we know that we have something like
3557 `command exec [redirection]', since otherwise `exec' would have
3558 overwritten the shell and we wouldn't get here. In this case, we
3559 want to behave as if the `command' builtin had not been specified
3560 and preserve the redirections. */
3561 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3563 if (saved_undo_list)
3564 dispose_redirects (saved_undo_list);
3565 redirection_undo_list = exec_redirection_undo_list;
3566 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3567 discard_unwind_frame ("saved_redirects");
3570 if (saved_undo_list)
3572 redirection_undo_list = saved_undo_list;
3573 discard_unwind_frame ("saved redirects");
3576 if (redirection_undo_list)
3578 cleanup_redirects (redirection_undo_list);
3579 redirection_undo_list = (REDIRECT *)NULL;
3586 setup_async_signals ()
3588 #if defined (__BEOS__)
3589 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3592 #if defined (JOB_CONTROL)
3593 if (job_control == 0)
3596 set_signal_handler (SIGINT, SIG_IGN);
3597 set_signal_ignored (SIGINT);
3598 set_signal_handler (SIGQUIT, SIG_IGN);
3599 set_signal_ignored (SIGQUIT);
3603 /* Execute a simple command that is hopefully defined in a disk file
3608 3) look up the command
3611 6) If the execve failed, see if the file has executable mode set.
3612 If so, and it isn't a directory, then execute its contents as
3615 Note that the filename hashing stuff has to take place up here,
3616 in the parent. This is probably why the Bourne style shells
3617 don't handle it, since that would require them to go through
3618 this gnarly hair, for no good reason.
3620 NOTE: callers expect this to fork or exit(). */
3622 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3623 async, fds_to_close, cmdflags)
3625 REDIRECT *redirects;
3627 int pipe_in, pipe_out, async;
3628 struct fd_bitmap *fds_to_close;
3631 char *pathname, *command, **args;
3635 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3636 pathname = words->word->word;
3638 #if defined (RESTRICTED_SHELL)
3639 command = (char *)NULL;
3640 if (restricted && xstrchr (pathname, '/'))
3642 internal_error (_("%s: restricted: cannot specify `/' in command names"),
3644 last_command_exit_value = EXECUTION_FAILURE;
3646 /* If we're not going to fork below, we must already be in a child
3647 process or a context in which it's safe to call exit(2). */
3648 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3649 exit (last_command_exit_value);
3653 #endif /* RESTRICTED_SHELL */
3655 command = search_for_command (pathname);
3659 maybe_make_export_env ();
3660 put_command_name_into_env (command);
3663 /* We have to make the child before we check for the non-existence
3664 of COMMAND, since we want the error messages to be redirected. */
3665 /* If we can get away without forking and there are no pipes to deal with,
3666 don't bother to fork, just directly exec the command. */
3667 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3670 pid = make_child (savestring (command_line), async);
3674 int old_interactive;
3677 /* This has been disabled for the time being. */
3678 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3679 if (posixly_correct == 0)
3680 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
3684 /* Cancel traps, in trap.c. */
3685 restore_original_signals ();
3687 /* restore_original_signals may have undone the work done
3688 by make_child to ensure that SIGINT and SIGQUIT are ignored
3689 in asynchronous children. */
3692 if ((cmdflags & CMD_STDIN_REDIR) &&
3693 pipe_in == NO_PIPE &&
3694 (stdin_redirects (redirects) == 0))
3695 async_redirect_stdin ();
3696 setup_async_signals ();
3699 /* This functionality is now provided by close-on-exec of the
3700 file descriptors manipulated by redirection and piping.
3701 Some file descriptors still need to be closed in all children
3702 because of the way bash does pipes; fds_to_close is a
3703 bitmap of all such file descriptors. */
3705 close_fd_bitmap (fds_to_close);
3707 do_piping (pipe_in, pipe_out);
3709 old_interactive = interactive;
3713 subshell_environment = SUBSHELL_FORK;
3715 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
3717 #if defined (PROCESS_SUBSTITUTION)
3718 /* Try to remove named pipes that may have been created as the
3719 result of redirections. */
3720 unlink_fifo_list ();
3721 #endif /* PROCESS_SUBSTITUTION */
3722 exit (EXECUTION_FAILURE);
3726 interactive = old_interactive;
3730 internal_error (_("%s: command not found"), pathname);
3731 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3734 /* Execve expects the command name to be in args[0]. So we
3735 leave it there, in the same format that the user used to
3737 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
3738 exit (shell_execve (command, args, export_env));
3743 /* Make sure that the pipes are closed in the parent. */
3744 close_pipes (pipe_in, pipe_out);
3745 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3746 unlink_fifo_list ();
3752 /* CPP defines to decide whether a particular index into the #! line
3753 corresponds to a valid interpreter name or argument character, or
3754 whitespace. The MSDOS define is to allow \r to be treated the same
3757 #if !defined (MSDOS)
3758 # define STRINGCHAR(ind) \
3759 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3760 # define WHITECHAR(ind) \
3761 (ind < sample_len && whitespace (sample[ind]))
3763 # define STRINGCHAR(ind) \
3764 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3765 # define WHITECHAR(ind) \
3766 (ind < sample_len && whitespace (sample[ind]))
3770 getinterp (sample, sample_len, endp)
3772 int sample_len, *endp;
3778 /* Find the name of the interpreter to exec. */
3779 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
3782 for (start = i; STRINGCHAR(i); i++)
3785 execname = substring (sample, start, i);
3792 #if !defined (HAVE_HASH_BANG_EXEC)
3793 /* If the operating system on which we're running does not handle
3794 the #! executable format, then help out. SAMPLE is the text read
3795 from the file, SAMPLE_LEN characters. COMMAND is the name of
3796 the script; it and ARGS, the arguments given by the user, will
3797 become arguments to the specified interpreter. ENV is the environment
3798 to pass to the interpreter.
3800 The word immediately following the #! is the interpreter to execute.
3801 A single argument to the interpreter is allowed. */
3804 execute_shell_script (sample, sample_len, command, args, env)
3810 char *execname, *firstarg;
3811 int i, start, size_increment, larry;
3813 /* Find the name of the interpreter to exec. */
3814 execname = getinterp (sample, sample_len, &i);
3817 /* Now the argument, if any. */
3818 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3821 /* If there is more text on the line, then it is an argument for the
3826 for (start = i; STRINGCHAR(i); i++)
3828 firstarg = substring ((char *)sample, start, i);
3832 larry = strvec_len (args) + size_increment;
3833 args = strvec_resize (args, larry + 1);
3835 for (i = larry - 1; i; i--)
3836 args[i] = args[i - size_increment];
3847 args[larry] = (char *)NULL;
3849 return (shell_execve (execname, args, env));
3854 #endif /* !HAVE_HASH_BANG_EXEC */
3857 initialize_subshell ()
3860 /* Forget about any aliases that we knew of. We are in a subshell. */
3861 delete_all_aliases ();
3864 #if defined (HISTORY)
3865 /* Forget about the history lines we have read. This is a non-interactive
3867 history_lines_this_session = 0;
3870 #if defined (JOB_CONTROL)
3871 /* Forget about the way job control was working. We are in a subshell. */
3872 without_job_control ();
3873 set_sigchld_handler ();
3875 #endif /* JOB_CONTROL */
3877 /* Reset the values of the shell flags and options. */
3878 reset_shell_flags ();
3879 reset_shell_options ();
3880 reset_shopt_options ();
3882 /* Zero out builtin_env, since this could be a shell script run from a
3883 sourced file with a temporary environment supplied to the `source/.'
3884 builtin. Such variables are not supposed to be exported (empirical
3885 testing with sh and ksh). Just throw it away; don't worry about a
3887 if (vc_isbltnenv (shell_variables))
3888 shell_variables = shell_variables->down;
3890 clear_unwind_protect_list (0);
3891 /* XXX -- are there other things we should be resetting here? */
3892 parse_and_execute_level = 0; /* nothing left to restore it */
3894 /* We're no longer inside a shell function. */
3895 variable_context = return_catch_flag = 0;
3897 /* If we're not interactive, close the file descriptor from which we're
3898 reading the current shell script. */
3899 if (interactive_shell == 0)
3900 unset_bash_input (0);
3903 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3904 # define SETOSTYPE(x) __setostype(x)
3906 # define SETOSTYPE(x)
3909 #define READ_SAMPLE_BUF(file, buf, len) \
3912 fd = open(file, O_RDONLY); \
3915 len = read (fd, buf, 80); \
3923 /* Call execve (), handling interpreting shell scripts, and handling
3926 shell_execve (command, args, env)
3935 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3936 execve (command, args, env);
3937 i = errno; /* error from execve() */
3940 /* If we get to this point, then start checking out the file.
3941 Maybe it is something we can hack ourselves. */
3944 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3945 internal_error (_("%s: is a directory"), command);
3946 else if (executable_file (command) == 0)
3949 file_error (command);
3951 /* errors not involving the path argument to execve. */
3952 else if (i == E2BIG || i == ENOMEM)
3955 file_error (command);
3959 /* The file has the execute bits set, but the kernel refuses to
3960 run it for some reason. See why. */
3961 #if defined (HAVE_HASH_BANG_EXEC)
3962 READ_SAMPLE_BUF (command, sample, sample_len);
3963 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3968 interp = getinterp (sample, sample_len, (int *)NULL);
3969 ilen = strlen (interp);
3971 if (interp[ilen - 1] == '\r')
3973 interp = xrealloc (interp, ilen + 2);
3974 interp[ilen - 1] = '^';
3976 interp[ilen + 1] = '\0';
3978 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
3984 file_error (command);
3986 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3989 /* This file is executable.
3990 If it begins with #!, then help out people with losing operating
3991 systems. Otherwise, check to see if it is a binary file by seeing
3992 if the contents of the first line (or up to 80 characters) are in the
3993 ASCII set. If it's a text file, execute the contents as shell commands,
3994 otherwise return 126 (EX_BINARY_FILE). */
3995 READ_SAMPLE_BUF (command, sample, sample_len);
3997 if (sample_len == 0)
3998 return (EXECUTION_SUCCESS);
4000 /* Is this supposed to be an executable script?
4001 If so, the format of the line is "#! interpreter [argument]".
4002 A single argument is allowed. The BSD kernel restricts
4003 the length of the entire line to 32 characters (32 bytes
4004 being the size of the BSD exec header), but we allow 80
4008 #if !defined (HAVE_HASH_BANG_EXEC)
4009 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4010 return (execute_shell_script (sample, sample_len, command, args, env));
4013 if (check_binary_file (sample, sample_len))
4015 internal_error (_("%s: cannot execute binary file"), command);
4016 return (EX_BINARY_FILE);
4020 /* We have committed to attempting to execute the contents of this file
4021 as shell commands. */
4023 initialize_subshell ();
4025 set_sigint_handler ();
4027 /* Insert the name of this shell into the argument list. */
4028 larray = strvec_len (args) + 1;
4029 args = strvec_resize (args, larray + 1);
4031 for (i = larray - 1; i; i--)
4032 args[i] = args[i - 1];
4034 args[0] = shell_name;
4036 args[larray] = (char *)NULL;
4038 if (args[0][0] == '-')
4041 #if defined (RESTRICTED_SHELL)
4043 change_flag ('r', FLAG_OFF);
4048 /* Can't free subshell_argv[0]; that is shell_name. */
4049 for (i = 1; i < subshell_argc; i++)
4050 free (subshell_argv[i]);
4051 free (subshell_argv);
4054 dispose_command (currently_executing_command); /* XXX */
4055 currently_executing_command = (COMMAND *)NULL;
4057 subshell_argc = larray;
4058 subshell_argv = args;
4059 subshell_envp = env;
4061 unbind_args (); /* remove the positional parameters */
4063 longjmp (subshell_top_level, 1);
4068 execute_intern_function (name, function)
4074 if (check_identifier (name, posixly_correct) == 0)
4076 if (posixly_correct && interactive_shell == 0)
4078 last_command_exit_value = EX_USAGE;
4079 jump_to_top_level (ERREXIT);
4081 return (EXECUTION_FAILURE);
4084 var = find_function (name->word);
4085 if (var && (readonly_p (var) || noassign_p (var)))
4087 if (readonly_p (var))
4088 internal_error (_("%s: readonly function"), var->name);
4089 return (EXECUTION_FAILURE);
4092 bind_function (name->word, function);
4093 return (EXECUTION_SUCCESS);
4096 #if defined (INCLUDE_UNUSED)
4097 #if defined (PROCESS_SUBSTITUTION)
4101 register int i, fd_table_size;
4103 fd_table_size = getdtablesize ();
4104 if (fd_table_size > 256) /* clamp to a reasonable value */
4105 fd_table_size = 256;
4107 for (i = 3; i < fd_table_size; i++)
4110 #endif /* PROCESS_SUBSTITUTION */
4114 close_pipes (in, out)
4124 dup_error (oldd, newd)
4127 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
4130 /* Redirect input and output to be from and to the specified pipes.
4131 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4133 do_piping (pipe_in, pipe_out)
4134 int pipe_in, pipe_out;
4136 if (pipe_in != NO_PIPE)
4138 if (dup2 (pipe_in, 0) < 0)
4139 dup_error (pipe_in, 0);
4143 if (pipe_out != NO_PIPE)
4145 if (pipe_out != REDIRECT_BOTH)
4147 if (dup2 (pipe_out, 1) < 0)
4148 dup_error (pipe_out, 1);
4149 if (pipe_out == 0 || pipe_out > 1)
4154 if (dup2 (1, 2) < 0)