1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2016 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
34 #include "posixstat.h"
36 #if defined (HAVE_SYS_PARAM_H)
37 # include <sys/param.h>
40 #if defined (HAVE_UNISTD_H)
44 #include "posixtime.h"
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 # include <sys/resource.h>
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 # include <sys/times.h>
60 #define NEED_FPURGE_DECL
61 #define NEED_SH_SETLINEBUF_DECL
68 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
73 #include "execute_cmd.h"
80 #if defined (COND_COMMAND)
84 #include "builtins/common.h"
85 #include "builtins/builtext.h" /* list of builtins */
87 #include "builtins/getopt.h"
89 #include <glob/strmatch.h>
90 #include <tilde/tilde.h>
92 #if defined (BUFFERED_INPUT)
100 #if defined (HISTORY)
101 # include "bashhist.h"
104 #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
105 # include <mbstr.h> /* mbschr */
108 extern int dollar_dollar_pid
;
109 extern int posixly_correct
;
110 extern int expand_aliases
;
112 extern int breaking
, continuing
, loop_level
;
113 extern int parse_and_execute_level
, running_trap
, sourcelevel
;
114 extern int command_string_index
, line_number
;
115 extern int dot_found_in_search
;
116 extern int already_making_children
;
117 extern int tempenv_assign_error
;
118 extern char *the_printed_command
, *shell_name
;
119 extern pid_t last_command_subst_pid
;
120 extern sh_builtin_func_t
*last_shell_builtin
, *this_shell_builtin
;
121 extern char **subshell_argv
, **subshell_envp
;
122 extern int subshell_argc
;
123 extern time_t shell_start_time
;
125 extern char *glob_argv_flags
;
128 extern int job_control
; /* XXX */
130 extern int close
__P((int));
132 /* Static functions defined and used in this file. */
133 static void close_pipes
__P((int, int));
134 static void do_piping
__P((int, int));
135 static void bind_lastarg
__P((char *));
136 static int shell_control_structure
__P((enum command_type
));
137 static void cleanup_redirects
__P((REDIRECT
*));
139 #if defined (JOB_CONTROL)
140 static int restore_signal_mask
__P((sigset_t
*));
143 static void async_redirect_stdin
__P((void));
145 static int builtin_status
__P((int));
147 static int execute_for_command
__P((FOR_COM
*));
148 #if defined (SELECT_COMMAND)
149 static int displen
__P((const char *));
150 static int print_index_and_element
__P((int, int, WORD_LIST
*));
151 static void indent
__P((int, int));
152 static void print_select_list
__P((WORD_LIST
*, int, int, int));
153 static char *select_query
__P((WORD_LIST
*, int, char *, int));
154 static int execute_select_command
__P((SELECT_COM
*));
156 #if defined (DPAREN_ARITHMETIC)
157 static int execute_arith_command
__P((ARITH_COM
*));
159 #if defined (COND_COMMAND)
160 static int execute_cond_node
__P((COND_COM
*));
161 static int execute_cond_command
__P((COND_COM
*));
163 #if defined (COMMAND_TIMING)
164 static int mkfmt
__P((char *, int, int, time_t, int));
165 static void print_formatted_time
__P((FILE *, char *,
166 time_t, int, time_t, int,
168 static int time_command
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
170 #if defined (ARITH_FOR_COMMAND)
171 static intmax_t eval_arith_for_expr
__P((WORD_LIST
*, int *));
172 static int execute_arith_for_command
__P((ARITH_FOR_COM
*));
174 static int execute_case_command
__P((CASE_COM
*));
175 static int execute_while_command
__P((WHILE_COM
*));
176 static int execute_until_command
__P((WHILE_COM
*));
177 static int execute_while_or_until
__P((WHILE_COM
*, int));
178 static int execute_if_command
__P((IF_COM
*));
179 static int execute_null_command
__P((REDIRECT
*, int, int, int));
180 static void fix_assignment_words
__P((WORD_LIST
*));
181 static int execute_simple_command
__P((SIMPLE_COM
*, int, int, int, struct fd_bitmap
*));
182 static int execute_builtin
__P((sh_builtin_func_t
*, WORD_LIST
*, int, int));
183 static int execute_function
__P((SHELL_VAR
*, WORD_LIST
*, int, struct fd_bitmap
*, int, int));
184 static int execute_builtin_or_function
__P((WORD_LIST
*, sh_builtin_func_t
*,
186 REDIRECT
*, struct fd_bitmap
*, int));
187 static void execute_subshell_builtin_or_function
__P((WORD_LIST
*, REDIRECT
*,
193 static int execute_disk_command
__P((WORD_LIST
*, REDIRECT
*, char *,
194 int, int, int, struct fd_bitmap
*, int));
196 static char *getinterp
__P((char *, int, int *));
197 static void initialize_subshell
__P((void));
198 static int execute_in_subshell
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
199 #if defined (COPROCESS_SUPPORT)
200 static int execute_coproc
__P((COMMAND
*, int, int, struct fd_bitmap
*));
203 static int execute_pipeline
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
205 static int execute_connection
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
207 static int execute_intern_function
__P((WORD_DESC
*, FUNCTION_DEF
*));
209 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
210 so that reader_loop can set it to zero before executing a command. */
213 /* The name of the command that is currently being executed.
214 `test' needs this, for example. */
215 char *this_command_name
;
217 /* The printed representation of the currently-executing command (same as
218 the_printed_command), except when a trap is being executed. Useful for
219 a debugger to know where exactly the program is currently executing. */
220 char *the_printed_command_except_trap
;
222 /* For catching RETURN in a function. */
223 int return_catch_flag
;
224 int return_catch_value
;
225 procenv_t return_catch
;
227 /* The value returned by the last synchronous command. */
228 volatile int last_command_exit_value
;
230 /* Whether or not the last command (corresponding to last_command_exit_value)
231 was terminated by a signal, and, if so, which one. */
232 int last_command_exit_signal
;
234 /* Are we currently ignoring the -e option for the duration of a builtin's
236 int builtin_ignoring_errexit
= 0;
238 /* The list of redirections to perform which will undo the redirections
239 that I made in the shell. */
240 REDIRECT
*redirection_undo_list
= (REDIRECT
*)NULL
;
242 /* The list of redirections to perform which will undo the internal
243 redirections performed by the `exec' builtin. These are redirections
244 that must be undone even when exec discards redirection_undo_list. */
245 REDIRECT
*exec_redirection_undo_list
= (REDIRECT
*)NULL
;
247 /* When greater than zero, value is the `level' of builtins we are
248 currently executing (e.g. `eval echo a' would have it set to 2). */
249 int executing_builtin
= 0;
251 /* Non-zero if we are executing a command list (a;b;c, etc.) */
252 int executing_list
= 0;
254 /* Non-zero if failing commands in a command substitution should not exit the
255 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
256 commands run in command substitutions by parse_and_execute. */
257 int comsub_ignore_return
= 0;
259 /* Non-zero if we have just forked and are currently running in a subshell
261 int subshell_environment
;
263 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
264 int subshell_level
= 0;
266 /* Currently-executing shell function. */
267 SHELL_VAR
*this_shell_function
;
269 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
270 int match_ignore_case
= 0;
272 int executing_command_builtin
= 0;
274 struct stat SB
; /* used for debugging */
276 static int special_builtin_failed
;
278 static COMMAND
*currently_executing_command
;
280 /* The line number that the currently executing function starts on. */
281 static int function_line_number
;
283 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
284 number containing the function name. Used by executing_line_number to
285 report the correct line number. Kind of a hack. */
286 static int showing_function_line
;
288 /* $LINENO ($BASH_LINENO) for use by an ERR trap. Global so parse_and_execute
289 can save and restore it. */
290 int line_number_for_err_trap
;
292 /* A sort of function nesting level counter */
294 int funcnest_max
= 0;
296 int evalnest
= 0; /* bash-4.4/bash-5.0 */
297 int evalnest_max
= EVALNEST_MAX
;
300 int sourcenest_max
= SOURCENEST_MAX
;
302 volatile int from_return_trap
= 0;
304 int lastpipe_opt
= 0;
306 struct fd_bitmap
*current_fds_to_close
= (struct fd_bitmap
*)NULL
;
308 #define FD_BITMAP_DEFAULT_SIZE 32
310 /* Functions to allocate and deallocate the structures used to pass
311 information from the shell to its children about file descriptors
317 struct fd_bitmap
*ret
;
319 ret
= (struct fd_bitmap
*)xmalloc (sizeof (struct fd_bitmap
));
325 ret
->bitmap
= (char *)xmalloc (size
);
326 memset (ret
->bitmap
, '\0', size
);
329 ret
->bitmap
= (char *)NULL
;
334 dispose_fd_bitmap (fdbp
)
335 struct fd_bitmap
*fdbp
;
342 close_fd_bitmap (fdbp
)
343 struct fd_bitmap
*fdbp
;
349 for (i
= 0; i
< fdbp
->size
; i
++)
358 /* Return the line number of the currently executing command. */
360 executing_line_number ()
362 if (executing
&& showing_function_line
== 0 &&
363 (variable_context
== 0 || interactive_shell
== 0) &&
364 currently_executing_command
)
366 #if defined (COND_COMMAND)
367 if (currently_executing_command
->type
== cm_cond
)
368 return currently_executing_command
->value
.Cond
->line
;
370 #if defined (DPAREN_ARITHMETIC)
371 if (currently_executing_command
->type
== cm_arith
)
372 return currently_executing_command
->value
.Arith
->line
;
374 #if defined (ARITH_FOR_COMMAND)
375 if (currently_executing_command
->type
== cm_arith_for
)
376 return currently_executing_command
->value
.ArithFor
->line
;
385 /* Execute the command passed in COMMAND. COMMAND is exactly what
386 read_command () places into GLOBAL_COMMAND. See "command.h" for the
387 details of the command structure.
389 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
390 return values. Executing a command with nothing in it returns
391 EXECUTION_SUCCESS. */
393 execute_command (command
)
396 struct fd_bitmap
*bitmap
;
399 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
400 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
401 begin_unwind_frame ("execute-command");
402 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
404 /* Just do the command, but not asynchronously. */
405 result
= execute_command_internal (command
, 0, NO_PIPE
, NO_PIPE
, bitmap
);
407 dispose_fd_bitmap (bitmap
);
408 discard_unwind_frame ("execute-command");
410 #if defined (PROCESS_SUBSTITUTION)
411 /* don't unlink fifos if we're in a shell function; wait until the function
413 if (variable_context
== 0)
415 #endif /* PROCESS_SUBSTITUTION */
421 /* Return 1 if TYPE is a shell control structure type. */
423 shell_control_structure (type
)
424 enum command_type type
;
428 #if defined (ARITH_FOR_COMMAND)
431 #if defined (SELECT_COMMAND)
434 #if defined (DPAREN_ARITHMETIC)
437 #if defined (COND_COMMAND)
446 case cm_function_def
:
454 /* A function to use to unwind_protect the redirection undo list
457 cleanup_redirects (list
)
460 do_redirections (list
, RX_ACTIVE
);
461 dispose_redirects (list
);
465 /* Function to unwind_protect the redirections for functions and builtins. */
467 cleanup_func_redirects (list
)
470 do_redirections (list
, RX_ACTIVE
);
475 dispose_exec_redirects ()
477 if (exec_redirection_undo_list
)
479 dispose_redirects (exec_redirection_undo_list
);
480 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
484 #if defined (JOB_CONTROL)
485 /* A function to restore the signal mask to its proper value when the shell
486 is interrupted or errors occur while creating a pipeline. */
488 restore_signal_mask (set
)
491 return (sigprocmask (SIG_SETMASK
, set
, (sigset_t
*)NULL
));
493 #endif /* JOB_CONTROL */
496 /* A debugging function that can be called from gdb, for instance. */
501 int f
, fd_table_size
;
503 fd_table_size
= getdtablesize ();
505 fprintf (stderr
, "pid %ld open files:", (long)getpid ());
506 for (i
= 3; i
< fd_table_size
; i
++)
508 if ((f
= fcntl (i
, F_GETFD
, 0)) != -1)
509 fprintf (stderr
, " %d (%s)", i
, f
? "close" : "open");
511 fprintf (stderr
, "\n");
516 async_redirect_stdin ()
520 fd
= open ("/dev/null", O_RDONLY
);
527 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno
));
530 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
532 /* Execute the command passed in COMMAND, perhaps doing it asynchronously.
533 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
534 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
535 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
536 from and where it goes. They can have the value of NO_PIPE, which means
538 FDS_TO_CLOSE is a list of file descriptors to close once the child has
539 been forked. This list often contains the unusable sides of pipes, etc.
541 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
542 return values. Executing a command with nothing in it returns
543 EXECUTION_SUCCESS. */
545 execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
,
549 int pipe_in
, pipe_out
;
550 struct fd_bitmap
*fds_to_close
;
552 int exec_result
, user_subshell
, invert
, ignore_return
, was_error_trap
;
553 REDIRECT
*my_undo_list
, *exec_undo_list
;
555 volatile int last_pid
;
556 volatile int save_line_number
;
557 #if defined (PROCESS_SUBSTITUTION)
558 volatile int ofifo
, nfifo
, osize
, saved_fifo
;
559 volatile char *ofifo_list
;
562 if (breaking
|| continuing
)
563 return (last_command_exit_value
);
564 if (command
== 0 || read_but_dont_execute
)
565 return (EXECUTION_SUCCESS
);
568 run_pending_traps ();
571 if (running_trap
== 0)
573 currently_executing_command
= command
;
575 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
577 /* If we're inverting the return value and `set -e' has been executed,
578 we don't want a failing command to inadvertently cause the shell
580 if (exit_immediately_on_error
&& invert
) /* XXX */
581 command
->flags
|= CMD_IGNORE_RETURN
; /* XXX */
583 exec_result
= EXECUTION_SUCCESS
;
585 /* If a command was being explicitly run in a subshell, or if it is
586 a shell control-structure, and it has a pipe, then we do the command
588 if (command
->type
== cm_subshell
&& (command
->flags
& CMD_NO_FORK
))
589 return (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
591 #if defined (COPROCESS_SUPPORT)
592 if (command
->type
== cm_coproc
)
593 return (execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
));
596 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
598 if (command
->type
== cm_subshell
||
599 (command
->flags
& (CMD_WANT_SUBSHELL
|CMD_FORCE_SUBSHELL
)) ||
600 (shell_control_structure (command
->type
) &&
601 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
|| asynchronous
)))
606 /* Fork a subshell, turn off the subshell bit, turn off job
607 control and call execute_command () on the command again. */
608 line_number_for_err_trap
= line_number
; /* XXX - save value? */
609 tcmd
= make_command_string (command
);
610 paren_pid
= make_child (savestring (tcmd
), asynchronous
);
612 if (user_subshell
&& signal_is_trapped (ERROR_TRAP
) &&
613 signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
615 FREE (the_printed_command_except_trap
);
616 the_printed_command_except_trap
= savestring (the_printed_command
);
621 /* We want to run the exit trap for forced {} subshells, and we
622 want to note this before execute_in_subshell modifies the
623 COMMAND struct. Need to keep in mind that execute_in_subshell
624 runs the exit trap for () subshells itself. */
625 /* This handles { command; } & */
626 s
= user_subshell
== 0 && command
->type
== cm_group
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& asynchronous
;
627 /* run exit trap for : | { ...; } and { ...; } | : */
628 /* run exit trap for : | ( ...; ) and ( ...; ) | : */
629 s
+= user_subshell
== 0 && command
->type
== cm_group
&& (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
) && asynchronous
== 0;
631 last_command_exit_value
= execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
633 subshell_exit (last_command_exit_value
);
635 sh_exit (last_command_exit_value
);
640 close_pipes (pipe_in
, pipe_out
);
642 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
643 if (variable_context
== 0) /* wait until shell function completes */
646 /* If we are part of a pipeline, and not the end of the pipeline,
647 then we should simply return and let the last command in the
648 pipe be waited for. If we are not in a pipeline, or are the
649 last command in the pipeline, then we wait for the subshell
650 and return its exit status as usual. */
651 if (pipe_out
!= NO_PIPE
)
652 return (EXECUTION_SUCCESS
);
654 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
656 if (asynchronous
== 0)
658 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
659 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
660 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
662 exec_result
= wait_for (paren_pid
);
664 /* If we have to, invert the return value. */
666 exec_result
= ((exec_result
== EXECUTION_SUCCESS
)
668 : EXECUTION_SUCCESS
);
670 last_command_exit_value
= exec_result
;
671 if (user_subshell
&& was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
673 save_line_number
= line_number
;
674 line_number
= line_number_for_err_trap
;
676 line_number
= save_line_number
;
679 if (user_subshell
&& ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
681 run_pending_traps ();
682 jump_to_top_level (ERREXIT
);
685 return (last_command_exit_value
);
689 DESCRIBE_PID (paren_pid
);
691 run_pending_traps ();
693 /* Posix 2013 2.9.3.1: "the exit status of an asynchronous list
695 last_command_exit_value
= 0;
696 return (EXECUTION_SUCCESS
);
701 #if defined (COMMAND_TIMING)
702 if (command
->flags
& CMD_TIME_PIPELINE
)
706 command
->flags
|= CMD_FORCE_SUBSHELL
;
707 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
711 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
713 if (running_trap
== 0)
715 currently_executing_command
= (COMMAND
*)NULL
;
717 return (exec_result
);
719 #endif /* COMMAND_TIMING */
721 if (shell_control_structure (command
->type
) && command
->redirects
)
722 stdin_redir
= stdin_redirects (command
->redirects
);
724 #if defined (PROCESS_SUBSTITUTION)
725 if (variable_context
!= 0)
727 ofifo
= num_fifos ();
728 ofifo_list
= copy_fifo_list ((int *)&osize
);
729 begin_unwind_frame ("internal_fifos");
730 add_unwind_protect (xfree
, ofifo_list
);
737 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
739 if (do_redirections (command
->redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
741 cleanup_redirects (redirection_undo_list
);
742 redirection_undo_list
= (REDIRECT
*)NULL
;
743 dispose_exec_redirects ();
744 #if defined (PROCESS_SUBSTITUTION)
747 free ((void *)ofifo_list
);
748 discard_unwind_frame ("internal_fifos");
751 return (last_command_exit_value
= EXECUTION_FAILURE
);
754 if (redirection_undo_list
)
756 /* XXX - why copy here? */
757 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
758 dispose_redirects (redirection_undo_list
);
759 redirection_undo_list
= (REDIRECT
*)NULL
;
762 my_undo_list
= (REDIRECT
*)NULL
;
764 if (exec_redirection_undo_list
)
766 /* XXX - why copy here? */
767 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
768 dispose_redirects (exec_redirection_undo_list
);
769 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
772 exec_undo_list
= (REDIRECT
*)NULL
;
774 if (my_undo_list
|| exec_undo_list
)
775 begin_unwind_frame ("loop_redirections");
778 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
781 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
783 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
787 switch (command
->type
)
791 save_line_number
= line_number
;
792 /* We can't rely on variables retaining their values across a
793 call to execute_simple_command if a longjmp occurs as the
794 result of a `return' builtin. This is true for sure with gcc. */
795 #if defined (RECYCLES_PIDS)
796 last_made_pid
= NO_PID
;
798 last_pid
= last_made_pid
;
799 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
801 if (ignore_return
&& command
->value
.Simple
)
802 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
803 if (command
->flags
& CMD_STDIN_REDIR
)
804 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
806 line_number_for_err_trap
= line_number
= command
->value
.Simple
->line
;
808 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
809 asynchronous
, fds_to_close
);
810 line_number
= save_line_number
;
812 /* The temporary environment should be used for only the simple
813 command immediately following its definition. */
814 dispose_used_env_vars ();
816 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
817 /* Reclaim memory allocated with alloca () on machines which
818 may be using the alloca emulation code. */
820 #endif /* (ultrix && mips) || C_ALLOCA */
822 /* If we forked to do the command, then we must wait_for ()
825 /* XXX - this is something to watch out for if there are problems
826 when the shell is compiled without job control. Don't worry about
827 whether or not last_made_pid == last_pid; already_making_children
828 tells us whether or not there are unwaited-for children to wait
830 if (already_making_children
&& pipe_out
== NO_PIPE
)
832 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
836 DESCRIBE_PID (last_made_pid
);
837 exec_result
= EXECUTION_SUCCESS
;
838 invert
= 0; /* async commands always succeed */
841 #if !defined (JOB_CONTROL)
842 /* Do not wait for asynchronous processes started from
844 if (last_made_pid
!= NO_PID
&& last_made_pid
!= last_asynchronous_pid
)
846 if (last_made_pid
!= NO_PID
)
848 /* When executing a shell function that executes other
849 commands, this causes the last simple command in
850 the function to be waited for twice. This also causes
851 subshells forked to execute builtin commands (e.g., in
852 pipelines) to be waited for twice. */
853 exec_result
= wait_for (last_made_pid
);
857 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
858 only the failure of a simple command. */
859 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)
861 last_command_exit_value
= exec_result
;
862 line_number
= line_number_for_err_trap
;
864 line_number
= save_line_number
;
867 if (ignore_return
== 0 && invert
== 0 &&
868 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
869 (exit_immediately_on_error
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)))
871 last_command_exit_value
= exec_result
;
872 run_pending_traps ();
874 /* Undo redirections before running exit trap on the way out of
875 set -e. Report by Mark Farrell 5/19/2014 */
876 if (exit_immediately_on_error
&& signal_is_trapped (0) &&
877 unwind_protect_tag_on_stack ("saved-redirects"))
878 run_unwind_frame ("saved-redirects");
880 jump_to_top_level (ERREXIT
);
887 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
888 exec_result
= execute_for_command (command
->value
.For
);
891 #if defined (ARITH_FOR_COMMAND)
894 command
->value
.ArithFor
->flags
|= CMD_IGNORE_RETURN
;
895 exec_result
= execute_arith_for_command (command
->value
.ArithFor
);
899 #if defined (SELECT_COMMAND)
902 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
903 exec_result
= execute_select_command (command
->value
.Select
);
909 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
910 exec_result
= execute_case_command (command
->value
.Case
);
915 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
916 exec_result
= execute_while_command (command
->value
.While
);
921 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
922 exec_result
= execute_until_command (command
->value
.While
);
927 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
928 exec_result
= execute_if_command (command
->value
.If
);
933 /* This code can be executed from either of two paths: an explicit
934 '{}' command, or via a function call. If we are executed via a
935 function call, we have already taken care of the function being
936 executed in the background (down there in execute_simple_command ()),
937 and this command should *not* be marked as asynchronous. If we
938 are executing a regular '{}' group command, and asynchronous == 1,
939 we must want to execute the whole command in the background, so we
940 need a subshell, and we want the stuff executed in that subshell
941 (this group command) to be executed in the foreground of that
942 subshell (i.e. there will not be *another* subshell forked).
944 What we do is to force a subshell if asynchronous, and then call
945 execute_command_internal again with asynchronous still set to 1,
946 but with the original group command, so the printed command will
949 The code above that handles forking off subshells will note that
950 both subshell and async are on, and turn off async in the child
951 after forking the subshell (but leave async set in the parent, so
952 the normal call to describe_pid is made). This turning off
953 async is *crucial*; if it is not done, this will fall into an
954 infinite loop of executions through this spot in subshell after
955 subshell until the process limit is exhausted. */
959 command
->flags
|= CMD_FORCE_SUBSHELL
;
961 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
966 if (ignore_return
&& command
->value
.Group
->command
)
967 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
969 execute_command_internal (command
->value
.Group
->command
,
970 asynchronous
, pipe_in
, pipe_out
,
976 exec_result
= execute_connection (command
, asynchronous
,
977 pipe_in
, pipe_out
, fds_to_close
);
979 invert
= 0; /* XXX */
983 #if defined (DPAREN_ARITHMETIC)
985 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
987 command
->value
.Arith
->flags
|= CMD_IGNORE_RETURN
;
988 line_number_for_err_trap
= save_line_number
= line_number
;
989 exec_result
= execute_arith_command (command
->value
.Arith
);
990 line_number
= save_line_number
;
992 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
994 last_command_exit_value
= exec_result
;
995 save_line_number
= line_number
;
996 line_number
= line_number_for_err_trap
;
998 line_number
= save_line_number
;
1001 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
1003 last_command_exit_value
= exec_result
;
1004 run_pending_traps ();
1005 jump_to_top_level (ERREXIT
);
1011 #if defined (COND_COMMAND)
1013 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
1015 command
->value
.Cond
->flags
|= CMD_IGNORE_RETURN
;
1017 line_number_for_err_trap
= save_line_number
= line_number
;
1018 exec_result
= execute_cond_command (command
->value
.Cond
);
1019 line_number
= save_line_number
;
1021 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
1023 last_command_exit_value
= exec_result
;
1024 save_line_number
= line_number
;
1025 line_number
= line_number_for_err_trap
;
1027 line_number
= save_line_number
;
1030 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
1032 last_command_exit_value
= exec_result
;
1033 run_pending_traps ();
1034 jump_to_top_level (ERREXIT
);
1040 case cm_function_def
:
1041 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
1042 command
->value
.Function_def
);
1046 command_error ("execute_command", CMDERR_BADTYPE
, command
->type
, 0);
1051 do_redirections (my_undo_list
, RX_ACTIVE
);
1052 dispose_redirects (my_undo_list
);
1056 dispose_redirects (exec_undo_list
);
1058 if (my_undo_list
|| exec_undo_list
)
1059 discard_unwind_frame ("loop_redirections");
1061 #if defined (PROCESS_SUBSTITUTION)
1064 nfifo
= num_fifos ();
1066 close_new_fifos ((char *)ofifo_list
, osize
);
1067 free ((void *)ofifo_list
);
1068 discard_unwind_frame ("internal_fifos");
1072 /* Invert the return value if we have to */
1074 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
1076 : EXECUTION_SUCCESS
;
1078 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
1079 /* This is where we set PIPESTATUS from the exit status of the appropriate
1080 compound commands (the ones that look enough like simple commands to
1081 cause confusion). We might be able to optimize by not doing this if
1082 subshell_environment != 0. */
1083 switch (command
->type
)
1085 # if defined (DPAREN_ARITHMETIC)
1088 # if defined (COND_COMMAND)
1091 set_pipestatus_from_exit (exec_result
);
1096 last_command_exit_value
= exec_result
;
1097 run_pending_traps ();
1099 if (running_trap
== 0)
1101 currently_executing_command
= (COMMAND
*)NULL
;
1103 return (last_command_exit_value
);
1106 #if defined (COMMAND_TIMING)
1108 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1109 extern struct timeval
*difftimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1110 extern struct timeval
*addtimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1111 extern int timeval_to_cpu
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1114 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1115 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1117 static const int precs
[] = { 0, 100, 10, 1 };
1119 #if defined (HAVE_LOCALE_H) && defined (HAVE_LOCALECONV)
1126 return (lv
&& lv
->decimal_point
&& lv
->decimal_point
[0]) ? lv
->decimal_point
[0] : '.';
1129 # define decpoint() '.'
1132 /* Expand one `%'-prefixed escape sequence from a time format string. */
1134 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
1141 char abuf
[INT_STRLEN_BOUND(time_t) + 1];
1145 abuf
[sizeof(abuf
) - 1] = '\0';
1147 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1152 aind
= sizeof(abuf
) - 2;
1154 abuf
[aind
--] = (min
% 10) + '0';
1158 buf
[ind
++] = abuf
[aind
++];
1162 /* Now add the seconds. */
1163 aind
= sizeof (abuf
) - 2;
1165 abuf
[aind
--] = (sec
% 10) + '0';
1169 buf
[ind
++] = abuf
[aind
++];
1171 /* We want to add a decimal point and PREC places after it if PREC is
1172 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1176 buf
[ind
++] = decpoint ();
1177 for (aind
= 1; aind
<= prec
; aind
++)
1179 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
1180 sec_fraction
%= precs
[aind
];
1191 /* Interpret the format string FORMAT, interpolating the following escape
1195 where the optional `prec' is a precision, meaning the number of
1196 characters after the decimal point, the optional `l' means to format
1197 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1198 and the last character is one of
1200 R number of seconds of `real' time
1201 U number of seconds of `user' time
1202 S number of seconds of `system' time
1204 An occurrence of `%%' in the format string is translated to a `%'. The
1205 result is printed to FP, a pointer to a FILE. The other variables are
1206 the seconds and thousandths of a second of real, user, and system time,
1209 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1220 char *str
, *s
, ts
[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1225 len
= strlen (format
);
1226 ssize
= (len
+ 64) - (len
% 64);
1227 str
= (char *)xmalloc (ssize
);
1230 for (s
= format
; *s
; s
++)
1232 if (*s
!= '%' || s
[1] == '\0')
1234 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1237 else if (s
[1] == '%')
1240 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1243 else if (s
[1] == 'P')
1247 /* clamp CPU usage at 100% */
1252 sum_frac
= (cpu
% 100) * 10;
1253 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1254 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1255 strcpy (str
+ sindex
, ts
);
1260 prec
= 3; /* default is three places past the decimal point. */
1261 lng
= 0; /* default is to not use minutes or append `s' */
1263 if (DIGIT (*s
)) /* `precision' */
1266 if (prec
> 3) prec
= 3;
1268 if (*s
== 'l') /* `length extender' */
1273 if (*s
== 'R' || *s
== 'E')
1274 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1276 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1278 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1281 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s
);
1285 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1286 strcpy (str
+ sindex
, ts
);
1292 fprintf (fp
, "%s\n", str
);
1299 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1301 int asynchronous
, pipe_in
, pipe_out
;
1302 struct fd_bitmap
*fds_to_close
;
1304 int rv
, posix_time
, old_flags
, nullcmd
, code
;
1309 volatile procenv_t save_top_level
;
1311 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1312 struct timeval real
, user
, sys
;
1313 struct timeval before
, after
;
1314 # if defined (HAVE_STRUCT_TIMEZONE)
1315 struct timezone dtz
; /* posix doesn't define this */
1317 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1319 # if defined (HAVE_TIMES)
1320 clock_t tbefore
, tafter
, real
, user
, sys
;
1321 struct tms before
, after
;
1325 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1326 # if defined (HAVE_STRUCT_TIMEZONE)
1327 gettimeofday (&before
, &dtz
);
1329 gettimeofday (&before
, (void *)NULL
);
1330 # endif /* !HAVE_STRUCT_TIMEZONE */
1331 getrusage (RUSAGE_SELF
, &selfb
);
1332 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1334 # if defined (HAVE_TIMES)
1335 tbefore
= times (&before
);
1339 posix_time
= command
&& (command
->flags
& CMD_TIME_POSIX
);
1341 nullcmd
= (command
== 0) || (command
->type
== cm_simple
&& command
->value
.Simple
->words
== 0 && command
->value
.Simple
->redirects
== 0);
1342 if (posixly_correct
&& nullcmd
)
1344 #if defined (HAVE_GETRUSAGE)
1345 selfb
.ru_utime
.tv_sec
= kidsb
.ru_utime
.tv_sec
= selfb
.ru_stime
.tv_sec
= kidsb
.ru_stime
.tv_sec
= 0;
1346 selfb
.ru_utime
.tv_usec
= kidsb
.ru_utime
.tv_usec
= selfb
.ru_stime
.tv_usec
= kidsb
.ru_stime
.tv_usec
= 0;
1347 before
.tv_sec
= shell_start_time
;
1350 before
.tms_utime
= before
.tms_stime
= before
.tms_cutime
= before
.tms_cstime
= 0;
1351 tbefore
= shell_start_time
;
1355 old_flags
= command
->flags
;
1356 COPY_PROCENV (top_level
, save_top_level
);
1357 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1358 code
= setjmp_nosigs (top_level
);
1359 if (code
== NOT_JUMPED
)
1360 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1361 command
->flags
= old_flags
;
1362 COPY_PROCENV (save_top_level
, top_level
);
1365 rsf
= usf
= ssf
= cpu
= 0;
1367 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1368 # if defined (HAVE_STRUCT_TIMEZONE)
1369 gettimeofday (&after
, &dtz
);
1371 gettimeofday (&after
, (void *)NULL
);
1372 # endif /* !HAVE_STRUCT_TIMEZONE */
1373 getrusage (RUSAGE_SELF
, &selfa
);
1374 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1376 difftimeval (&real
, &before
, &after
);
1377 timeval_to_secs (&real
, &rs
, &rsf
);
1379 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1380 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1381 timeval_to_secs (&user
, &us
, &usf
);
1383 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1384 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1385 timeval_to_secs (&sys
, &ss
, &ssf
);
1387 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1389 # if defined (HAVE_TIMES)
1390 tafter
= times (&after
);
1392 real
= tafter
- tbefore
;
1393 clock_t_to_secs (real
, &rs
, &rsf
);
1395 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1396 clock_t_to_secs (user
, &us
, &usf
);
1398 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1399 clock_t_to_secs (sys
, &ss
, &ssf
);
1401 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1405 rsf
= usf
= ssf
= cpu
= 0;
1410 time_format
= POSIX_TIMEFORMAT
;
1411 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1413 if (posixly_correct
&& nullcmd
)
1414 time_format
= "user\t%2lU\nsys\t%2lS";
1416 time_format
= BASH_TIMEFORMAT
;
1418 if (time_format
&& *time_format
)
1419 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1422 sh_longjmp (top_level
, code
);
1426 #endif /* COMMAND_TIMING */
1428 /* Execute a command that's supposed to be in a subshell. This must be
1429 called after make_child and we must be running in the child process.
1430 The caller will return or exit() immediately with the value this returns. */
1432 execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1435 int pipe_in
, pipe_out
;
1436 struct fd_bitmap
*fds_to_close
;
1438 int user_subshell
, return_code
, function_value
, should_redir_stdin
, invert
;
1439 int ois
, user_coproc
;
1441 volatile COMMAND
*tcom
;
1443 USE_VAR(user_subshell
);
1444 USE_VAR(user_coproc
);
1447 USE_VAR(asynchronous
);
1450 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
1451 pipe_in
== NO_PIPE
&&
1452 stdin_redirects (command
->redirects
) == 0);
1454 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
1455 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
1456 user_coproc
= command
->type
== cm_coproc
;
1458 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
1460 /* If a command is asynchronous in a subshell (like ( foo ) & or
1461 the special case of an asynchronous GROUP command where the
1462 the subshell bit is turned on down in case cm_group: below),
1463 turn off `asynchronous', so that two subshells aren't spawned.
1464 XXX - asynchronous used to be set to 0 in this block, but that
1465 means that setup_async_signals was never run. Now it's set to
1466 0 after subshell_environment is set appropriately and setup_async_signals
1469 This seems semantically correct to me. For example,
1470 ( foo ) & seems to say ``do the command `foo' in a subshell
1471 environment, but don't wait for that subshell to finish'',
1472 and "{ foo ; bar ; } &" seems to me to be like functions or
1473 builtins in the background, which executed in a subshell
1474 environment. I just don't see the need to fork two subshells. */
1476 /* Don't fork again, we are already in a subshell. A `doubly
1477 async' shell is not interactive, however. */
1480 #if defined (JOB_CONTROL)
1481 /* If a construct like ( exec xxx yyy ) & is given while job
1482 control is active, we want to prevent exec from putting the
1483 subshell back into the original process group, carefully
1484 undoing all the work we just did in make_child. */
1486 #endif /* JOB_CONTROL */
1487 ois
= interactive_shell
;
1488 interactive_shell
= 0;
1489 /* This test is to prevent alias expansion by interactive shells that
1490 run `(command) &' but to allow scripts that have enabled alias
1491 expansion with `shopt -s expand_alias' to continue to expand
1493 if (ois
!= interactive_shell
)
1497 /* Subshells are neither login nor interactive. */
1498 login_shell
= interactive
= 0;
1501 subshell_environment
= SUBSHELL_PAREN
; /* XXX */
1504 subshell_environment
= 0; /* XXX */
1506 subshell_environment
|= SUBSHELL_ASYNC
;
1507 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
1508 subshell_environment
|= SUBSHELL_PIPE
;
1510 subshell_environment
|= SUBSHELL_COPROC
;
1513 reset_terminating_signals (); /* in sig.c */
1514 /* Cancel traps, in trap.c. */
1515 /* Reset the signal handlers in the child, but don't free the
1516 trap strings. Set a flag noting that we have to free the
1517 trap strings if we run trap to change a signal disposition. */
1518 reset_signal_handlers ();
1519 subshell_environment
|= SUBSHELL_RESETTRAP
;
1521 /* Make sure restore_original_signals doesn't undo the work done by
1522 make_child to ensure that asynchronous children are immune to SIGINT
1523 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1527 setup_async_signals ();
1531 #if defined (JOB_CONTROL)
1532 set_sigchld_handler ();
1533 #endif /* JOB_CONTROL */
1535 set_sigint_handler ();
1537 #if defined (JOB_CONTROL)
1538 /* Delete all traces that there were any jobs running. This is
1539 only for subshells. */
1540 without_job_control ();
1541 #endif /* JOB_CONTROL */
1544 close_fd_bitmap (fds_to_close
);
1546 do_piping (pipe_in
, pipe_out
);
1548 #if defined (COPROCESS_SUPPORT)
1552 /* If this is a user subshell, set a flag if stdin was redirected.
1553 This is used later to decide whether to redirect fd 0 to
1554 /dev/null for async commands in the subshell. This adds more
1555 sh compatibility, but I'm not sure it's the right thing to do.
1556 Note that an input pipe to a compound command suffices to inhibit
1557 the implicit /dev/null redirection for asynchronous commands
1558 executed as part of that compound command. */
1561 stdin_redir
= stdin_redirects (command
->redirects
) || pipe_in
!= NO_PIPE
;
1563 restore_default_signal (EXIT_TRAP
); /* XXX - reset_signal_handlers above */
1566 else if (shell_control_structure (command
->type
) && pipe_in
!= NO_PIPE
)
1569 /* If this is an asynchronous command (command &), we want to
1570 redirect the standard input from /dev/null in the absence of
1571 any specific redirection involving stdin. */
1572 if (should_redir_stdin
&& stdin_redir
== 0)
1573 async_redirect_stdin ();
1575 /* Do redirections, then dispose of them before recursive call. */
1576 if (command
->redirects
)
1578 if (do_redirections (command
->redirects
, RX_ACTIVE
) != 0)
1579 exit (invert
? EXECUTION_SUCCESS
: EXECUTION_FAILURE
);
1581 dispose_redirects (command
->redirects
);
1582 command
->redirects
= (REDIRECT
*)NULL
;
1585 if (command
->type
== cm_subshell
)
1586 tcom
= command
->value
.Subshell
->command
;
1587 else if (user_coproc
)
1588 tcom
= command
->value
.Coproc
->command
;
1592 if (command
->flags
& CMD_TIME_PIPELINE
)
1593 tcom
->flags
|= CMD_TIME_PIPELINE
;
1594 if (command
->flags
& CMD_TIME_POSIX
)
1595 tcom
->flags
|= CMD_TIME_POSIX
;
1597 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1598 if ((command
->flags
& CMD_IGNORE_RETURN
) && tcom
!= command
)
1599 tcom
->flags
|= CMD_IGNORE_RETURN
;
1601 /* If this is a simple command, tell execute_disk_command that it
1602 might be able to get away without forking and simply exec.
1603 This means things like ( sleep 10 ) will only cause one fork.
1604 If we're timing the command or inverting its return value, however,
1605 we cannot do this optimization. */
1606 if ((user_subshell
|| user_coproc
) && (tcom
->type
== cm_simple
|| tcom
->type
== cm_subshell
) &&
1607 ((tcom
->flags
& CMD_TIME_PIPELINE
) == 0) &&
1608 ((tcom
->flags
& CMD_INVERT_RETURN
) == 0))
1610 tcom
->flags
|= CMD_NO_FORK
;
1611 if (tcom
->type
== cm_simple
)
1612 tcom
->value
.Simple
->flags
|= CMD_NO_FORK
;
1615 invert
= (tcom
->flags
& CMD_INVERT_RETURN
) != 0;
1616 tcom
->flags
&= ~CMD_INVERT_RETURN
;
1618 result
= setjmp_nosigs (top_level
);
1620 /* If we're inside a function while executing this subshell, we
1621 need to handle a possible `return'. */
1623 if (return_catch_flag
)
1624 function_value
= setjmp_nosigs (return_catch
);
1626 /* If we're going to exit the shell, we don't want to invert the return
1628 if (result
== EXITPROG
)
1629 invert
= 0, return_code
= last_command_exit_value
;
1631 return_code
= (last_command_exit_value
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: last_command_exit_value
;
1632 else if (function_value
)
1633 return_code
= return_catch_value
;
1635 return_code
= execute_command_internal ((COMMAND
*)tcom
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
1637 /* If we are asked to, invert the return value. */
1639 return_code
= (return_code
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
1640 : EXECUTION_SUCCESS
;
1642 /* If we were explicitly placed in a subshell with (), we need
1643 to do the `shell cleanup' things, such as running traps[0]. */
1644 if (user_subshell
&& signal_is_trapped (0))
1646 last_command_exit_value
= return_code
;
1647 return_code
= run_exit_trap ();
1651 subshell_level
--; /* don't bother, caller will just exit */
1653 return (return_code
);
1657 #if defined (COPROCESS_SUPPORT)
1658 #define COPROC_MAX 16
1660 typedef struct cpelement
1662 struct cpelement
*next
;
1663 struct coproc
*coproc
;
1667 typedef struct cplist
1669 struct cpelement
*head
;
1670 struct cpelement
*tail
;
1676 static struct cpelement
*cpe_alloc
__P((struct coproc
*));
1677 static void cpe_dispose
__P((struct cpelement
*));
1678 static struct cpelement
*cpl_add
__P((struct coproc
*));
1679 static struct cpelement
*cpl_delete
__P((pid_t
));
1680 static void cpl_reap
__P((void));
1681 static void cpl_flush
__P((void));
1682 static void cpl_closeall
__P((void));
1683 static struct cpelement
*cpl_search
__P((pid_t
));
1684 static struct cpelement
*cpl_searchbyname
__P((const char *));
1685 static void cpl_prune
__P((void));
1687 static void coproc_free
__P((struct coproc
*));
1689 /* Will go away when there is fully-implemented support for multiple coprocs. */
1690 Coproc sh_coproc
= { 0, NO_PID
, -1, -1, 0, 0, 0, 0, 0 };
1692 cplist_t coproc_list
= {0, 0, 0};
1694 /* Functions to manage the list of coprocs */
1696 static struct cpelement
*
1700 struct cpelement
*cpe
;
1702 cpe
= (struct cpelement
*)xmalloc (sizeof (struct cpelement
));
1704 cpe
->next
= (struct cpelement
*)0;
1710 struct cpelement
*cpe
;
1715 static struct cpelement
*
1719 struct cpelement
*cpe
;
1721 cpe
= cpe_alloc (cp
);
1723 if (coproc_list
.head
== 0)
1725 coproc_list
.head
= coproc_list
.tail
= cpe
;
1726 coproc_list
.ncoproc
= 0; /* just to make sure */
1730 coproc_list
.tail
->next
= cpe
;
1731 coproc_list
.tail
= cpe
;
1733 coproc_list
.ncoproc
++;
1738 static struct cpelement
*
1742 struct cpelement
*prev
, *p
;
1744 for (prev
= p
= coproc_list
.head
; p
; prev
= p
, p
= p
->next
)
1745 if (p
->coproc
->c_pid
== pid
)
1747 prev
->next
= p
->next
; /* remove from list */
1752 return 0; /* not found */
1755 itrace("cpl_delete: deleting %d", pid
);
1758 /* Housekeeping in the border cases. */
1759 if (p
== coproc_list
.head
)
1760 coproc_list
.head
= coproc_list
.head
->next
;
1761 else if (p
== coproc_list
.tail
)
1762 coproc_list
.tail
= prev
;
1764 coproc_list
.ncoproc
--;
1765 if (coproc_list
.ncoproc
== 0)
1766 coproc_list
.head
= coproc_list
.tail
= 0;
1767 else if (coproc_list
.ncoproc
== 1)
1768 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1776 struct cpelement
*p
, *next
, *nh
, *nt
;
1778 /* Build a new list by removing dead coprocs and fix up the coproc_list
1779 pointers when done. */
1780 nh
= nt
= next
= (struct cpelement
*)0;
1781 for (p
= coproc_list
.head
; p
; p
= next
)
1784 if (p
->coproc
->c_flags
& COPROC_DEAD
)
1786 coproc_list
.ncoproc
--; /* keep running count, fix up pointers later */
1789 itrace("cpl_reap: deleting %d", p
->coproc
->c_pid
);
1792 coproc_dispose (p
->coproc
);
1804 if (coproc_list
.ncoproc
== 0)
1805 coproc_list
.head
= coproc_list
.tail
= 0;
1810 coproc_list
.head
= nh
;
1811 coproc_list
.tail
= nt
;
1812 if (coproc_list
.ncoproc
== 1)
1813 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1817 /* Clear out the list of saved statuses */
1821 struct cpelement
*cpe
, *p
;
1823 for (cpe
= coproc_list
.head
; cpe
; )
1828 coproc_dispose (p
->coproc
);
1832 coproc_list
.head
= coproc_list
.tail
= 0;
1833 coproc_list
.ncoproc
= 0;
1839 struct cpelement
*cpe
;
1841 for (cpe
= coproc_list
.head
; cpe
; cpe
= cpe
->next
)
1842 coproc_close (cpe
->coproc
);
1849 struct cpelement
*cpe
;
1851 for (cpe
= coproc_list
.head
; cpe
; cpe
= cpe
->next
)
1852 coproc_checkfd (cpe
->coproc
, fd
);
1855 /* Search for PID in the list of coprocs; return the cpelement struct if
1856 found. If not found, return NULL. */
1857 static struct cpelement
*
1861 struct cpelement
*cpe
;
1863 for (cpe
= coproc_list
.head
; cpe
; cpe
= cpe
->next
)
1864 if (cpe
->coproc
->c_pid
== pid
)
1866 return (struct cpelement
*)NULL
;
1869 /* Search for the coproc named NAME in the list of coprocs; return the
1870 cpelement struct if found. If not found, return NULL. */
1871 static struct cpelement
*
1872 cpl_searchbyname (name
)
1875 struct cpelement
*cp
;
1877 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1878 if (STREQ (cp
->coproc
->c_name
, name
))
1880 return (struct cpelement
*)NULL
;
1887 struct cpelement
*cp
;
1889 while (coproc_list
.head
&& coproc_list
.ncoproc
> COPROC_MAX
)
1891 cp
= coproc_list
.head
;
1892 coproc_list
.head
= coproc_list
.head
->next
;
1893 coproc_dispose (cp
->coproc
);
1895 coproc_list
.ncoproc
--;
1900 /* These currently use a single global "shell coproc" but are written in a
1901 way to not preclude additional coprocs later (using the list management
1905 getcoprocbypid (pid
)
1908 #if MULTIPLE_COPROCS
1909 struct cpelement
*p
;
1911 p
= cpl_search (pid
);
1912 return (p
? p
->coproc
: 0);
1914 return (pid
== sh_coproc
.c_pid
? &sh_coproc
: 0);
1919 getcoprocbyname (name
)
1922 #if MULTIPLE_COPROCS
1923 struct cpelement
*p
;
1925 p
= cpl_searchbyname (name
);
1926 return (p
? p
->coproc
: 0);
1928 return ((sh_coproc
.c_name
&& STREQ (sh_coproc
.c_name
, name
)) ? &sh_coproc
: 0);
1938 cp
->c_rfd
= cp
->c_wfd
= -1;
1939 cp
->c_rsave
= cp
->c_wsave
= -1;
1940 cp
->c_flags
= cp
->c_status
= cp
->c_lock
= 0;
1944 coproc_alloc (name
, pid
)
1950 #if MULTIPLE_COPROCS
1951 cp
= (struct coproc
*)xmalloc (sizeof (struct coproc
));
1959 cp
->c_name
= savestring (name
);
1960 #if MULTIPLE_COPROCS
1983 BLOCK_SIGNAL (SIGCHLD
, set
, oset
);
1985 coproc_unsetvars (cp
);
1988 #if MULTIPLE_COPROCS
1994 UNBLOCK_SIGNAL (oset
);
1997 /* Placeholder for now. Will require changes for multiple coprocs */
2001 #if MULTIPLE_COPROCS
2004 coproc_dispose (&sh_coproc
);
2022 cp
->c_rsave
= cp
->c_wsave
= -1;
2028 #if MULTIPLE_COPROCS
2031 coproc_close (&sh_coproc
); /* XXX - will require changes for multiple coprocs */
2038 #if MULTIPLE_COPROCS
2043 cp
= &sh_coproc
; /* XXX - will require changes for multiple coprocs */
2044 if (cp
&& (cp
->c_flags
& COPROC_DEAD
))
2045 coproc_dispose (cp
);
2050 coproc_rclose (cp
, fd
)
2054 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
2062 coproc_wclose (cp
, fd
)
2066 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
2074 coproc_checkfd (cp
, fd
)
2081 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
2082 update
= cp
->c_rfd
= -1;
2083 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
2084 update
= cp
->c_wfd
= -1;
2086 coproc_setvars (cp
);
2093 #if MULTIPLE_COPROCS
2096 coproc_checkfd (&sh_coproc
, fd
);
2101 coproc_fdclose (cp
, fd
)
2105 coproc_rclose (cp
, fd
);
2106 coproc_wclose (cp
, fd
);
2107 coproc_setvars (cp
);
2114 cp
->c_rsave
= cp
->c_rfd
;
2115 cp
->c_wsave
= cp
->c_wfd
;
2119 coproc_fdrestore (cp
)
2122 cp
->c_rfd
= cp
->c_rsave
;
2123 cp
->c_wfd
= cp
->c_wsave
;
2127 coproc_pidchk (pid
, status
)
2133 #if MULTIPLE_COPROCS
2134 struct cpelement
*cpe
;
2136 cpe
= cpl_delete (pid
);
2137 cp
= cpe
? cpe
->coproc
: 0;
2139 cp
= getcoprocbypid (pid
);
2144 cp
->c_status
= status
;
2145 cp
->c_flags
|= COPROC_DEAD
;
2146 cp
->c_flags
&= ~COPROC_RUNNING
;
2147 /* Don't dispose the coproc or unset the COPROC_XXX variables because
2148 this is executed in a signal handler context. Wait until coproc_reap
2149 takes care of it. */
2162 #if defined (ARRAY_VARS)
2166 if (cp
->c_name
== 0)
2169 /* We could do more here but right now we only check the name, warn if it's
2170 not a valid identifier, and refuse to create variables with invalid names
2171 if a coproc with such a name is supplied. */
2172 w
.word
= cp
->c_name
;
2174 if (check_identifier (&w
, 1) == 0)
2177 l
= strlen (cp
->c_name
);
2178 namevar
= xmalloc (l
+ 16);
2180 #if defined (ARRAY_VARS)
2181 v
= find_variable (cp
->c_name
);
2183 /* This is the same code as in find_or_make_array_variable */
2186 v
= find_variable_nameref_for_create (cp
->c_name
, 1);
2187 if (v
== INVALID_NAMEREF_VALUE
)
2189 if (v
&& nameref_p (v
))
2192 cp
->c_name
= savestring (nameref_cell (v
));
2193 v
= make_new_array_variable (cp
->c_name
);
2197 if (v
&& (readonly_p (v
) || noassign_p (v
)))
2200 err_readonly (cp
->c_name
);
2204 v
= make_new_array_variable (cp
->c_name
);
2205 if (array_p (v
) == 0)
2206 v
= convert_var_to_array (v
);
2208 t
= itos (cp
->c_rfd
);
2210 v
= bind_array_variable (cp
->c_name
, ind
, t
, 0);
2213 t
= itos (cp
->c_wfd
);
2215 bind_array_variable (cp
->c_name
, ind
, t
, 0);
2218 sprintf (namevar
, "%s_READ", cp
->c_name
);
2219 t
= itos (cp
->c_rfd
);
2220 bind_variable (namevar
, t
, 0);
2222 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
2223 t
= itos (cp
->c_wfd
);
2224 bind_variable (namevar
, t
, 0);
2228 sprintf (namevar
, "%s_PID", cp
->c_name
);
2229 t
= itos (cp
->c_pid
);
2230 bind_variable (namevar
, t
, 0);
2237 coproc_unsetvars (cp
)
2243 if (cp
->c_name
== 0)
2246 l
= strlen (cp
->c_name
);
2247 namevar
= xmalloc (l
+ 16);
2249 sprintf (namevar
, "%s_PID", cp
->c_name
);
2250 unbind_variable_noref (namevar
);
2252 #if defined (ARRAY_VARS)
2253 check_unbind_variable (cp
->c_name
);
2255 sprintf (namevar
, "%s_READ", cp
->c_name
);
2256 unbind_variable (namevar
);
2257 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
2258 unbind_variable (namevar
);
2265 execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
)
2267 int pipe_in
, pipe_out
;
2268 struct fd_bitmap
*fds_to_close
;
2270 int rpipe
[2], wpipe
[2], estat
, invert
;
2276 /* XXX -- can be removed after changes to handle multiple coprocs */
2277 #if !MULTIPLE_COPROCS
2278 if (sh_coproc
.c_pid
!= NO_PID
)
2279 internal_warning (_("execute_coproc: coproc [%d:%s] still exists"), sh_coproc
.c_pid
, sh_coproc
.c_name
);
2280 coproc_init (&sh_coproc
);
2283 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
2284 command_string_index
= 0;
2285 tcmd
= make_command_string (command
);
2287 sh_openpipe ((int *)&rpipe
); /* 0 = parent read, 1 = child write */
2288 sh_openpipe ((int *)&wpipe
); /* 0 = child read, 1 = parent write */
2290 BLOCK_SIGNAL (SIGCHLD
, set
, oset
);
2292 coproc_pid
= make_child (savestring (tcmd
), 1);
2294 if (coproc_pid
== 0)
2299 UNBLOCK_SIGNAL (oset
);
2300 estat
= execute_in_subshell (command
, 1, wpipe
[0], rpipe
[1], fds_to_close
);
2311 /* XXX - possibly run Coproc->name through word expansion? */
2312 cp
= coproc_alloc (command
->value
.Coproc
->name
, coproc_pid
);
2313 cp
->c_rfd
= rpipe
[0];
2314 cp
->c_wfd
= wpipe
[1];
2316 SET_CLOSE_ON_EXEC (cp
->c_rfd
);
2317 SET_CLOSE_ON_EXEC (cp
->c_wfd
);
2319 coproc_setvars (cp
);
2321 UNBLOCK_SIGNAL (oset
);
2324 itrace ("execute_coproc: [%d] %s", coproc_pid
, the_printed_command
);
2327 close_pipes (pipe_in
, pipe_out
);
2328 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2329 unlink_fifo_list ();
2331 stop_pipeline (1, (COMMAND
*)NULL
);
2332 DESCRIBE_PID (coproc_pid
);
2333 run_pending_traps ();
2335 return (invert
? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
2347 /* Catch-all cleanup function for lastpipe code for unwind-protects */
2349 lastpipe_cleanup (s
)
2352 unfreeze_jobs_list ();
2356 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2358 int asynchronous
, pipe_in
, pipe_out
;
2359 struct fd_bitmap
*fds_to_close
;
2361 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
2362 int lstdin
, lastpipe_flag
, lastpipe_jid
;
2364 struct fd_bitmap
*fd_bitmap
;
2367 #if defined (JOB_CONTROL)
2369 BLOCK_CHILD (set
, oset
);
2370 #endif /* JOB_CONTROL */
2372 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2377 while (cmd
&& cmd
->type
== cm_connection
&&
2378 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
2380 /* Make a pipeline between the two commands. */
2381 if (pipe (fildes
) < 0)
2383 sys_error (_("pipe error"));
2384 #if defined (JOB_CONTROL)
2385 terminate_current_pipeline ();
2386 kill_current_pipeline ();
2387 UNBLOCK_CHILD (oset
);
2388 #endif /* JOB_CONTROL */
2389 last_command_exit_value
= EXECUTION_FAILURE
;
2390 /* The unwind-protects installed below will take care
2391 of closing all of the open file descriptors. */
2392 throw_to_top_level ();
2393 return (EXECUTION_FAILURE
); /* XXX */
2396 /* Here is a problem: with the new file close-on-exec
2397 code, the read end of the pipe (fildes[0]) stays open
2398 in the first process, so that process will never get a
2399 SIGPIPE. There is no way to signal the first process
2400 that it should close fildes[0] after forking, so it
2401 remains open. No SIGPIPE is ever sent because there
2402 is still a file descriptor open for reading connected
2403 to the pipe. We take care of that here. This passes
2404 around a bitmap of file descriptors that must be
2405 closed after making a child process in execute_simple_command. */
2407 /* We need fd_bitmap to be at least as big as fildes[0].
2408 If fildes[0] is less than fds_to_close->size, then
2409 use fds_to_close->size. */
2410 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
2411 ? fds_to_close
->size
2414 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
2416 /* Now copy the old information into the new bitmap. */
2417 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
2419 /* And mark the pipe file descriptors to be closed. */
2420 fd_bitmap
->bitmap
[fildes
[0]] = 1;
2422 /* In case there are pipe or out-of-processes errors, we
2423 want all these file descriptors to be closed when
2424 unwind-protects are run, and the storage used for the
2425 bitmaps freed up. */
2426 begin_unwind_frame ("pipe-file-descriptors");
2427 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
2428 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
2430 add_unwind_protect (close
, prev
);
2431 dummyfd
= fildes
[1];
2432 add_unwind_protect (close
, dummyfd
);
2434 #if defined (JOB_CONTROL)
2435 add_unwind_protect (restore_signal_mask
, &oset
);
2436 #endif /* JOB_CONTROL */
2438 if (ignore_return
&& cmd
->value
.Connection
->first
)
2439 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2440 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
2441 prev
, fildes
[1], fd_bitmap
);
2449 dispose_fd_bitmap (fd_bitmap
);
2450 discard_unwind_frame ("pipe-file-descriptors");
2452 cmd
= cmd
->value
.Connection
->second
;
2455 lastpid
= last_made_pid
;
2457 /* Now execute the rightmost command in the pipeline. */
2458 if (ignore_return
&& cmd
)
2459 cmd
->flags
|= CMD_IGNORE_RETURN
;
2463 begin_unwind_frame ("lastpipe-exec");
2465 /* If the `lastpipe' option is set with shopt, and job control is not
2466 enabled, execute the last element of non-async pipelines in the
2467 current shell environment. */
2468 if (lastpipe_opt
&& job_control
== 0 && asynchronous
== 0 && pipe_out
== NO_PIPE
&& prev
> 0)
2470 lstdin
= move_to_high_fd (0, 1, -1);
2473 do_piping (prev
, pipe_out
);
2475 add_unwind_protect (restore_stdin
, lstdin
);
2477 freeze_jobs_list ();
2478 lastpipe_jid
= stop_pipeline (0, (COMMAND
*)NULL
); /* XXX */
2479 add_unwind_protect (lastpipe_cleanup
, lastpipe_jid
);
2482 cmd
->flags
|= CMD_LASTPIPE
;
2485 add_unwind_protect (close
, prev
);
2487 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
2490 restore_stdin (lstdin
);
2495 #if defined (JOB_CONTROL)
2496 UNBLOCK_CHILD (oset
);
2503 #if defined (JOB_CONTROL)
2504 if (INVALID_JOB (lastpipe_jid
) == 0)
2506 append_process (savestring (the_printed_command_except_trap
), dollar_dollar_pid
, exec_result
, lastpipe_jid
);
2507 lstdin
= wait_for (lastpid
);
2510 lstdin
= wait_for_single_pid (lastpid
, 0); /* checks bgpids list */
2512 lstdin
= wait_for (lastpid
);
2515 #if defined (JOB_CONTROL)
2516 /* If wait_for removes the job from the jobs table, use result of last
2517 command as pipeline's exit status as usual. The jobs list can get
2518 frozen and unfrozen at inconvenient times if there are multiple pipelines
2519 running simultaneously. */
2520 if (INVALID_JOB (lastpipe_jid
) == 0)
2521 exec_result
= job_exit_status (lastpipe_jid
);
2522 else if (pipefail_opt
)
2523 exec_result
= exec_result
| lstdin
; /* XXX */
2524 /* otherwise we use exec_result */
2527 unfreeze_jobs_list ();
2530 discard_unwind_frame ("lastpipe-exec");
2532 return (exec_result
);
2536 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2538 int asynchronous
, pipe_in
, pipe_out
;
2539 struct fd_bitmap
*fds_to_close
;
2541 COMMAND
*tc
, *second
;
2542 int ignore_return
, exec_result
, was_error_trap
, invert
;
2543 volatile int save_line_number
;
2545 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2547 switch (command
->value
.Connection
->connector
)
2549 /* Do the first command asynchronously. */
2551 tc
= command
->value
.Connection
->first
;
2553 return (EXECUTION_SUCCESS
);
2556 tc
->flags
|= CMD_IGNORE_RETURN
;
2557 tc
->flags
|= CMD_AMPERSAND
;
2559 /* If this shell was compiled without job control support,
2560 if we are currently in a subshell via `( xxx )', or if job
2561 control is not active then the standard input for an
2562 asynchronous command is forced to /dev/null. */
2563 #if defined (JOB_CONTROL)
2564 if ((subshell_environment
|| !job_control
) && !stdin_redir
)
2567 #endif /* JOB_CONTROL */
2568 tc
->flags
|= CMD_STDIN_REDIR
;
2570 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
2573 if (tc
->flags
& CMD_STDIN_REDIR
)
2574 tc
->flags
&= ~CMD_STDIN_REDIR
;
2576 second
= command
->value
.Connection
->second
;
2580 second
->flags
|= CMD_IGNORE_RETURN
;
2582 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2587 /* Just call execute command on both sides. */
2591 if (command
->value
.Connection
->first
)
2592 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2593 if (command
->value
.Connection
->second
)
2594 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2598 execute_command (command
->value
.Connection
->first
);
2600 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
2601 asynchronous
, pipe_in
, pipe_out
,
2607 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
2608 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
2609 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2611 line_number_for_err_trap
= line_number
; /* XXX - save value? */
2612 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2616 exec_result
= EXECUTION_SUCCESS
;
2620 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
2622 last_command_exit_value
= exec_result
;
2623 save_line_number
= line_number
;
2624 line_number
= line_number_for_err_trap
;
2626 line_number
= save_line_number
;
2629 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
2631 last_command_exit_value
= exec_result
;
2632 run_pending_traps ();
2633 jump_to_top_level (ERREXIT
);
2642 /* If we have something like `a && b &' or `a || b &', run the
2643 && or || stuff in a subshell. Force a subshell and just call
2644 execute_command_internal again. Leave asynchronous on
2645 so that we get a report from the parent shell about the
2647 command
->flags
|= CMD_FORCE_SUBSHELL
;
2648 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
2652 /* Execute the first command. If the result of that is successful
2653 and the connector is AND_AND, or the result is not successful
2654 and the connector is OR_OR, then execute the second command,
2655 otherwise return. */
2658 if (command
->value
.Connection
->first
)
2659 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2661 exec_result
= execute_command (command
->value
.Connection
->first
);
2663 if (((command
->value
.Connection
->connector
== AND_AND
) &&
2664 (exec_result
== EXECUTION_SUCCESS
)) ||
2665 ((command
->value
.Connection
->connector
== OR_OR
) &&
2666 (exec_result
!= EXECUTION_SUCCESS
)))
2668 second
= command
->value
.Connection
->second
;
2669 if (ignore_return
&& second
)
2670 second
->flags
|= CMD_IGNORE_RETURN
;
2672 exec_result
= execute_command (second
);
2678 command_error ("execute_connection", CMDERR_BADCONN
, command
->value
.Connection
->connector
, 0);
2679 jump_to_top_level (DISCARD
);
2680 exec_result
= EXECUTION_FAILURE
;
2686 /* The test used to be only for interactive_shell, but we don't want to report
2687 job status when the shell is not interactive or when job control isn't
2692 if (job_control == 0 || interactive_shell == 0) \
2693 reap_dead_jobs (); \
2697 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2700 execute_for_command (for_command
)
2701 FOR_COM
*for_command
;
2703 register WORD_LIST
*releaser
, *list
;
2706 int retval
, save_line_number
;
2708 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
2711 save_line_number
= line_number
;
2712 if (check_identifier (for_command
->name
, 1) == 0)
2714 if (posixly_correct
&& interactive_shell
== 0)
2716 last_command_exit_value
= EX_BADUSAGE
;
2717 jump_to_top_level (ERREXIT
);
2719 return (EXECUTION_FAILURE
);
2723 identifier
= for_command
->name
->word
;
2725 line_number
= for_command
->line
; /* for expansion error messages */
2726 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
2728 begin_unwind_frame ("for");
2729 add_unwind_protect (dispose_words
, releaser
);
2732 if (lexical_scoping
)
2734 old_value
= copy_variable (find_variable (identifier
));
2736 add_unwind_protect (dispose_variable
, old_value
);
2740 if (for_command
->flags
& CMD_IGNORE_RETURN
)
2741 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2743 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
2747 line_number
= for_command
->line
;
2749 /* Remember what this command looks like, for debugger. */
2750 command_string_index
= 0;
2751 print_for_command_head (for_command
);
2753 if (echo_command_at_execute
)
2754 xtrace_print_for_command_head (for_command
);
2756 /* Save this command unless it's a trap command and we're not running
2758 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2760 FREE (the_printed_command_except_trap
);
2761 the_printed_command_except_trap
= savestring (the_printed_command
);
2764 retval
= run_debug_trap ();
2765 #if defined (DEBUGGER)
2766 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2767 skip the command. */
2768 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2772 this_command_name
= (char *)NULL
;
2773 /* XXX - special ksh93 for command index variable handling */
2774 v
= find_variable_last_nameref (identifier
, 1);
2775 if (v
&& nameref_p (v
))
2777 if (valid_nameref_value (list
->word
->word
, 1) == 0)
2779 sh_invalidid (list
->word
->word
);
2783 v
= bind_variable_value (v
, list
->word
->word
, 0);
2786 v
= bind_variable (identifier
, list
->word
->word
, 0);
2788 if (v
== 0 || readonly_p (v
) || noassign_p (v
))
2790 line_number
= save_line_number
;
2791 if (v
&& readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2793 last_command_exit_value
= EXECUTION_FAILURE
;
2794 jump_to_top_level (FORCE_EOF
);
2798 dispose_words (releaser
);
2799 discard_unwind_frame ("for");
2801 return (EXECUTION_FAILURE
);
2805 if (ifsname (identifier
))
2808 retval
= execute_command (for_command
->action
);
2827 line_number
= save_line_number
;
2830 if (lexical_scoping
)
2833 unbind_variable (identifier
);
2836 SHELL_VAR
*new_value
;
2838 new_value
= bind_variable (identifier
, value_cell(old_value
), 0);
2839 new_value
->attributes
= old_value
->attributes
;
2840 dispose_variable (old_value
);
2845 dispose_words (releaser
);
2846 discard_unwind_frame ("for");
2850 #if defined (ARITH_FOR_COMMAND)
2851 /* Execute an arithmetic for command. The syntax is
2853 for (( init ; step ; test ))
2858 The execution should be exactly equivalent to
2861 while eval \(\( test \)\) ; do
2867 eval_arith_for_expr (l
, okp
)
2875 new = expand_words_no_vars (l
);
2878 if (echo_command_at_execute
)
2879 xtrace_print_arith_cmd (new);
2880 this_command_name
= "(("; /* )) for expression error messages */
2882 command_string_index
= 0;
2883 print_arith_command (new);
2884 if (signal_in_progress (DEBUG_TRAP
) == 0)
2886 FREE (the_printed_command_except_trap
);
2887 the_printed_command_except_trap
= savestring (the_printed_command
);
2890 r
= run_debug_trap ();
2891 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2892 skip the command. */
2893 #if defined (DEBUGGER)
2894 if (debugging_mode
== 0 || r
== EXECUTION_SUCCESS
)
2895 expresult
= evalexp (new->word
->word
, okp
);
2903 expresult
= evalexp (new->word
->word
, okp
);
2905 dispose_words (new);
2917 execute_arith_for_command (arith_for_command
)
2918 ARITH_FOR_COM
*arith_for_command
;
2921 int expok
, body_status
, arith_lineno
, save_lineno
;
2923 body_status
= EXECUTION_SUCCESS
;
2925 save_lineno
= line_number
;
2927 if (arith_for_command
->flags
& CMD_IGNORE_RETURN
)
2928 arith_for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2930 this_command_name
= "(("; /* )) for expression error messages */
2932 /* save the starting line number of the command so we can reset
2933 line_number before executing each expression -- for $LINENO
2934 and the DEBUG trap. */
2935 line_number
= arith_lineno
= arith_for_command
->line
;
2936 if (variable_context
&& interactive_shell
)
2938 line_number
-= function_line_number
;
2939 if (line_number
< 0)
2943 /* Evaluate the initialization expression. */
2944 expresult
= eval_arith_for_expr (arith_for_command
->init
, &expok
);
2947 line_number
= save_lineno
;
2948 return (EXECUTION_FAILURE
);
2953 /* Evaluate the test expression. */
2954 line_number
= arith_lineno
;
2955 expresult
= eval_arith_for_expr (arith_for_command
->test
, &expok
);
2956 line_number
= save_lineno
;
2960 body_status
= EXECUTION_FAILURE
;
2967 /* Execute the body of the arithmetic for command. */
2969 body_status
= execute_command (arith_for_command
->action
);
2972 /* Handle any `break' or `continue' commands executed by the body. */
2986 /* Evaluate the step expression. */
2987 line_number
= arith_lineno
;
2988 expresult
= eval_arith_for_expr (arith_for_command
->step
, &expok
);
2989 line_number
= save_lineno
;
2993 body_status
= EXECUTION_FAILURE
;
2999 line_number
= save_lineno
;
3001 return (body_status
);
3005 #if defined (SELECT_COMMAND)
3006 static int LINES
, COLS
, tabsize
;
3008 #define RP_SPACE ") "
3009 #define RP_SPACE_LEN 2
3011 /* XXX - does not handle numbers > 1000000 at all. */
3012 #define NUMBER_LEN(s) \
3016 : ((s < 10000) ? 4 \
3017 : ((s < 100000) ? 5 \
3024 #if defined (HANDLE_MULTIBYTE)
3030 slen
= mbstowcs (wcstr
, s
, 0);
3033 wcstr
= (wchar_t *)xmalloc (sizeof (wchar_t) * (slen
+ 1));
3034 mbstowcs (wcstr
, s
, slen
+ 1);
3035 wclen
= wcswidth (wcstr
, slen
);
3037 return (wclen
< 0 ? STRLEN(s
) : wclen
);
3039 return (STRLEN (s
));
3044 print_index_and_element (len
, ind
, list
)
3048 register WORD_LIST
*l
;
3053 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
3055 if (l
== 0) /* don't think this can happen */
3057 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
3058 return (displen (l
->word
->word
));
3067 if ((to
/ tabsize
) > (from
/ tabsize
))
3069 putc ('\t', stderr
);
3070 from
+= tabsize
- from
% tabsize
;
3081 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
3083 int list_len
, max_elem_len
, indices_len
;
3085 int ind
, row
, elem_len
, pos
, cols
, rows
;
3086 int first_column_indices_len
, other_indices_len
;
3090 putc ('\n', stderr
);
3094 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
3097 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
3098 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
3106 first_column_indices_len
= NUMBER_LEN (rows
);
3107 other_indices_len
= indices_len
;
3109 for (row
= 0; row
< rows
; row
++)
3115 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
3116 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
3117 elem_len
+= indices_len
+ RP_SPACE_LEN
;
3119 if (ind
>= list_len
)
3121 indent (pos
+ elem_len
, pos
+ max_elem_len
);
3122 pos
+= max_elem_len
;
3124 putc ('\n', stderr
);
3128 /* Print the elements of LIST, one per line, preceded by an index from 1 to
3129 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
3130 If the number is between 1 and LIST_LEN, return that selection. If EOF
3131 is read, return a null string. If a blank line is entered, or an invalid
3132 number is entered, the loop is executed again. */
3134 select_query (list
, list_len
, prompt
, print_menu
)
3140 int max_elem_len
, indices_len
, len
;
3143 char *repl_string
, *t
;
3146 t
= get_string_value ("LINES");
3147 LINES
= (t
&& *t
) ? atoi (t
) : 24;
3149 t
= get_string_value ("COLUMNS");
3150 COLS
= (t
&& *t
) ? atoi (t
) : 80;
3153 t
= get_string_value ("TABSIZE");
3154 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
3162 for (l
= list
; l
; l
= l
->next
)
3164 len
= displen (l
->word
->word
);
3165 if (len
> max_elem_len
)
3168 indices_len
= NUMBER_LEN (list_len
);
3169 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
3174 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
3175 fprintf (stderr
, "%s", prompt
);
3179 if (read_builtin ((WORD_LIST
*)NULL
) != EXECUTION_SUCCESS
)
3182 return ((char *)NULL
);
3184 repl_string
= get_string_value ("REPLY");
3185 if (repl_string
== 0)
3186 return ((char *)NULL
);
3187 if (*repl_string
== 0)
3192 if (legal_number (repl_string
, &reply
) == 0)
3194 if (reply
< 1 || reply
> list_len
)
3197 for (l
= list
; l
&& --reply
; l
= l
->next
)
3199 return (l
->word
->word
); /* XXX - can't be null? */
3203 /* Execute a SELECT command. The syntax is:
3204 SELECT word IN list DO command_list DONE
3205 Only `break' or `return' in command_list will terminate
3208 execute_select_command (select_command
)
3209 SELECT_COM
*select_command
;
3211 WORD_LIST
*releaser
, *list
;
3213 char *identifier
, *ps3_prompt
, *selection
;
3214 int retval
, list_len
, show_menu
, save_line_number
;
3216 if (check_identifier (select_command
->name
, 1) == 0)
3217 return (EXECUTION_FAILURE
);
3219 save_line_number
= line_number
;
3220 line_number
= select_command
->line
;
3222 command_string_index
= 0;
3223 print_select_command_head (select_command
);
3225 if (echo_command_at_execute
)
3226 xtrace_print_select_command_head (select_command
);
3229 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3231 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3234 FREE (the_printed_command_except_trap
);
3235 the_printed_command_except_trap
= savestring (the_printed_command
);
3238 retval
= run_debug_trap ();
3239 #if defined (DEBUGGER)
3240 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3241 skip the command. */
3242 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3243 return (EXECUTION_SUCCESS
);
3247 identifier
= select_command
->name
->word
;
3249 /* command and arithmetic substitution, parameter and variable expansion,
3250 word splitting, pathname expansion, and quote removal. */
3251 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
3252 list_len
= list_length (list
);
3253 if (list
== 0 || list_len
== 0)
3256 dispose_words (list
);
3257 line_number
= save_line_number
;
3258 return (EXECUTION_SUCCESS
);
3261 begin_unwind_frame ("select");
3262 add_unwind_protect (dispose_words
, releaser
);
3264 if (select_command
->flags
& CMD_IGNORE_RETURN
)
3265 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
3267 retval
= EXECUTION_SUCCESS
;
3272 line_number
= select_command
->line
;
3273 ps3_prompt
= get_string_value ("PS3");
3274 if (ps3_prompt
== 0)
3278 selection
= select_query (list
, list_len
, ps3_prompt
, show_menu
);
3282 /* select_query returns EXECUTION_FAILURE if the read builtin
3283 fails, so we want to return failure in this case. */
3284 retval
= EXECUTION_FAILURE
;
3288 v
= bind_variable (identifier
, selection
, 0);
3289 if (v
== 0 || readonly_p (v
) || noassign_p (v
))
3291 if (v
&& readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
3293 last_command_exit_value
= EXECUTION_FAILURE
;
3294 jump_to_top_level (FORCE_EOF
);
3298 dispose_words (releaser
);
3299 discard_unwind_frame ("select");
3301 line_number
= save_line_number
;
3302 return (EXECUTION_FAILURE
);
3306 retval
= execute_command (select_command
->action
);
3324 #if defined (KSH_COMPATIBLE_SELECT)
3326 selection
= get_string_value ("REPLY");
3327 if (selection
&& *selection
== '\0')
3333 line_number
= save_line_number
;
3335 dispose_words (releaser
);
3336 discard_unwind_frame ("select");
3339 #endif /* SELECT_COMMAND */
3341 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
3342 The pattern_list is a linked list of pattern clauses; each clause contains
3343 some patterns to compare word_desc against, and an associated command to
3346 execute_case_command (case_command
)
3347 CASE_COM
*case_command
;
3349 register WORD_LIST
*list
;
3350 WORD_LIST
*wlist
, *es
;
3351 PATTERN_LIST
*clauses
;
3352 char *word
, *pattern
;
3353 int retval
, match
, ignore_return
, save_line_number
;
3355 save_line_number
= line_number
;
3356 line_number
= case_command
->line
;
3358 command_string_index
= 0;
3359 print_case_command_head (case_command
);
3361 if (echo_command_at_execute
)
3362 xtrace_print_case_command_head (case_command
);
3365 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3367 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3370 FREE (the_printed_command_except_trap
);
3371 the_printed_command_except_trap
= savestring (the_printed_command
);
3374 retval
= run_debug_trap();
3375 #if defined (DEBUGGER)
3376 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3377 skip the command. */
3378 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3380 line_number
= save_line_number
;
3381 return (EXECUTION_SUCCESS
);
3385 wlist
= expand_word_unsplit (case_command
->word
, 0);
3386 word
= wlist
? string_list (wlist
) : savestring ("");
3387 dispose_words (wlist
);
3389 retval
= EXECUTION_SUCCESS
;
3390 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
3392 begin_unwind_frame ("case");
3393 add_unwind_protect (xfree
, word
);
3395 #define EXIT_CASE() goto exit_case_command
3397 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
3400 for (list
= clauses
->patterns
; list
; list
= list
->next
)
3402 es
= expand_word_leave_quoted (list
->word
, 0);
3404 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
3405 pattern
= quote_string_for_globbing (es
->word
->word
, QGLOB_CVTNULL
);
3408 pattern
= (char *)xmalloc (1);
3412 /* Since the pattern does not undergo quote removal (as per
3413 Posix.2, section 3.9.4.3), the strmatch () call must be able
3414 to recognize backslashes as escape characters. */
3415 match
= strmatch (pattern
, word
, FNMATCH_EXTFLAG
|FNMATCH_IGNCASE
) != FNM_NOMATCH
;
3424 if (clauses
->action
&& ignore_return
)
3425 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
3426 retval
= execute_command (clauses
->action
);
3428 while ((clauses
->flags
& CASEPAT_FALLTHROUGH
) && (clauses
= clauses
->next
));
3429 if (clauses
== 0 || (clauses
->flags
& CASEPAT_TESTNEXT
) == 0)
3441 discard_unwind_frame ("case");
3442 line_number
= save_line_number
;
3449 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3450 Repeatedly execute action while executing test produces
3451 EXECUTION_SUCCESS. */
3453 execute_while_command (while_command
)
3454 WHILE_COM
*while_command
;
3456 return (execute_while_or_until (while_command
, CMD_WHILE
));
3459 /* UNTIL is just like WHILE except that the test result is negated. */
3461 execute_until_command (while_command
)
3462 WHILE_COM
*while_command
;
3464 return (execute_while_or_until (while_command
, CMD_UNTIL
));
3467 /* The body for both while and until. The only difference between the
3468 two is that the test value is treated differently. TYPE is
3469 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3470 be EXECUTION_SUCCESS if no commands in the body are executed, and
3471 the status of the last command executed in the body otherwise. */
3473 execute_while_or_until (while_command
, type
)
3474 WHILE_COM
*while_command
;
3477 int return_value
, body_status
;
3479 body_status
= EXECUTION_SUCCESS
;
3482 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
3483 if (while_command
->flags
& CMD_IGNORE_RETURN
)
3484 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
3488 return_value
= execute_command (while_command
->test
);
3491 /* Need to handle `break' in the test when we would break out of the
3492 loop. The job control code will set `breaking' to loop_level
3493 when a job in a loop is stopped with SIGTSTP. If the stopped job
3494 is in the loop test, `breaking' will not be reset unless we do
3495 this, and the shell will cease to execute commands. The same holds
3496 true for `continue'. */
3497 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
3505 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
3515 body_status
= execute_command (while_command
->action
);
3533 return (body_status
);
3536 /* IF test THEN command [ELSE command].
3537 IF also allows ELIF in the place of ELSE IF, but
3538 the parser makes *that* stupidity transparent. */
3540 execute_if_command (if_command
)
3543 int return_value
, save_line_number
;
3545 save_line_number
= line_number
;
3546 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
3547 return_value
= execute_command (if_command
->test
);
3548 line_number
= save_line_number
;
3550 if (return_value
== EXECUTION_SUCCESS
)
3554 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
3555 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
3557 return (execute_command (if_command
->true_case
));
3563 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
3564 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
3566 return (execute_command (if_command
->false_case
));
3570 #if defined (DPAREN_ARITHMETIC)
3572 execute_arith_command (arith_command
)
3573 ARITH_COM
*arith_command
;
3575 int expok
, save_line_number
, retval
;
3582 save_line_number
= line_number
;
3583 this_command_name
= "(("; /* )) */
3584 line_number
= arith_command
->line
;
3585 /* If we're in a function, update the line number information. */
3586 if (variable_context
&& interactive_shell
)
3588 line_number
-= function_line_number
;
3589 if (line_number
< 0)
3593 command_string_index
= 0;
3594 print_arith_command (arith_command
->exp
);
3596 if (signal_in_progress (DEBUG_TRAP
) == 0)
3598 FREE (the_printed_command_except_trap
);
3599 the_printed_command_except_trap
= savestring (the_printed_command
);
3602 /* Run the debug trap before each arithmetic command, but do it after we
3603 update the line number information and before we expand the various
3604 words in the expression. */
3605 retval
= run_debug_trap ();
3606 #if defined (DEBUGGER)
3607 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3608 skip the command. */
3609 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3611 line_number
= save_line_number
;
3612 return (EXECUTION_SUCCESS
);
3616 new = expand_words_no_vars (arith_command
->exp
);
3618 /* If we're tracing, make a new word list with `((' at the front and `))'
3619 at the back and print it. */
3620 if (echo_command_at_execute
)
3621 xtrace_print_arith_cmd (new);
3625 exp
= new->next
? string_list (new) : new->word
->word
;
3626 expresult
= evalexp (exp
, &expok
);
3627 line_number
= save_line_number
;
3628 if (exp
!= new->word
->word
)
3630 dispose_words (new);
3639 return (EXECUTION_FAILURE
);
3641 return (expresult
== 0 ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
3643 #endif /* DPAREN_ARITHMETIC */
3645 #if defined (COND_COMMAND)
3647 static char * const nullstr
= "";
3649 /* XXX - can COND ever be NULL when this is called? */
3651 execute_cond_node (cond
)
3654 int result
, invert
, patmatch
, rmatch
, mflags
, ignore
;
3660 invert
= (cond
->flags
& CMD_INVERT_RETURN
);
3661 ignore
= (cond
->flags
& CMD_IGNORE_RETURN
);
3665 cond
->left
->flags
|= CMD_IGNORE_RETURN
;
3667 cond
->right
->flags
|= CMD_IGNORE_RETURN
;
3670 if (cond
->type
== COND_EXPR
)
3671 result
= execute_cond_node (cond
->left
);
3672 else if (cond
->type
== COND_OR
)
3674 result
= execute_cond_node (cond
->left
);
3675 if (result
!= EXECUTION_SUCCESS
)
3676 result
= execute_cond_node (cond
->right
);
3678 else if (cond
->type
== COND_AND
)
3680 result
= execute_cond_node (cond
->left
);
3681 if (result
== EXECUTION_SUCCESS
)
3682 result
= execute_cond_node (cond
->right
);
3684 else if (cond
->type
== COND_UNARY
)
3687 comsub_ignore_return
++;
3688 arg1
= cond_expand_word (cond
->left
->op
, 0);
3690 comsub_ignore_return
--;
3693 if (echo_command_at_execute
)
3694 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, (char *)NULL
);
3695 result
= unary_test (cond
->op
->word
, arg1
) ? EXECUTION_SUCCESS
: EXECUTION_FAILURE
;
3696 if (arg1
!= nullstr
)
3699 else if (cond
->type
== COND_BINARY
)
3702 patmatch
= (((cond
->op
->word
[1] == '=') && (cond
->op
->word
[2] == '\0') &&
3703 (cond
->op
->word
[0] == '!' || cond
->op
->word
[0] == '=')) ||
3704 (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '\0'));
3705 #if defined (COND_REGEXP)
3706 rmatch
= (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '~' &&
3707 cond
->op
->word
[2] == '\0');
3711 comsub_ignore_return
++;
3712 arg1
= cond_expand_word (cond
->left
->op
, 0);
3714 comsub_ignore_return
--;
3718 comsub_ignore_return
++;
3719 arg2
= cond_expand_word (cond
->right
->op
,
3720 (rmatch
&& shell_compatibility_level
> 31) ? 2 : (patmatch
? 1 : 0));
3722 comsub_ignore_return
--;
3726 if (echo_command_at_execute
)
3727 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, arg2
);
3729 #if defined (COND_REGEXP)
3732 mflags
= SHMAT_PWARN
;
3733 #if defined (ARRAY_VARS)
3734 mflags
|= SHMAT_SUBEXP
;
3738 t1
= strescape(arg1
);
3739 t2
= strescape(arg2
);
3740 itrace("execute_cond_node: sh_regmatch on `%s' and `%s'", t1
, t2
);
3745 result
= sh_regmatch (arg1
, arg2
, mflags
);
3748 #endif /* COND_REGEXP */
3753 result
= binary_test (cond
->op
->word
, arg1
, arg2
, TEST_PATMATCH
|TEST_ARITHEXP
|TEST_LOCALE
)
3755 : EXECUTION_FAILURE
;
3758 if (arg1
!= nullstr
)
3760 if (arg2
!= nullstr
)
3765 command_error ("execute_cond_node", CMDERR_BADTYPE
, cond
->type
, 0);
3766 jump_to_top_level (DISCARD
);
3767 result
= EXECUTION_FAILURE
;
3771 result
= (result
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
;
3777 execute_cond_command (cond_command
)
3778 COND_COM
*cond_command
;
3780 int retval
, save_line_number
;
3782 retval
= EXECUTION_SUCCESS
;
3783 save_line_number
= line_number
;
3785 this_command_name
= "[[";
3786 line_number
= cond_command
->line
;
3787 /* If we're in a function, update the line number information. */
3788 if (variable_context
&& interactive_shell
)
3790 line_number
-= function_line_number
;
3791 if (line_number
< 0)
3794 command_string_index
= 0;
3795 print_cond_command (cond_command
);
3797 if (signal_in_progress (DEBUG_TRAP
) == 0)
3799 FREE (the_printed_command_except_trap
);
3800 the_printed_command_except_trap
= savestring (the_printed_command
);
3803 /* Run the debug trap before each conditional command, but do it after we
3804 update the line number information. */
3805 retval
= run_debug_trap ();
3806 #if defined (DEBUGGER)
3807 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3808 skip the command. */
3809 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3811 line_number
= save_line_number
;
3812 return (EXECUTION_SUCCESS
);
3817 debug_print_cond_command (cond_command
);
3820 last_command_exit_value
= retval
= execute_cond_node (cond_command
);
3821 line_number
= save_line_number
;
3824 #endif /* COND_COMMAND */
3834 var
= bind_variable ("_", arg
, 0);
3836 VUNSETATTR (var
, att_exported
);
3839 /* Execute a null command. Fork a subshell if the command uses pipes or is
3840 to be run asynchronously. This handles all the side effects that are
3841 supposed to take place. */
3843 execute_null_command (redirects
, pipe_in
, pipe_out
, async
)
3844 REDIRECT
*redirects
;
3845 int pipe_in
, pipe_out
, async
;
3851 for (forcefork
= 0, rd
= redirects
; rd
; rd
= rd
->next
)
3852 forcefork
+= rd
->rflags
& REDIR_VARASSIGN
;
3854 if (forcefork
|| pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
3856 /* We have a null command, but we really want a subshell to take
3857 care of it. Just fork, do piping and redirections, and exit. */
3858 if (make_child ((char *)NULL
, async
) == 0)
3860 /* Cancel traps, in trap.c. */
3861 restore_original_signals (); /* XXX */
3863 do_piping (pipe_in
, pipe_out
);
3865 #if defined (COPROCESS_SUPPORT)
3869 subshell_environment
= 0;
3871 subshell_environment
|= SUBSHELL_ASYNC
;
3872 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3873 subshell_environment
|= SUBSHELL_PIPE
;
3875 if (do_redirections (redirects
, RX_ACTIVE
) == 0)
3876 exit (EXECUTION_SUCCESS
);
3878 exit (EXECUTION_FAILURE
);
3882 close_pipes (pipe_in
, pipe_out
);
3883 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3884 if (pipe_out
== NO_PIPE
)
3885 unlink_fifo_list ();
3887 return (EXECUTION_SUCCESS
);
3892 /* Even if there aren't any command names, pretend to do the
3893 redirections that are specified. The user expects the side
3894 effects to take place. If the redirections fail, then return
3895 failure. Otherwise, if a command substitution took place while
3896 expanding the command or a redirection, return the value of that
3897 substitution. Otherwise, return EXECUTION_SUCCESS. */
3899 r
= do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
);
3900 cleanup_redirects (redirection_undo_list
);
3901 redirection_undo_list
= (REDIRECT
*)NULL
;
3904 return (EXECUTION_FAILURE
);
3905 else if (last_command_subst_pid
!= NO_PID
)
3906 return (last_command_exit_value
);
3908 return (EXECUTION_SUCCESS
);
3912 /* This is a hack to suppress word splitting for assignment statements
3913 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3915 fix_assignment_words (words
)
3918 WORD_LIST
*w
, *wcmd
;
3920 int assoc
, global
, array
, integer
;
3926 assoc
= global
= array
= integer
= 0;
3928 /* Skip over assignment statements preceding a command name */
3930 for (wcmd
= words
; wcmd
; wcmd
= wcmd
->next
)
3931 if ((wcmd
->word
->flags
& W_ASSIGNMENT
) == 0)
3933 /* Posix (post-2008) says that `command' doesn't change whether
3934 or not the builtin it shadows is a `declaration command', even
3935 though it removes other special builtin properties. In Posix
3936 mode, we skip over one or more instances of `command' and
3937 deal with the next word as the assignment builtin. */
3938 while (posixly_correct
&& wcmd
&& wcmd
->word
&& wcmd
->word
->word
&& STREQ (wcmd
->word
->word
, "command"))
3941 for (w
= wcmd
; w
; w
= w
->next
)
3942 if (w
->word
->flags
& W_ASSIGNMENT
)
3944 /* Lazy builtin lookup, only do it if we find an assignment */
3947 b
= builtin_address_internal (wcmd
->word
->word
, 0);
3948 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3950 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3951 wcmd
->word
->flags
|= W_ASSNBLTIN
;
3953 w
->word
->flags
|= (W_NOSPLIT
|W_NOGLOB
|W_TILDEEXP
|W_ASSIGNARG
);
3954 #if defined (ARRAY_VARS)
3956 w
->word
->flags
|= W_ASSIGNASSOC
;
3958 w
->word
->flags
|= W_ASSIGNARRAY
;
3961 w
->word
->flags
|= W_ASSNGLOBAL
;
3963 /* If we have an assignment builtin that does not create local variables,
3964 make sure we create global variables even if we internally call
3966 if (b
&& ((b
->flags
& (ASSIGNMENT_BUILTIN
|LOCALVAR_BUILTIN
)) == ASSIGNMENT_BUILTIN
))
3967 w
->word
->flags
|= W_ASSNGLOBAL
;
3969 #if defined (ARRAY_VARS)
3970 /* Note that we saw an associative array option to a builtin that takes
3971 assignment statements. This is a bit of a kludge. */
3972 else if (w
->word
->word
[0] == '-' && (strpbrk (w
->word
->word
+1, "Aag") != 0))
3974 else if (w
->word
->word
[0] == '-' && strchr (w
->word
->word
+1, 'g'))
3979 b
= builtin_address_internal (wcmd
->word
->word
, 0);
3980 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3982 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3983 wcmd
->word
->flags
|= W_ASSNBLTIN
;
3985 if ((wcmd
->word
->flags
& W_ASSNBLTIN
) && strchr (w
->word
->word
+1, 'A'))
3987 else if ((wcmd
->word
->flags
& W_ASSNBLTIN
) && strchr (w
->word
->word
+1, 'a'))
3989 if ((wcmd
->word
->flags
& W_ASSNBLTIN
) && strchr (w
->word
->word
+1, 'g'))
3994 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3995 to PATHNAME, is a directory. Used by the autocd code below. */
3997 is_dirname (pathname
)
4003 temp
= search_for_command (pathname
, 0);
4004 ret
= temp
? file_isdir (temp
) : file_isdir (pathname
);
4009 /* The meaty part of all the executions. We have to start hacking the
4010 real execution of commands here. Fork a process, set things up,
4011 execute the command. */
4013 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
4014 SIMPLE_COM
*simple_command
;
4015 int pipe_in
, pipe_out
, async
;
4016 struct fd_bitmap
*fds_to_close
;
4018 WORD_LIST
*words
, *lastword
;
4019 char *command_line
, *lastarg
, *temp
;
4020 int first_word_quoted
, result
, builtin_is_special
, already_forked
, dofork
;
4021 pid_t old_last_async_pid
;
4022 sh_builtin_func_t
*builtin
;
4024 volatile int old_builtin
, old_command_builtin
;
4026 result
= EXECUTION_SUCCESS
;
4027 special_builtin_failed
= builtin_is_special
= 0;
4028 command_line
= (char *)0;
4032 /* If we're in a function, update the line number information. */
4033 if (variable_context
&& interactive_shell
&& sourcelevel
== 0)
4035 line_number
-= function_line_number
;
4036 if (line_number
< 0)
4040 /* Remember what this command line looks like at invocation. */
4041 command_string_index
= 0;
4042 print_simple_command (simple_command
);
4045 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
4047 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
4050 FREE (the_printed_command_except_trap
);
4051 the_printed_command_except_trap
= the_printed_command
? savestring (the_printed_command
) : (char *)0;
4054 /* Run the debug trap before each simple command, but do it after we
4055 update the line number information. */
4056 result
= run_debug_trap ();
4057 #if defined (DEBUGGER)
4058 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4059 skip the command. */
4060 if (debugging_mode
&& result
!= EXECUTION_SUCCESS
)
4061 return (EXECUTION_SUCCESS
);
4065 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
) : 0;
4067 last_command_subst_pid
= NO_PID
;
4068 old_last_async_pid
= last_asynchronous_pid
;
4070 already_forked
= dofork
= 0;
4072 /* If we're in a pipeline or run in the background, set DOFORK so we
4073 make the child early, before word expansion. This keeps assignment
4074 statements from affecting the parent shell's environment when they
4076 dofork
= pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
;
4078 /* Something like `%2 &' should restart job 2 in the background, not cause
4079 the shell to fork here. */
4080 if (dofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&&
4081 simple_command
->words
&& simple_command
->words
->word
&&
4082 simple_command
->words
->word
->word
&&
4083 (simple_command
->words
->word
->word
[0] == '%'))
4088 /* Do this now, because execute_disk_command will do it anyway in the
4089 vast majority of cases. */
4090 maybe_make_export_env ();
4092 /* Don't let a DEBUG trap overwrite the command string to be saved with
4093 the process/job associated with this child. */
4094 if (make_child (savestring (the_printed_command_except_trap
), async
) == 0)
4097 simple_command
->flags
|= CMD_NO_FORK
;
4099 subshell_environment
= SUBSHELL_FORK
; /* XXX */
4100 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4101 subshell_environment
|= SUBSHELL_PIPE
;
4103 subshell_environment
|= SUBSHELL_ASYNC
;
4105 /* We need to do this before piping to handle some really
4106 pathological cases where one of the pipe file descriptors
4109 close_fd_bitmap (fds_to_close
);
4111 /* If we fork because of an input pipe, note input pipe for later to
4112 inhibit async commands from redirecting stdin from /dev/null */
4113 stdin_redir
|= pipe_in
!= NO_PIPE
;
4115 do_piping (pipe_in
, pipe_out
);
4116 pipe_in
= pipe_out
= NO_PIPE
;
4117 #if defined (COPROCESS_SUPPORT)
4121 last_asynchronous_pid
= old_last_async_pid
;
4126 subshell_level
++; /* not for pipes yet */
4130 /* Don't let simple commands that aren't the last command in a
4131 pipeline change $? for the rest of the pipeline (or at all). */
4132 if (pipe_out
!= NO_PIPE
)
4133 result
= last_command_exit_value
;
4134 close_pipes (pipe_in
, pipe_out
);
4135 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4136 /* Close /dev/fd file descriptors in the parent after forking the
4137 last child in a (possibly one-element) pipeline. Defer this
4138 until any running shell function completes. */
4139 if (pipe_out
== NO_PIPE
&& variable_context
== 0) /* XXX */
4140 unlink_fifo_list (); /* XXX */
4142 command_line
= (char *)NULL
; /* don't free this. */
4143 bind_lastarg ((char *)NULL
);
4150 /* If we are re-running this as the result of executing the `command'
4151 builtin, do not expand the command words a second time. */
4152 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
4154 current_fds_to_close
= fds_to_close
;
4155 fix_assignment_words (simple_command
->words
);
4156 /* Pass the ignore return flag down to command substitutions */
4157 if (simple_command
->flags
& CMD_IGNORE_RETURN
) /* XXX */
4158 comsub_ignore_return
++;
4159 words
= expand_words (simple_command
->words
);
4160 if (simple_command
->flags
& CMD_IGNORE_RETURN
)
4161 comsub_ignore_return
--;
4162 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
4165 words
= copy_word_list (simple_command
->words
);
4167 /* It is possible for WORDS not to have anything left in it.
4168 Perhaps all the words consisted of `$foo', and there was
4169 no variable `$foo'. */
4172 this_command_name
= 0;
4173 result
= execute_null_command (simple_command
->redirects
,
4175 already_forked
? 0 : async
);
4180 bind_lastarg ((char *)NULL
);
4181 set_pipestatus_from_exit (result
);
4186 lastarg
= (char *)NULL
;
4188 begin_unwind_frame ("simple-command");
4190 if (echo_command_at_execute
)
4191 xtrace_print_word_list (words
, 1);
4193 builtin
= (sh_builtin_func_t
*)NULL
;
4194 func
= (SHELL_VAR
*)NULL
;
4195 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
4197 /* Posix.2 says special builtins are found before functions. We
4198 don't set builtin_is_special anywhere other than here, because
4199 this path is followed only when the `command' builtin is *not*
4200 being used, and we don't want to exit the shell if a special
4201 builtin executed with `command builtin' fails. `command' is not
4202 a special builtin. */
4203 if (posixly_correct
)
4205 builtin
= find_special_builtin (words
->word
->word
);
4207 builtin_is_special
= 1;
4210 func
= find_function (words
->word
->word
);
4213 /* In POSIX mode, assignment errors in the temporary environment cause a
4214 non-interactive shell to exit. */
4215 if (posixly_correct
&& builtin_is_special
&& interactive_shell
== 0 && tempenv_assign_error
)
4217 last_command_exit_value
= EXECUTION_FAILURE
;
4218 jump_to_top_level (ERREXIT
);
4220 tempenv_assign_error
= 0; /* don't care about this any more */
4222 add_unwind_protect (dispose_words
, words
);
4225 /* Bind the last word in this command to "$_" after execution. */
4226 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
4228 lastarg
= lastword
->word
->word
;
4230 #if defined (JOB_CONTROL)
4231 /* Is this command a job control related thing? */
4232 if (words
->word
->word
[0] == '%' && already_forked
== 0)
4234 this_command_name
= async
? "bg" : "fg";
4235 last_shell_builtin
= this_shell_builtin
;
4236 this_shell_builtin
= builtin_address (this_command_name
);
4237 result
= (*this_shell_builtin
) (words
);
4241 /* One other possibililty. The user may want to resume an existing job.
4242 If they do, find out whether this word is a candidate for a running
4244 if (job_control
&& already_forked
== 0 && async
== 0 &&
4245 !first_word_quoted
&&
4247 words
->word
->word
[0] &&
4248 !simple_command
->redirects
&&
4249 pipe_in
== NO_PIPE
&&
4250 pipe_out
== NO_PIPE
&&
4251 (temp
= get_string_value ("auto_resume")))
4253 int job
, jflags
, started_status
;
4255 jflags
= JM_STOPPED
|JM_FIRSTMATCH
;
4256 if (STREQ (temp
, "exact"))
4258 else if (STREQ (temp
, "substring"))
4259 jflags
|= JM_SUBSTRING
;
4261 jflags
|= JM_PREFIX
;
4262 job
= get_job_by_name (words
->word
->word
, jflags
);
4265 run_unwind_frame ("simple-command");
4266 this_command_name
= "fg";
4267 last_shell_builtin
= this_shell_builtin
;
4268 this_shell_builtin
= builtin_address ("fg");
4270 started_status
= start_job (job
, 1);
4271 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
4274 #endif /* JOB_CONTROL */
4277 /* Remember the name of this command globally. */
4278 this_command_name
= words
->word
->word
;
4282 /* This command could be a shell builtin or a user-defined function.
4283 We have already found special builtins by this time, so we do not
4284 set builtin_is_special. If this is a function or builtin, and we
4285 have pipes, then fork a subshell in here. Otherwise, just execute
4286 the command directly. */
4287 if (func
== 0 && builtin
== 0)
4288 builtin
= find_shell_builtin (this_command_name
);
4290 last_shell_builtin
= this_shell_builtin
;
4291 this_shell_builtin
= builtin
;
4293 if (builtin
|| func
)
4297 old_builtin
= executing_builtin
;
4298 old_command_builtin
= executing_command_builtin
;
4299 unwind_protect_int (executing_builtin
); /* modified in execute_builtin */
4300 unwind_protect_int (executing_command_builtin
); /* ditto */
4304 /* reset_terminating_signals (); */ /* XXX */
4305 /* Reset the signal handlers in the child, but don't free the
4306 trap strings. Set a flag noting that we have to free the
4307 trap strings if we run trap to change a signal disposition. */
4308 reset_signal_handlers ();
4309 subshell_environment
|= SUBSHELL_RESETTRAP
;
4313 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
4314 pipe_in
== NO_PIPE
&&
4315 (stdin_redirects (simple_command
->redirects
) == 0))
4316 async_redirect_stdin ();
4317 setup_async_signals ();
4322 execute_subshell_builtin_or_function
4323 (words
, simple_command
->redirects
, builtin
, func
,
4324 pipe_in
, pipe_out
, async
, fds_to_close
,
4325 simple_command
->flags
);
4330 result
= execute_builtin_or_function
4331 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
4332 simple_command
->flags
);
4335 if (result
> EX_SHERRBASE
)
4342 /* These errors cause non-interactive posix mode shells to exit */
4343 if (posixly_correct
&& builtin_is_special
&& interactive_shell
== 0)
4345 last_command_exit_value
= EXECUTION_FAILURE
;
4346 jump_to_top_level (ERREXIT
);
4349 result
= builtin_status (result
);
4350 if (builtin_is_special
)
4351 special_builtin_failed
= 1;
4353 /* In POSIX mode, if there are assignment statements preceding
4354 a special builtin, they persist after the builtin
4356 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
4357 merge_temporary_env ();
4361 if (result
== EX_USAGE
)
4362 result
= EX_BADUSAGE
;
4363 else if (result
> EX_SHERRBASE
)
4364 result
= EXECUTION_FAILURE
;
4367 set_pipestatus_from_exit (result
);
4373 if (autocd
&& interactive
&& words
->word
&& is_dirname (words
->word
->word
))
4375 words
= make_word_list (make_word ("--"), words
);
4376 words
= make_word_list (make_word ("cd"), words
);
4377 xtrace_print_word_list (words
, 0);
4378 func
= find_function ("cd");
4382 if (command_line
== 0)
4383 command_line
= savestring (the_printed_command_except_trap
? the_printed_command_except_trap
: "");
4385 #if defined (PROCESS_SUBSTITUTION)
4386 /* The old code did not test already_forked and only did this if
4387 subshell_environment&SUBSHELL_COMSUB != 0 (comsubs and procsubs). Other
4388 uses of the no-fork optimization left FIFOs in $TMPDIR */
4389 if (already_forked
== 0 && (simple_command
->flags
& CMD_NO_FORK
) && fifos_pending() > 0)
4390 simple_command
->flags
&= ~CMD_NO_FORK
;
4392 result
= execute_disk_command (words
, simple_command
->redirects
, command_line
,
4393 pipe_in
, pipe_out
, async
, fds_to_close
,
4394 simple_command
->flags
);
4397 bind_lastarg (lastarg
);
4398 FREE (command_line
);
4399 dispose_words (words
);
4402 executing_builtin
= old_builtin
;
4403 executing_command_builtin
= old_command_builtin
;
4405 discard_unwind_frame ("simple-command");
4406 this_command_name
= (char *)NULL
; /* points to freed memory now */
4410 /* Translate the special builtin exit statuses. We don't really need a
4411 function for this; it's a placeholder for future work. */
4413 builtin_status (result
)
4427 r
= EXECUTION_FAILURE
;
4430 r
= EXECUTION_SUCCESS
;
4437 execute_builtin (builtin
, words
, flags
, subshell
)
4438 sh_builtin_func_t
*builtin
;
4440 int flags
, subshell
;
4442 int result
, eval_unwind
, ignexit_flag
, old_e_flag
;
4448 /* The eval builtin calls parse_and_execute, which does not know about
4449 the setting of flags, and always calls the execution functions with
4450 flags that will exit the shell on an error if -e is set. If the
4451 eval builtin is being called, and we're supposed to ignore the exit
4452 value of the command, we turn the -e flag off ourselves and disable
4453 the ERR trap, then restore them when the command completes. This is
4454 also a problem (as below) for the command and source/. builtins. */
4455 if (subshell
== 0 && (flags
& CMD_IGNORE_RETURN
) &&
4456 (builtin
== eval_builtin
|| builtin
== command_builtin
|| builtin
== source_builtin
))
4458 begin_unwind_frame ("eval_builtin");
4459 unwind_protect_int (exit_immediately_on_error
);
4460 unwind_protect_int (builtin_ignoring_errexit
);
4461 error_trap
= TRAP_STRING (ERROR_TRAP
);
4464 error_trap
= savestring (error_trap
);
4465 add_unwind_protect (xfree
, error_trap
);
4466 add_unwind_protect (set_error_trap
, error_trap
);
4467 restore_default_signal (ERROR_TRAP
);
4469 exit_immediately_on_error
= 0;
4470 ignexit_flag
= builtin_ignoring_errexit
;
4471 builtin_ignoring_errexit
= 1;
4477 /* The temporary environment for a builtin is supposed to apply to
4478 all commands executed by that builtin. Currently, this is a
4479 problem only with the `unset', `source' and `eval' builtins.
4480 `mapfile' is a special case because it uses evalstring (same as
4481 eval or source) to run its callbacks. */
4482 isbltinenv
= (builtin
== source_builtin
|| builtin
== eval_builtin
|| builtin
== unset_builtin
|| builtin
== mapfile_builtin
);
4487 begin_unwind_frame ("builtin_env");
4491 push_scope (VC_BLTNENV
, temporary_env
);
4493 add_unwind_protect (pop_scope
, (flags
& CMD_COMMAND_BUILTIN
) ? 0 : "1");
4494 temporary_env
= (HASH_TABLE
*)NULL
;
4498 if (subshell
== 0 && builtin
== eval_builtin
)
4500 if (evalnest_max
> 0 && evalnest
>= evalnest_max
)
4502 internal_error (_("eval: maximum eval nesting level exceeded (%d)"), evalnest
);
4504 jump_to_top_level (DISCARD
);
4506 unwind_protect_int (evalnest
);
4507 /* The test for subshell == 0 above doesn't make a difference */
4508 evalnest
++; /* execute_subshell_builtin_or_function sets this to 0 */
4510 else if (subshell
== 0 && builtin
== source_builtin
)
4512 if (sourcenest_max
> 0 && sourcenest
>= sourcenest_max
)
4514 internal_error (_("%s: maximum source nesting level exceeded (%d)"), this_command_name
, sourcenest
);
4516 jump_to_top_level (DISCARD
);
4518 unwind_protect_int (sourcenest
);
4519 /* The test for subshell == 0 above doesn't make a difference */
4520 sourcenest
++; /* execute_subshell_builtin_or_function sets this to 0 */
4523 /* `return' does a longjmp() back to a saved environment in execute_function.
4524 If a variable assignment list preceded the command, and the shell is
4525 running in POSIX mode, we need to merge that into the shell_variables
4526 table, since `return' is a POSIX special builtin. */
4527 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
4529 begin_unwind_frame ("return_temp_env");
4530 add_unwind_protect (merge_temporary_env
, (char *)NULL
);
4533 executing_builtin
++;
4534 executing_command_builtin
|= builtin
== command_builtin
;
4535 result
= ((*builtin
) (words
->next
));
4537 /* This shouldn't happen, but in case `return' comes back instead of
4538 longjmp'ing, we need to unwind. */
4539 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
4540 discard_unwind_frame ("return_temp_env");
4542 if (subshell
== 0 && isbltinenv
)
4543 run_unwind_frame ("builtin_env");
4547 builtin_ignoring_errexit
= ignexit_flag
;
4548 exit_immediately_on_error
= builtin_ignoring_errexit
? 0 : errexit_flag
;
4551 set_error_trap (error_trap
);
4554 discard_unwind_frame ("eval_builtin");
4561 maybe_restore_getopt_state (gs
)
4562 sh_getopt_state_t
*gs
;
4566 /* If we have a local copy of OPTIND and it's at the right (current)
4567 context, then we restore getopt's internal state. If not, we just
4568 let it go. We know there is a local OPTIND if gs->gs_flags & 1.
4569 This is set below in execute_function() before the context is run. */
4570 if (gs
->gs_flags
& 1)
4571 sh_getopt_restore_istate (gs
);
4576 #if defined (ARRAY_VARS)
4578 restore_funcarray_state (fa
)
4579 struct func_array_state
*fa
;
4584 array_pop (fa
->source_a
);
4585 array_pop (fa
->lineno_a
);
4587 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv
, funcname_a
);
4588 if (nfv
== fa
->funcname_v
)
4589 array_pop (funcname_a
);
4596 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
4600 struct fd_bitmap
*fds_to_close
;
4601 int async
, subshell
;
4603 int return_val
, result
;
4604 COMMAND
*tc
, *fc
, *save_current
;
4605 char *debug_trap
, *error_trap
, *return_trap
;
4606 #if defined (ARRAY_VARS)
4607 SHELL_VAR
*funcname_v
, *bash_source_v
, *bash_lineno_v
;
4609 volatile ARRAY
*bash_source_a
;
4610 volatile ARRAY
*bash_lineno_a
;
4611 struct func_array_state
*fa
;
4613 FUNCTION_DEF
*shell_fn
;
4615 sh_getopt_state_t
*gs
;
4620 if (funcnest_max
> 0 && funcnest
>= funcnest_max
)
4622 internal_error (_("%s: maximum function nesting level exceeded (%d)"), var
->name
, funcnest
);
4623 funcnest
= 0; /* XXX - should we reset it somewhere else? */
4624 jump_to_top_level (DISCARD
);
4627 #if defined (ARRAY_VARS)
4628 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v
, funcname_a
);
4629 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v
, bash_source_a
);
4630 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v
, bash_lineno_a
);
4633 tc
= (COMMAND
*)copy_command (function_cell (var
));
4634 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
4635 tc
->flags
|= CMD_IGNORE_RETURN
;
4637 gs
= sh_getopt_save_istate ();
4640 begin_unwind_frame ("function_calling");
4641 push_context (var
->name
, subshell
, temporary_env
);
4642 /* This has to be before the pop_context(), because the unwinding of
4643 local variables may cause the restore of a local declaration of
4644 OPTIND to force a getopts state reset. */
4645 add_unwind_protect (maybe_restore_getopt_state
, gs
);
4646 add_unwind_protect (pop_context
, (char *)NULL
);
4647 unwind_protect_int (line_number
);
4648 unwind_protect_int (line_number_for_err_trap
);
4649 unwind_protect_int (function_line_number
);
4650 unwind_protect_int (return_catch_flag
);
4651 unwind_protect_jmp_buf (return_catch
);
4652 add_unwind_protect (dispose_command
, (char *)tc
);
4653 unwind_protect_pointer (this_shell_function
);
4654 unwind_protect_int (funcnest
);
4655 unwind_protect_int (loop_level
);
4658 push_context (var
->name
, subshell
, temporary_env
); /* don't unwind-protect for subshells */
4660 temporary_env
= (HASH_TABLE
*)NULL
;
4662 this_shell_function
= var
;
4663 make_funcname_visible (1);
4665 debug_trap
= TRAP_STRING(DEBUG_TRAP
);
4666 error_trap
= TRAP_STRING(ERROR_TRAP
);
4667 return_trap
= TRAP_STRING(RETURN_TRAP
);
4669 /* The order of the unwind protects for debug_trap, error_trap and
4670 return_trap is important here! unwind-protect commands are run
4671 in reverse order of registration. If this causes problems, take
4672 out the xfree unwind-protect calls and live with the small memory leak. */
4674 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4675 if the function has the trace attribute set, it inherits the DEBUG trap */
4676 if (debug_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
4680 debug_trap
= savestring (debug_trap
);
4681 add_unwind_protect (xfree
, debug_trap
);
4682 add_unwind_protect (maybe_set_debug_trap
, debug_trap
);
4684 restore_default_signal (DEBUG_TRAP
);
4687 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4688 if (error_trap
&& error_trace_mode
== 0)
4692 error_trap
= savestring (error_trap
);
4693 add_unwind_protect (xfree
, error_trap
);
4694 add_unwind_protect (maybe_set_error_trap
, error_trap
);
4696 restore_default_signal (ERROR_TRAP
);
4699 /* Shell functions inherit the RETURN trap if function tracing is on
4700 globally or on individually for this function. */
4702 if (return_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
4704 if (return_trap
&& (signal_in_progress (DEBUG_TRAP
) || ((trace_p (var
) == 0) && function_trace_mode
== 0)))
4709 return_trap
= savestring (return_trap
);
4710 add_unwind_protect (xfree
, return_trap
);
4711 add_unwind_protect (maybe_set_return_trap
, return_trap
);
4713 restore_default_signal (RETURN_TRAP
);
4717 #if defined (ARRAY_VARS)
4718 /* This is quite similar to the code in shell.c and elsewhere. */
4719 shell_fn
= find_function_def (this_shell_function
->name
);
4720 sfile
= shell_fn
? shell_fn
->source_file
: "";
4721 array_push ((ARRAY
*)funcname_a
, this_shell_function
->name
);
4723 array_push ((ARRAY
*)bash_source_a
, sfile
);
4724 t
= itos (executing_line_number ());
4725 array_push ((ARRAY
*)bash_lineno_a
, t
);
4729 #if defined (ARRAY_VARS)
4730 fa
= (struct func_array_state
*)xmalloc (sizeof (struct func_array_state
));
4731 fa
->source_a
= (ARRAY
*)bash_source_a
;
4732 fa
->source_v
= bash_source_v
;
4733 fa
->lineno_a
= (ARRAY
*)bash_lineno_a
;
4734 fa
->lineno_v
= bash_lineno_v
;
4735 fa
->funcname_a
= (ARRAY
*)funcname_a
;
4736 fa
->funcname_v
= funcname_v
;
4738 add_unwind_protect (restore_funcarray_state
, fa
);
4741 /* The temporary environment for a function is supposed to apply to
4742 all commands executed within the function body. */
4744 remember_args (words
->next
, 1);
4746 /* Update BASH_ARGV and BASH_ARGC */
4749 push_args (words
->next
);
4751 add_unwind_protect (pop_args
, 0);
4754 /* Number of the line on which the function body starts. */
4755 line_number
= function_line_number
= tc
->line
;
4757 #if defined (JOB_CONTROL)
4759 stop_pipeline (async
, (COMMAND
*)NULL
);
4762 if (shell_compatibility_level
> 43)
4767 from_return_trap
= 0;
4769 return_catch_flag
++;
4770 return_val
= setjmp_nosigs (return_catch
);
4774 result
= return_catch_value
;
4775 /* Run the RETURN trap in the function's context. */
4776 save_current
= currently_executing_command
;
4777 if (from_return_trap
== 0)
4779 currently_executing_command
= save_current
;
4783 /* Run the debug trap here so we can trap at the start of a function's
4784 execution rather than the execution of the body's first command. */
4785 showing_function_line
= 1;
4786 save_current
= currently_executing_command
;
4787 result
= run_debug_trap ();
4788 #if defined (DEBUGGER)
4789 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4790 skip the command. */
4791 if (debugging_mode
== 0 || result
== EXECUTION_SUCCESS
)
4793 showing_function_line
= 0;
4794 currently_executing_command
= save_current
;
4795 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
4797 /* Run the RETURN trap in the function's context */
4798 save_current
= currently_executing_command
;
4800 currently_executing_command
= save_current
;
4803 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
4805 save_current
= currently_executing_command
;
4807 currently_executing_command
= save_current
;
4809 showing_function_line
= 0;
4812 /* If we have a local copy of OPTIND, note it in the saved getopts state. */
4813 gv
= find_variable ("OPTIND");
4814 if (gv
&& gv
->context
== variable_context
)
4818 run_unwind_frame ("function_calling");
4819 #if defined (ARRAY_VARS)
4822 restore_funcarray_state (fa
);
4823 /* Restore BASH_ARGC and BASH_ARGV */
4829 if (variable_context
== 0 || this_shell_function
== 0)
4831 make_funcname_visible (0);
4832 #if defined (PROCESS_SUBSTITUTION)
4833 unlink_fifo_list ();
4840 /* A convenience routine for use by other parts of the shell to execute
4841 a particular shell function. */
4843 execute_shell_function (var
, words
)
4848 struct fd_bitmap
*bitmap
;
4850 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
4851 begin_unwind_frame ("execute-shell-function");
4852 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
4854 ret
= execute_function (var
, words
, 0, bitmap
, 0, 0);
4856 dispose_fd_bitmap (bitmap
);
4857 discard_unwind_frame ("execute-shell-function");
4862 /* Execute a shell builtin or function in a subshell environment. This
4863 routine does not return; it only calls exit(). If BUILTIN is non-null,
4864 it points to a function to call to execute a shell builtin; otherwise
4865 VAR points at the body of a function to execute. WORDS is the arguments
4866 to the command, REDIRECTS specifies redirections to perform before the
4867 command is executed. */
4869 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
4870 pipe_in
, pipe_out
, async
, fds_to_close
,
4873 REDIRECT
*redirects
;
4874 sh_builtin_func_t
*builtin
;
4876 int pipe_in
, pipe_out
, async
;
4877 struct fd_bitmap
*fds_to_close
;
4880 int result
, r
, funcvalue
;
4881 #if defined (JOB_CONTROL)
4884 jobs_hack
= (builtin
== jobs_builtin
) &&
4885 ((subshell_environment
& SUBSHELL_ASYNC
) == 0 || pipe_out
!= NO_PIPE
);
4888 /* A subshell is neither a login shell nor interactive. */
4889 login_shell
= interactive
= 0;
4890 if (builtin
== eval_builtin
)
4892 else if (builtin
== source_builtin
)
4896 subshell_environment
|= SUBSHELL_ASYNC
;
4897 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4898 subshell_environment
|= SUBSHELL_PIPE
;
4900 maybe_make_export_env (); /* XXX - is this needed? */
4902 #if defined (JOB_CONTROL)
4903 /* Eradicate all traces of job control after we fork the subshell, so
4904 all jobs begun by this subshell are in the same process group as
4905 the shell itself. */
4907 /* Allow the output of `jobs' to be piped. */
4909 kill_current_pipeline ();
4911 without_job_control ();
4913 set_sigchld_handler ();
4914 #endif /* JOB_CONTROL */
4916 set_sigint_handler ();
4919 close_fd_bitmap (fds_to_close
);
4921 do_piping (pipe_in
, pipe_out
);
4923 if (do_redirections (redirects
, RX_ACTIVE
) != 0)
4924 exit (EXECUTION_FAILURE
);
4928 /* Give builtins a place to jump back to on failure,
4929 so we don't go back up to main(). */
4930 result
= setjmp_nosigs (top_level
);
4932 /* Give the return builtin a place to jump to when executed in a subshell
4935 if (return_catch_flag
&& builtin
== return_builtin
)
4936 funcvalue
= setjmp_nosigs (return_catch
);
4938 if (result
== EXITPROG
)
4939 exit (last_command_exit_value
);
4941 exit (EXECUTION_FAILURE
);
4943 exit (return_catch_value
);
4946 r
= execute_builtin (builtin
, words
, flags
, 1);
4955 r
= execute_function (var
, words
, flags
, fds_to_close
, async
, 1);
4961 /* Execute a builtin or function in the current shell context. If BUILTIN
4962 is non-null, it is the builtin command to execute, otherwise VAR points
4963 to the body of a function. WORDS are the command's arguments, REDIRECTS
4964 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4965 file descriptors to close.
4967 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4968 not undone before this function returns. */
4970 execute_builtin_or_function (words
, builtin
, var
, redirects
,
4971 fds_to_close
, flags
)
4973 sh_builtin_func_t
*builtin
;
4975 REDIRECT
*redirects
;
4976 struct fd_bitmap
*fds_to_close
;
4980 REDIRECT
*saved_undo_list
;
4981 #if defined (PROCESS_SUBSTITUTION)
4982 int ofifo
, nfifo
, osize
;
4986 #if defined (PROCESS_SUBSTITUTION)
4987 begin_unwind_frame ("saved_fifos");
4988 /* If we return, we longjmp and don't get a chance to restore the old
4989 fifo list, so we add an unwind protect to free it */
4990 ofifo
= num_fifos ();
4991 ofifo_list
= copy_fifo_list (&osize
);
4993 add_unwind_protect (xfree
, ofifo_list
);
4996 if (do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
4998 cleanup_redirects (redirection_undo_list
);
4999 redirection_undo_list
= (REDIRECT
*)NULL
;
5000 dispose_exec_redirects ();
5001 #if defined (PROCESS_SUBSTITUTION)
5004 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
5007 saved_undo_list
= redirection_undo_list
;
5009 /* Calling the "exec" builtin changes redirections forever. */
5010 if (builtin
== exec_builtin
)
5012 dispose_redirects (saved_undo_list
);
5013 saved_undo_list
= exec_redirection_undo_list
;
5014 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
5017 dispose_exec_redirects ();
5019 if (saved_undo_list
)
5021 begin_unwind_frame ("saved-redirects");
5022 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
5025 redirection_undo_list
= (REDIRECT
*)NULL
;
5028 result
= execute_builtin (builtin
, words
, flags
, 0);
5030 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
5032 /* We do this before undoing the effects of any redirections. */
5035 if (ferror (stdout
))
5038 /* If we are executing the `command' builtin, but this_shell_builtin is
5039 set to `exec_builtin', we know that we have something like
5040 `command exec [redirection]', since otherwise `exec' would have
5041 overwritten the shell and we wouldn't get here. In this case, we
5042 want to behave as if the `command' builtin had not been specified
5043 and preserve the redirections. */
5044 if (builtin
== command_builtin
&& this_shell_builtin
== exec_builtin
)
5049 if (saved_undo_list
)
5051 dispose_redirects (saved_undo_list
);
5054 redirection_undo_list
= exec_redirection_undo_list
;
5055 saved_undo_list
= exec_redirection_undo_list
= (REDIRECT
*)NULL
;
5057 discard_unwind_frame ("saved-redirects");
5060 if (saved_undo_list
)
5062 redirection_undo_list
= saved_undo_list
;
5063 discard_unwind_frame ("saved-redirects");
5066 if (redirection_undo_list
)
5068 cleanup_redirects (redirection_undo_list
);
5069 redirection_undo_list
= (REDIRECT
*)NULL
;
5072 #if defined (PROCESS_SUBSTITUTION)
5073 /* Close any FIFOs created by this builtin or function. */
5074 nfifo
= num_fifos ();
5076 close_new_fifos (ofifo_list
, osize
);
5079 discard_unwind_frame ("saved_fifos");
5086 setup_async_signals ()
5088 #if defined (__BEOS__)
5089 set_signal_handler (SIGHUP
, SIG_IGN
); /* they want csh-like behavior */
5092 #if defined (JOB_CONTROL)
5093 if (job_control
== 0)
5096 /* Make sure we get the original signal dispositions now so we don't
5097 confuse the trap builtin later if the subshell tries to use it to
5098 reset SIGINT/SIGQUIT. Don't call set_signal_ignored; that sets
5099 the value of original_signals to SIG_IGN. Posix interpretation 751. */
5100 get_original_signal (SIGINT
);
5101 set_signal_handler (SIGINT
, SIG_IGN
);
5103 get_original_signal (SIGQUIT
);
5104 set_signal_handler (SIGQUIT
, SIG_IGN
);
5108 /* Execute a simple command that is hopefully defined in a disk file
5113 3) look up the command
5116 6) If the execve failed, see if the file has executable mode set.
5117 If so, and it isn't a directory, then execute its contents as
5120 Note that the filename hashing stuff has to take place up here,
5121 in the parent. This is probably why the Bourne style shells
5122 don't handle it, since that would require them to go through
5123 this gnarly hair, for no good reason.
5125 NOTE: callers expect this to fork or exit(). */
5127 /* Name of a shell function to call when a command name is not found. */
5128 #ifndef NOTFOUND_HOOK
5129 # define NOTFOUND_HOOK "command_not_found_handle"
5133 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
5134 async
, fds_to_close
, cmdflags
)
5136 REDIRECT
*redirects
;
5138 int pipe_in
, pipe_out
, async
;
5139 struct fd_bitmap
*fds_to_close
;
5142 char *pathname
, *command
, **args
;
5143 int nofork
, stdpath
, result
;
5148 stdpath
= (cmdflags
& CMD_STDPATH
); /* use command -p path */
5149 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
5150 pathname
= words
->word
->word
;
5152 result
= EXECUTION_SUCCESS
;
5153 #if defined (RESTRICTED_SHELL)
5154 command
= (char *)NULL
;
5155 if (restricted
&& mbschr (pathname
, '/'))
5157 internal_error (_("%s: restricted: cannot specify `/' in command names"),
5159 result
= last_command_exit_value
= EXECUTION_FAILURE
;
5161 /* If we're not going to fork below, we must already be in a child
5162 process or a context in which it's safe to call exit(2). */
5163 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
5164 exit (last_command_exit_value
);
5168 #endif /* RESTRICTED_SHELL */
5170 command
= search_for_command (pathname
, CMDSRCH_HASH
|(stdpath
? CMDSRCH_STDPATH
: 0));
5174 maybe_make_export_env ();
5175 put_command_name_into_env (command
);
5178 /* We have to make the child before we check for the non-existence
5179 of COMMAND, since we want the error messages to be redirected. */
5180 /* If we can get away without forking and there are no pipes to deal with,
5181 don't bother to fork, just directly exec the command. */
5182 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
5185 pid
= make_child (savestring (command_line
), async
);
5189 int old_interactive
;
5191 reset_terminating_signals (); /* XXX */
5192 /* Cancel traps, in trap.c. */
5193 restore_original_signals ();
5197 /* restore_original_signals may have undone the work done
5198 by make_child to ensure that SIGINT and SIGQUIT are ignored
5199 in asynchronous children. */
5202 if ((cmdflags
& CMD_STDIN_REDIR
) &&
5203 pipe_in
== NO_PIPE
&&
5204 (stdin_redirects (redirects
) == 0))
5205 async_redirect_stdin ();
5206 setup_async_signals ();
5209 /* This functionality is now provided by close-on-exec of the
5210 file descriptors manipulated by redirection and piping.
5211 Some file descriptors still need to be closed in all children
5212 because of the way bash does pipes; fds_to_close is a
5213 bitmap of all such file descriptors. */
5215 close_fd_bitmap (fds_to_close
);
5217 do_piping (pipe_in
, pipe_out
);
5219 old_interactive
= interactive
;
5223 subshell_environment
|= SUBSHELL_FORK
; /* XXX - was just = */
5225 if (redirects
&& (do_redirections (redirects
, RX_ACTIVE
) != 0))
5227 #if defined (PROCESS_SUBSTITUTION)
5228 /* Try to remove named pipes that may have been created as the
5229 result of redirections. */
5230 unlink_fifo_list ();
5231 #endif /* PROCESS_SUBSTITUTION */
5232 exit (EXECUTION_FAILURE
);
5236 interactive
= old_interactive
;
5240 hookf
= find_function (NOTFOUND_HOOK
);
5243 /* Make sure filenames are displayed using printable characters */
5244 pathname
= printable_filename (pathname
, 0);
5245 internal_error (_("%s: command not found"), pathname
);
5246 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
5249 #if defined (JOB_CONTROL)
5250 /* May need to reinitialize more of the job control state here. */
5251 kill_current_pipeline ();
5254 wl
= make_word_list (make_word (NOTFOUND_HOOK
), words
);
5255 exit (execute_shell_function (hookf
, wl
));
5260 /* Execve expects the command name to be in args[0]. So we
5261 leave it there, in the same format that the user used to
5263 args
= strvec_from_word_list (words
, 0, 0, (int *)NULL
);
5264 exit (shell_execve (command
, args
, export_env
));
5271 /* Make sure that the pipes are closed in the parent. */
5272 close_pipes (pipe_in
, pipe_out
);
5273 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5274 if (variable_context
== 0)
5275 unlink_fifo_list ();
5282 /* CPP defines to decide whether a particular index into the #! line
5283 corresponds to a valid interpreter name or argument character, or
5284 whitespace. The MSDOS define is to allow \r to be treated the same
5287 #if !defined (MSDOS)
5288 # define STRINGCHAR(ind) \
5289 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
5290 # define WHITECHAR(ind) \
5291 (ind < sample_len && whitespace (sample[ind]))
5293 # define STRINGCHAR(ind) \
5294 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
5295 # define WHITECHAR(ind) \
5296 (ind < sample_len && whitespace (sample[ind]))
5300 getinterp (sample
, sample_len
, endp
)
5302 int sample_len
, *endp
;
5308 /* Find the name of the interpreter to exec. */
5309 for (i
= 2; i
< sample_len
&& whitespace (sample
[i
]); i
++)
5312 for (start
= i
; STRINGCHAR(i
); i
++)
5315 execname
= substring (sample
, start
, i
);
5322 #if !defined (HAVE_HASH_BANG_EXEC)
5323 /* If the operating system on which we're running does not handle
5324 the #! executable format, then help out. SAMPLE is the text read
5325 from the file, SAMPLE_LEN characters. COMMAND is the name of
5326 the script; it and ARGS, the arguments given by the user, will
5327 become arguments to the specified interpreter. ENV is the environment
5328 to pass to the interpreter.
5330 The word immediately following the #! is the interpreter to execute.
5331 A single argument to the interpreter is allowed. */
5334 execute_shell_script (sample
, sample_len
, command
, args
, env
)
5340 char *execname
, *firstarg
;
5341 int i
, start
, size_increment
, larry
;
5343 /* Find the name of the interpreter to exec. */
5344 execname
= getinterp (sample
, sample_len
, &i
);
5347 /* Now the argument, if any. */
5348 for (firstarg
= (char *)NULL
, start
= i
; WHITECHAR(i
); i
++)
5351 /* If there is more text on the line, then it is an argument for the
5356 for (start
= i
; STRINGCHAR(i
); i
++)
5358 firstarg
= substring ((char *)sample
, start
, i
);
5362 larry
= strvec_len (args
) + size_increment
;
5363 args
= strvec_resize (args
, larry
+ 1);
5365 for (i
= larry
- 1; i
; i
--)
5366 args
[i
] = args
[i
- size_increment
];
5377 args
[larry
] = (char *)NULL
;
5379 return (shell_execve (execname
, args
, env
));
5384 #endif /* !HAVE_HASH_BANG_EXEC */
5387 initialize_subshell ()
5390 /* Forget about any aliases that we knew of. We are in a subshell. */
5391 delete_all_aliases ();
5394 #if defined (HISTORY)
5395 /* Forget about the history lines we have read. This is a non-interactive
5397 history_lines_this_session
= 0;
5400 /* Forget about the way job control was working. We are in a subshell. */
5401 without_job_control ();
5403 #if defined (JOB_CONTROL)
5404 set_sigchld_handler ();
5406 #endif /* JOB_CONTROL */
5408 /* Reset the values of the shell flags and options. */
5409 reset_shell_flags ();
5410 reset_shell_options ();
5411 reset_shopt_options ();
5413 /* Zero out builtin_env, since this could be a shell script run from a
5414 sourced file with a temporary environment supplied to the `source/.'
5415 builtin. Such variables are not supposed to be exported (empirical
5416 testing with sh and ksh). Just throw it away; don't worry about a
5418 if (vc_isbltnenv (shell_variables
))
5419 shell_variables
= shell_variables
->down
;
5421 clear_unwind_protect_list (0);
5422 /* XXX -- are there other things we should be resetting here? */
5423 parse_and_execute_level
= 0; /* nothing left to restore it */
5425 /* We're no longer inside a shell function. */
5426 variable_context
= return_catch_flag
= funcnest
= evalnest
= sourcenest
= 0;
5428 executing_list
= 0; /* XXX */
5430 /* If we're not interactive, close the file descriptor from which we're
5431 reading the current shell script. */
5432 if (interactive_shell
== 0)
5433 unset_bash_input (0);
5436 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
5437 # define SETOSTYPE(x) __setostype(x)
5439 # define SETOSTYPE(x)
5442 #define HASH_BANG_BUFSIZ 128
5444 #define READ_SAMPLE_BUF(file, buf, len) \
5447 fd = open(file, O_RDONLY); \
5450 len = read (fd, buf, HASH_BANG_BUFSIZ); \
5458 /* Call execve (), handling interpreting shell scripts, and handling
5461 shell_execve (command
, args
, env
)
5466 char sample
[HASH_BANG_BUFSIZ
];
5469 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
5470 execve (command
, args
, env
);
5471 i
= errno
; /* error from execve() */
5475 /* If we get to this point, then start checking out the file.
5476 Maybe it is something we can hack ourselves. */
5479 /* make sure this is set correctly for file_error/report_error */
5480 last_command_exit_value
= (i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
; /* XXX Posix.2 says that exit status is 126 */
5481 if (file_isdir (command
))
5482 #if defined (EISDIR)
5483 internal_error (_("%s: %s"), command
, strerror (EISDIR
));
5485 internal_error (_("%s: is a directory"), command
);
5487 else if (executable_file (command
) == 0)
5490 file_error (command
);
5492 /* errors not involving the path argument to execve. */
5493 else if (i
== E2BIG
|| i
== ENOMEM
)
5496 file_error (command
);
5500 /* The file has the execute bits set, but the kernel refuses to
5501 run it for some reason. See why. */
5502 #if defined (HAVE_HASH_BANG_EXEC)
5503 READ_SAMPLE_BUF (command
, sample
, sample_len
);
5505 sample
[sample_len
- 1] = '\0';
5506 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
5511 interp
= getinterp (sample
, sample_len
, (int *)NULL
);
5512 ilen
= strlen (interp
);
5514 if (interp
[ilen
- 1] == '\r')
5516 interp
= xrealloc (interp
, ilen
+ 2);
5517 interp
[ilen
- 1] = '^';
5519 interp
[ilen
+ 1] = '\0';
5521 sys_error (_("%s: %s: bad interpreter"), command
, interp
? interp
: "");
5527 file_error (command
);
5529 return (last_command_exit_value
);
5532 /* This file is executable.
5533 If it begins with #!, then help out people with losing operating
5534 systems. Otherwise, check to see if it is a binary file by seeing
5535 if the contents of the first line (or up to 80 characters) are in the
5536 ASCII set. If it's a text file, execute the contents as shell commands,
5537 otherwise return 126 (EX_BINARY_FILE). */
5538 READ_SAMPLE_BUF (command
, sample
, sample_len
);
5540 if (sample_len
== 0)
5541 return (EXECUTION_SUCCESS
);
5543 /* Is this supposed to be an executable script?
5544 If so, the format of the line is "#! interpreter [argument]".
5545 A single argument is allowed. The BSD kernel restricts
5546 the length of the entire line to 32 characters (32 bytes
5547 being the size of the BSD exec header), but we allow 80
5551 #if !defined (HAVE_HASH_BANG_EXEC)
5552 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
5553 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
5556 if (check_binary_file (sample
, sample_len
))
5558 internal_error (_("%s: cannot execute binary file: %s"), command
, strerror (i
));
5560 return (EX_BINARY_FILE
);
5564 /* We have committed to attempting to execute the contents of this file
5565 as shell commands. */
5568 initialize_subshell ();
5570 set_sigint_handler ();
5572 /* Insert the name of this shell into the argument list. */
5573 larray
= strvec_len (args
) + 1;
5574 args
= strvec_resize (args
, larray
+ 1);
5576 for (i
= larray
- 1; i
; i
--)
5577 args
[i
] = args
[i
- 1];
5579 args
[0] = shell_name
;
5581 args
[larray
] = (char *)NULL
;
5583 if (args
[0][0] == '-')
5586 #if defined (RESTRICTED_SHELL)
5588 change_flag ('r', FLAG_OFF
);
5593 /* Can't free subshell_argv[0]; that is shell_name. */
5594 for (i
= 1; i
< subshell_argc
; i
++)
5595 free (subshell_argv
[i
]);
5596 free (subshell_argv
);
5599 dispose_command (currently_executing_command
); /* XXX */
5600 currently_executing_command
= (COMMAND
*)NULL
;
5602 subshell_argc
= larray
;
5603 subshell_argv
= args
;
5604 subshell_envp
= env
;
5606 unbind_args (); /* remove the positional parameters */
5608 #if defined (PROCESS_SUBSTITUTION)
5609 clear_fifo_list (); /* pipe fds are what they are now */
5612 sh_longjmp (subshell_top_level
, 1);
5617 execute_intern_function (name
, funcdef
)
5619 FUNCTION_DEF
*funcdef
;
5623 if (check_identifier (name
, posixly_correct
) == 0)
5625 if (posixly_correct
&& interactive_shell
== 0)
5627 last_command_exit_value
= EX_BADUSAGE
;
5628 jump_to_top_level (ERREXIT
);
5630 return (EXECUTION_FAILURE
);
5633 /* Posix interpretation 383 */
5634 if (posixly_correct
&& find_special_builtin (name
->word
))
5636 internal_error (_("`%s': is a special builtin"), name
->word
);
5637 last_command_exit_value
= EX_BADUSAGE
;
5638 jump_to_top_level (interactive_shell
? DISCARD
: ERREXIT
);
5641 var
= find_function (name
->word
);
5642 if (var
&& (readonly_p (var
) || noassign_p (var
)))
5644 if (readonly_p (var
))
5645 internal_error (_("%s: readonly function"), var
->name
);
5646 return (EXECUTION_FAILURE
);
5649 #if defined (DEBUGGER)
5650 bind_function_def (name
->word
, funcdef
);
5653 bind_function (name
->word
, funcdef
->command
);
5654 return (EXECUTION_SUCCESS
);
5657 #if defined (INCLUDE_UNUSED)
5658 #if defined (PROCESS_SUBSTITUTION)
5662 register int i
, fd_table_size
;
5664 fd_table_size
= getdtablesize ();
5665 if (fd_table_size
> 256) /* clamp to a reasonable value */
5666 fd_table_size
= 256;
5668 for (i
= 3; i
< fd_table_size
; i
++)
5671 #endif /* PROCESS_SUBSTITUTION */
5675 close_pipes (in
, out
)
5685 dup_error (oldd
, newd
)
5688 sys_error (_("cannot duplicate fd %d to fd %d"), oldd
, newd
);
5691 /* Redirect input and output to be from and to the specified pipes.
5692 NO_PIPE and REDIRECT_BOTH are handled correctly. */
5694 do_piping (pipe_in
, pipe_out
)
5695 int pipe_in
, pipe_out
;
5697 if (pipe_in
!= NO_PIPE
)
5699 if (dup2 (pipe_in
, 0) < 0)
5700 dup_error (pipe_in
, 0);
5704 /* Let stdio know the fd may have changed from text to binary mode. */
5705 freopen (NULL
, "r", stdin
);
5706 #endif /* __CYGWIN__ */
5708 if (pipe_out
!= NO_PIPE
)
5710 if (pipe_out
!= REDIRECT_BOTH
)
5712 if (dup2 (pipe_out
, 1) < 0)
5713 dup_error (pipe_out
, 1);
5714 if (pipe_out
== 0 || pipe_out
> 1)
5719 if (dup2 (1, 2) < 0)
5723 /* Let stdio know the fd may have changed from text to binary mode, and
5724 make sure to preserve stdout line buffering. */
5725 freopen (NULL
, "w", stdout
);
5726 sh_setlinebuf (stdout
);
5727 #endif /* __CYGWIN__ */