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
);
735 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
737 if (do_redirections (command
->redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
739 cleanup_redirects (redirection_undo_list
);
740 redirection_undo_list
= (REDIRECT
*)NULL
;
741 dispose_exec_redirects ();
742 #if defined (PROCESS_SUBSTITUTION)
744 free ((void *)ofifo_list
);
746 return (last_command_exit_value
= EXECUTION_FAILURE
);
749 if (redirection_undo_list
)
751 /* XXX - why copy here? */
752 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
753 dispose_redirects (redirection_undo_list
);
754 redirection_undo_list
= (REDIRECT
*)NULL
;
757 my_undo_list
= (REDIRECT
*)NULL
;
759 if (exec_redirection_undo_list
)
761 /* XXX - why copy here? */
762 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
763 dispose_redirects (exec_redirection_undo_list
);
764 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
767 exec_undo_list
= (REDIRECT
*)NULL
;
769 if (my_undo_list
|| exec_undo_list
)
770 begin_unwind_frame ("loop_redirections");
773 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
776 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
778 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
782 switch (command
->type
)
786 save_line_number
= line_number
;
787 /* We can't rely on variables retaining their values across a
788 call to execute_simple_command if a longjmp occurs as the
789 result of a `return' builtin. This is true for sure with gcc. */
790 #if defined (RECYCLES_PIDS)
791 last_made_pid
= NO_PID
;
793 last_pid
= last_made_pid
;
794 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
796 if (ignore_return
&& command
->value
.Simple
)
797 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
798 if (command
->flags
& CMD_STDIN_REDIR
)
799 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
801 line_number_for_err_trap
= line_number
= command
->value
.Simple
->line
;
803 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
804 asynchronous
, fds_to_close
);
805 line_number
= save_line_number
;
807 /* The temporary environment should be used for only the simple
808 command immediately following its definition. */
809 dispose_used_env_vars ();
811 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
812 /* Reclaim memory allocated with alloca () on machines which
813 may be using the alloca emulation code. */
815 #endif /* (ultrix && mips) || C_ALLOCA */
817 /* If we forked to do the command, then we must wait_for ()
820 /* XXX - this is something to watch out for if there are problems
821 when the shell is compiled without job control. Don't worry about
822 whether or not last_made_pid == last_pid; already_making_children
823 tells us whether or not there are unwaited-for children to wait
825 if (already_making_children
&& pipe_out
== NO_PIPE
)
827 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
831 DESCRIBE_PID (last_made_pid
);
832 exec_result
= EXECUTION_SUCCESS
;
833 invert
= 0; /* async commands always succeed */
836 #if !defined (JOB_CONTROL)
837 /* Do not wait for asynchronous processes started from
839 if (last_made_pid
!= NO_PID
&& last_made_pid
!= last_asynchronous_pid
)
841 if (last_made_pid
!= NO_PID
)
843 /* When executing a shell function that executes other
844 commands, this causes the last simple command in
845 the function to be waited for twice. This also causes
846 subshells forked to execute builtin commands (e.g., in
847 pipelines) to be waited for twice. */
848 exec_result
= wait_for (last_made_pid
);
852 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
853 only the failure of a simple command. */
854 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)
856 last_command_exit_value
= exec_result
;
857 line_number
= line_number_for_err_trap
;
859 line_number
= save_line_number
;
862 if (ignore_return
== 0 && invert
== 0 &&
863 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
864 (exit_immediately_on_error
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)))
866 last_command_exit_value
= exec_result
;
867 run_pending_traps ();
869 /* Undo redirections before running exit trap on the way out of
870 set -e. Report by Mark Farrell 5/19/2014 */
871 if (exit_immediately_on_error
&& signal_is_trapped (0) &&
872 unwind_protect_tag_on_stack ("saved-redirects"))
873 run_unwind_frame ("saved-redirects");
875 jump_to_top_level (ERREXIT
);
882 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
883 exec_result
= execute_for_command (command
->value
.For
);
886 #if defined (ARITH_FOR_COMMAND)
889 command
->value
.ArithFor
->flags
|= CMD_IGNORE_RETURN
;
890 exec_result
= execute_arith_for_command (command
->value
.ArithFor
);
894 #if defined (SELECT_COMMAND)
897 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
898 exec_result
= execute_select_command (command
->value
.Select
);
904 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
905 exec_result
= execute_case_command (command
->value
.Case
);
910 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
911 exec_result
= execute_while_command (command
->value
.While
);
916 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
917 exec_result
= execute_until_command (command
->value
.While
);
922 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
923 exec_result
= execute_if_command (command
->value
.If
);
928 /* This code can be executed from either of two paths: an explicit
929 '{}' command, or via a function call. If we are executed via a
930 function call, we have already taken care of the function being
931 executed in the background (down there in execute_simple_command ()),
932 and this command should *not* be marked as asynchronous. If we
933 are executing a regular '{}' group command, and asynchronous == 1,
934 we must want to execute the whole command in the background, so we
935 need a subshell, and we want the stuff executed in that subshell
936 (this group command) to be executed in the foreground of that
937 subshell (i.e. there will not be *another* subshell forked).
939 What we do is to force a subshell if asynchronous, and then call
940 execute_command_internal again with asynchronous still set to 1,
941 but with the original group command, so the printed command will
944 The code above that handles forking off subshells will note that
945 both subshell and async are on, and turn off async in the child
946 after forking the subshell (but leave async set in the parent, so
947 the normal call to describe_pid is made). This turning off
948 async is *crucial*; if it is not done, this will fall into an
949 infinite loop of executions through this spot in subshell after
950 subshell until the process limit is exhausted. */
954 command
->flags
|= CMD_FORCE_SUBSHELL
;
956 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
961 if (ignore_return
&& command
->value
.Group
->command
)
962 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
964 execute_command_internal (command
->value
.Group
->command
,
965 asynchronous
, pipe_in
, pipe_out
,
971 exec_result
= execute_connection (command
, asynchronous
,
972 pipe_in
, pipe_out
, fds_to_close
);
974 invert
= 0; /* XXX */
978 #if defined (DPAREN_ARITHMETIC)
980 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
982 command
->value
.Arith
->flags
|= CMD_IGNORE_RETURN
;
983 line_number_for_err_trap
= save_line_number
= line_number
;
984 exec_result
= execute_arith_command (command
->value
.Arith
);
985 line_number
= save_line_number
;
987 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
989 last_command_exit_value
= exec_result
;
990 save_line_number
= line_number
;
991 line_number
= line_number_for_err_trap
;
993 line_number
= save_line_number
;
996 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
998 last_command_exit_value
= exec_result
;
999 run_pending_traps ();
1000 jump_to_top_level (ERREXIT
);
1006 #if defined (COND_COMMAND)
1008 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
1010 command
->value
.Cond
->flags
|= CMD_IGNORE_RETURN
;
1012 line_number_for_err_trap
= save_line_number
= line_number
;
1013 exec_result
= execute_cond_command (command
->value
.Cond
);
1014 line_number
= save_line_number
;
1016 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
1018 last_command_exit_value
= exec_result
;
1019 save_line_number
= line_number
;
1020 line_number
= line_number_for_err_trap
;
1022 line_number
= save_line_number
;
1025 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
1027 last_command_exit_value
= exec_result
;
1028 run_pending_traps ();
1029 jump_to_top_level (ERREXIT
);
1035 case cm_function_def
:
1036 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
1037 command
->value
.Function_def
);
1041 command_error ("execute_command", CMDERR_BADTYPE
, command
->type
, 0);
1046 do_redirections (my_undo_list
, RX_ACTIVE
);
1047 dispose_redirects (my_undo_list
);
1051 dispose_redirects (exec_undo_list
);
1053 if (my_undo_list
|| exec_undo_list
)
1054 discard_unwind_frame ("loop_redirections");
1056 #if defined (PROCESS_SUBSTITUTION)
1059 nfifo
= num_fifos ();
1061 close_new_fifos ((char *)ofifo_list
, osize
);
1062 free ((void *)ofifo_list
);
1066 /* Invert the return value if we have to */
1068 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
1070 : EXECUTION_SUCCESS
;
1072 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
1073 /* This is where we set PIPESTATUS from the exit status of the appropriate
1074 compound commands (the ones that look enough like simple commands to
1075 cause confusion). We might be able to optimize by not doing this if
1076 subshell_environment != 0. */
1077 switch (command
->type
)
1079 # if defined (DPAREN_ARITHMETIC)
1082 # if defined (COND_COMMAND)
1085 set_pipestatus_from_exit (exec_result
);
1090 last_command_exit_value
= exec_result
;
1091 run_pending_traps ();
1093 if (running_trap
== 0)
1095 currently_executing_command
= (COMMAND
*)NULL
;
1097 return (last_command_exit_value
);
1100 #if defined (COMMAND_TIMING)
1102 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1103 extern struct timeval
*difftimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1104 extern struct timeval
*addtimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1105 extern int timeval_to_cpu
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1108 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1109 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1111 static const int precs
[] = { 0, 100, 10, 1 };
1113 #if defined (HAVE_LOCALE_H) && defined (HAVE_LOCALECONV)
1120 return (lv
&& lv
->decimal_point
&& lv
->decimal_point
[0]) ? lv
->decimal_point
[0] : '.';
1123 # define decpoint() '.'
1126 /* Expand one `%'-prefixed escape sequence from a time format string. */
1128 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
1135 char abuf
[INT_STRLEN_BOUND(time_t) + 1];
1139 abuf
[sizeof(abuf
) - 1] = '\0';
1141 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1146 aind
= sizeof(abuf
) - 2;
1148 abuf
[aind
--] = (min
% 10) + '0';
1152 buf
[ind
++] = abuf
[aind
++];
1156 /* Now add the seconds. */
1157 aind
= sizeof (abuf
) - 2;
1159 abuf
[aind
--] = (sec
% 10) + '0';
1163 buf
[ind
++] = abuf
[aind
++];
1165 /* We want to add a decimal point and PREC places after it if PREC is
1166 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1170 buf
[ind
++] = decpoint ();
1171 for (aind
= 1; aind
<= prec
; aind
++)
1173 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
1174 sec_fraction
%= precs
[aind
];
1185 /* Interpret the format string FORMAT, interpolating the following escape
1189 where the optional `prec' is a precision, meaning the number of
1190 characters after the decimal point, the optional `l' means to format
1191 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1192 and the last character is one of
1194 R number of seconds of `real' time
1195 U number of seconds of `user' time
1196 S number of seconds of `system' time
1198 An occurrence of `%%' in the format string is translated to a `%'. The
1199 result is printed to FP, a pointer to a FILE. The other variables are
1200 the seconds and thousandths of a second of real, user, and system time,
1203 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1214 char *str
, *s
, ts
[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1219 len
= strlen (format
);
1220 ssize
= (len
+ 64) - (len
% 64);
1221 str
= (char *)xmalloc (ssize
);
1224 for (s
= format
; *s
; s
++)
1226 if (*s
!= '%' || s
[1] == '\0')
1228 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1231 else if (s
[1] == '%')
1234 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1237 else if (s
[1] == 'P')
1241 /* clamp CPU usage at 100% */
1246 sum_frac
= (cpu
% 100) * 10;
1247 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1248 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1249 strcpy (str
+ sindex
, ts
);
1254 prec
= 3; /* default is three places past the decimal point. */
1255 lng
= 0; /* default is to not use minutes or append `s' */
1257 if (DIGIT (*s
)) /* `precision' */
1260 if (prec
> 3) prec
= 3;
1262 if (*s
== 'l') /* `length extender' */
1267 if (*s
== 'R' || *s
== 'E')
1268 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1270 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1272 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1275 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s
);
1279 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1280 strcpy (str
+ sindex
, ts
);
1286 fprintf (fp
, "%s\n", str
);
1293 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1295 int asynchronous
, pipe_in
, pipe_out
;
1296 struct fd_bitmap
*fds_to_close
;
1298 int rv
, posix_time
, old_flags
, nullcmd
, code
;
1303 volatile procenv_t save_top_level
;
1305 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1306 struct timeval real
, user
, sys
;
1307 struct timeval before
, after
;
1308 # if defined (HAVE_STRUCT_TIMEZONE)
1309 struct timezone dtz
; /* posix doesn't define this */
1311 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1313 # if defined (HAVE_TIMES)
1314 clock_t tbefore
, tafter
, real
, user
, sys
;
1315 struct tms before
, after
;
1319 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1320 # if defined (HAVE_STRUCT_TIMEZONE)
1321 gettimeofday (&before
, &dtz
);
1323 gettimeofday (&before
, (void *)NULL
);
1324 # endif /* !HAVE_STRUCT_TIMEZONE */
1325 getrusage (RUSAGE_SELF
, &selfb
);
1326 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1328 # if defined (HAVE_TIMES)
1329 tbefore
= times (&before
);
1333 posix_time
= command
&& (command
->flags
& CMD_TIME_POSIX
);
1335 nullcmd
= (command
== 0) || (command
->type
== cm_simple
&& command
->value
.Simple
->words
== 0 && command
->value
.Simple
->redirects
== 0);
1336 if (posixly_correct
&& nullcmd
)
1338 #if defined (HAVE_GETRUSAGE)
1339 selfb
.ru_utime
.tv_sec
= kidsb
.ru_utime
.tv_sec
= selfb
.ru_stime
.tv_sec
= kidsb
.ru_stime
.tv_sec
= 0;
1340 selfb
.ru_utime
.tv_usec
= kidsb
.ru_utime
.tv_usec
= selfb
.ru_stime
.tv_usec
= kidsb
.ru_stime
.tv_usec
= 0;
1341 before
.tv_sec
= shell_start_time
;
1344 before
.tms_utime
= before
.tms_stime
= before
.tms_cutime
= before
.tms_cstime
= 0;
1345 tbefore
= shell_start_time
;
1349 old_flags
= command
->flags
;
1350 COPY_PROCENV (top_level
, save_top_level
);
1351 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1352 code
= setjmp_nosigs (top_level
);
1353 if (code
== NOT_JUMPED
)
1354 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1355 command
->flags
= old_flags
;
1356 COPY_PROCENV (save_top_level
, top_level
);
1359 rsf
= usf
= ssf
= cpu
= 0;
1361 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1362 # if defined (HAVE_STRUCT_TIMEZONE)
1363 gettimeofday (&after
, &dtz
);
1365 gettimeofday (&after
, (void *)NULL
);
1366 # endif /* !HAVE_STRUCT_TIMEZONE */
1367 getrusage (RUSAGE_SELF
, &selfa
);
1368 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1370 difftimeval (&real
, &before
, &after
);
1371 timeval_to_secs (&real
, &rs
, &rsf
);
1373 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1374 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1375 timeval_to_secs (&user
, &us
, &usf
);
1377 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1378 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1379 timeval_to_secs (&sys
, &ss
, &ssf
);
1381 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1383 # if defined (HAVE_TIMES)
1384 tafter
= times (&after
);
1386 real
= tafter
- tbefore
;
1387 clock_t_to_secs (real
, &rs
, &rsf
);
1389 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1390 clock_t_to_secs (user
, &us
, &usf
);
1392 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1393 clock_t_to_secs (sys
, &ss
, &ssf
);
1395 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1399 rsf
= usf
= ssf
= cpu
= 0;
1404 time_format
= POSIX_TIMEFORMAT
;
1405 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1407 if (posixly_correct
&& nullcmd
)
1408 time_format
= "user\t%2lU\nsys\t%2lS";
1410 time_format
= BASH_TIMEFORMAT
;
1412 if (time_format
&& *time_format
)
1413 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1416 sh_longjmp (top_level
, code
);
1420 #endif /* COMMAND_TIMING */
1422 /* Execute a command that's supposed to be in a subshell. This must be
1423 called after make_child and we must be running in the child process.
1424 The caller will return or exit() immediately with the value this returns. */
1426 execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1429 int pipe_in
, pipe_out
;
1430 struct fd_bitmap
*fds_to_close
;
1432 int user_subshell
, return_code
, function_value
, should_redir_stdin
, invert
;
1433 int ois
, user_coproc
;
1435 volatile COMMAND
*tcom
;
1437 USE_VAR(user_subshell
);
1438 USE_VAR(user_coproc
);
1441 USE_VAR(asynchronous
);
1444 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
1445 pipe_in
== NO_PIPE
&&
1446 stdin_redirects (command
->redirects
) == 0);
1448 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
1449 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
1450 user_coproc
= command
->type
== cm_coproc
;
1452 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
1454 /* If a command is asynchronous in a subshell (like ( foo ) & or
1455 the special case of an asynchronous GROUP command where the
1456 the subshell bit is turned on down in case cm_group: below),
1457 turn off `asynchronous', so that two subshells aren't spawned.
1458 XXX - asynchronous used to be set to 0 in this block, but that
1459 means that setup_async_signals was never run. Now it's set to
1460 0 after subshell_environment is set appropriately and setup_async_signals
1463 This seems semantically correct to me. For example,
1464 ( foo ) & seems to say ``do the command `foo' in a subshell
1465 environment, but don't wait for that subshell to finish'',
1466 and "{ foo ; bar ; } &" seems to me to be like functions or
1467 builtins in the background, which executed in a subshell
1468 environment. I just don't see the need to fork two subshells. */
1470 /* Don't fork again, we are already in a subshell. A `doubly
1471 async' shell is not interactive, however. */
1474 #if defined (JOB_CONTROL)
1475 /* If a construct like ( exec xxx yyy ) & is given while job
1476 control is active, we want to prevent exec from putting the
1477 subshell back into the original process group, carefully
1478 undoing all the work we just did in make_child. */
1480 #endif /* JOB_CONTROL */
1481 ois
= interactive_shell
;
1482 interactive_shell
= 0;
1483 /* This test is to prevent alias expansion by interactive shells that
1484 run `(command) &' but to allow scripts that have enabled alias
1485 expansion with `shopt -s expand_alias' to continue to expand
1487 if (ois
!= interactive_shell
)
1491 /* Subshells are neither login nor interactive. */
1492 login_shell
= interactive
= 0;
1495 subshell_environment
= SUBSHELL_PAREN
; /* XXX */
1498 subshell_environment
= 0; /* XXX */
1500 subshell_environment
|= SUBSHELL_ASYNC
;
1501 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
1502 subshell_environment
|= SUBSHELL_PIPE
;
1504 subshell_environment
|= SUBSHELL_COPROC
;
1507 reset_terminating_signals (); /* in sig.c */
1508 /* Cancel traps, in trap.c. */
1509 /* Reset the signal handlers in the child, but don't free the
1510 trap strings. Set a flag noting that we have to free the
1511 trap strings if we run trap to change a signal disposition. */
1512 reset_signal_handlers ();
1513 subshell_environment
|= SUBSHELL_RESETTRAP
;
1515 /* Make sure restore_original_signals doesn't undo the work done by
1516 make_child to ensure that asynchronous children are immune to SIGINT
1517 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1521 setup_async_signals ();
1525 #if defined (JOB_CONTROL)
1526 set_sigchld_handler ();
1527 #endif /* JOB_CONTROL */
1529 set_sigint_handler ();
1531 #if defined (JOB_CONTROL)
1532 /* Delete all traces that there were any jobs running. This is
1533 only for subshells. */
1534 without_job_control ();
1535 #endif /* JOB_CONTROL */
1538 close_fd_bitmap (fds_to_close
);
1540 do_piping (pipe_in
, pipe_out
);
1542 #if defined (COPROCESS_SUPPORT)
1546 /* If this is a user subshell, set a flag if stdin was redirected.
1547 This is used later to decide whether to redirect fd 0 to
1548 /dev/null for async commands in the subshell. This adds more
1549 sh compatibility, but I'm not sure it's the right thing to do.
1550 Note that an input pipe to a compound command suffices to inhibit
1551 the implicit /dev/null redirection for asynchronous commands
1552 executed as part of that compound command. */
1555 stdin_redir
= stdin_redirects (command
->redirects
) || pipe_in
!= NO_PIPE
;
1557 restore_default_signal (EXIT_TRAP
); /* XXX - reset_signal_handlers above */
1560 else if (shell_control_structure (command
->type
) && pipe_in
!= NO_PIPE
)
1563 /* If this is an asynchronous command (command &), we want to
1564 redirect the standard input from /dev/null in the absence of
1565 any specific redirection involving stdin. */
1566 if (should_redir_stdin
&& stdin_redir
== 0)
1567 async_redirect_stdin ();
1569 /* Do redirections, then dispose of them before recursive call. */
1570 if (command
->redirects
)
1572 if (do_redirections (command
->redirects
, RX_ACTIVE
) != 0)
1573 exit (invert
? EXECUTION_SUCCESS
: EXECUTION_FAILURE
);
1575 dispose_redirects (command
->redirects
);
1576 command
->redirects
= (REDIRECT
*)NULL
;
1579 if (command
->type
== cm_subshell
)
1580 tcom
= command
->value
.Subshell
->command
;
1581 else if (user_coproc
)
1582 tcom
= command
->value
.Coproc
->command
;
1586 if (command
->flags
& CMD_TIME_PIPELINE
)
1587 tcom
->flags
|= CMD_TIME_PIPELINE
;
1588 if (command
->flags
& CMD_TIME_POSIX
)
1589 tcom
->flags
|= CMD_TIME_POSIX
;
1591 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1592 if ((command
->flags
& CMD_IGNORE_RETURN
) && tcom
!= command
)
1593 tcom
->flags
|= CMD_IGNORE_RETURN
;
1595 /* If this is a simple command, tell execute_disk_command that it
1596 might be able to get away without forking and simply exec.
1597 This means things like ( sleep 10 ) will only cause one fork.
1598 If we're timing the command or inverting its return value, however,
1599 we cannot do this optimization. */
1600 if ((user_subshell
|| user_coproc
) && (tcom
->type
== cm_simple
|| tcom
->type
== cm_subshell
) &&
1601 ((tcom
->flags
& CMD_TIME_PIPELINE
) == 0) &&
1602 ((tcom
->flags
& CMD_INVERT_RETURN
) == 0))
1604 tcom
->flags
|= CMD_NO_FORK
;
1605 if (tcom
->type
== cm_simple
)
1606 tcom
->value
.Simple
->flags
|= CMD_NO_FORK
;
1609 invert
= (tcom
->flags
& CMD_INVERT_RETURN
) != 0;
1610 tcom
->flags
&= ~CMD_INVERT_RETURN
;
1612 result
= setjmp_nosigs (top_level
);
1614 /* If we're inside a function while executing this subshell, we
1615 need to handle a possible `return'. */
1617 if (return_catch_flag
)
1618 function_value
= setjmp_nosigs (return_catch
);
1620 /* If we're going to exit the shell, we don't want to invert the return
1622 if (result
== EXITPROG
)
1623 invert
= 0, return_code
= last_command_exit_value
;
1625 return_code
= (last_command_exit_value
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: last_command_exit_value
;
1626 else if (function_value
)
1627 return_code
= return_catch_value
;
1629 return_code
= execute_command_internal ((COMMAND
*)tcom
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
1631 /* If we are asked to, invert the return value. */
1633 return_code
= (return_code
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
1634 : EXECUTION_SUCCESS
;
1636 /* If we were explicitly placed in a subshell with (), we need
1637 to do the `shell cleanup' things, such as running traps[0]. */
1638 if (user_subshell
&& signal_is_trapped (0))
1640 last_command_exit_value
= return_code
;
1641 return_code
= run_exit_trap ();
1645 subshell_level
--; /* don't bother, caller will just exit */
1647 return (return_code
);
1651 #if defined (COPROCESS_SUPPORT)
1652 #define COPROC_MAX 16
1654 typedef struct cpelement
1656 struct cpelement
*next
;
1657 struct coproc
*coproc
;
1661 typedef struct cplist
1663 struct cpelement
*head
;
1664 struct cpelement
*tail
;
1670 static struct cpelement
*cpe_alloc
__P((struct coproc
*));
1671 static void cpe_dispose
__P((struct cpelement
*));
1672 static struct cpelement
*cpl_add
__P((struct coproc
*));
1673 static struct cpelement
*cpl_delete
__P((pid_t
));
1674 static void cpl_reap
__P((void));
1675 static void cpl_flush
__P((void));
1676 static void cpl_closeall
__P((void));
1677 static struct cpelement
*cpl_search
__P((pid_t
));
1678 static struct cpelement
*cpl_searchbyname
__P((const char *));
1679 static void cpl_prune
__P((void));
1681 static void coproc_free
__P((struct coproc
*));
1683 /* Will go away when there is fully-implemented support for multiple coprocs. */
1684 Coproc sh_coproc
= { 0, NO_PID
, -1, -1, 0, 0, 0, 0, 0 };
1686 cplist_t coproc_list
= {0, 0, 0};
1688 /* Functions to manage the list of coprocs */
1690 static struct cpelement
*
1694 struct cpelement
*cpe
;
1696 cpe
= (struct cpelement
*)xmalloc (sizeof (struct cpelement
));
1698 cpe
->next
= (struct cpelement
*)0;
1704 struct cpelement
*cpe
;
1709 static struct cpelement
*
1713 struct cpelement
*cpe
;
1715 cpe
= cpe_alloc (cp
);
1717 if (coproc_list
.head
== 0)
1719 coproc_list
.head
= coproc_list
.tail
= cpe
;
1720 coproc_list
.ncoproc
= 0; /* just to make sure */
1724 coproc_list
.tail
->next
= cpe
;
1725 coproc_list
.tail
= cpe
;
1727 coproc_list
.ncoproc
++;
1732 static struct cpelement
*
1736 struct cpelement
*prev
, *p
;
1738 for (prev
= p
= coproc_list
.head
; p
; prev
= p
, p
= p
->next
)
1739 if (p
->coproc
->c_pid
== pid
)
1741 prev
->next
= p
->next
; /* remove from list */
1746 return 0; /* not found */
1749 itrace("cpl_delete: deleting %d", pid
);
1752 /* Housekeeping in the border cases. */
1753 if (p
== coproc_list
.head
)
1754 coproc_list
.head
= coproc_list
.head
->next
;
1755 else if (p
== coproc_list
.tail
)
1756 coproc_list
.tail
= prev
;
1758 coproc_list
.ncoproc
--;
1759 if (coproc_list
.ncoproc
== 0)
1760 coproc_list
.head
= coproc_list
.tail
= 0;
1761 else if (coproc_list
.ncoproc
== 1)
1762 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1770 struct cpelement
*p
, *next
, *nh
, *nt
;
1772 /* Build a new list by removing dead coprocs and fix up the coproc_list
1773 pointers when done. */
1774 nh
= nt
= next
= (struct cpelement
*)0;
1775 for (p
= coproc_list
.head
; p
; p
= next
)
1778 if (p
->coproc
->c_flags
& COPROC_DEAD
)
1780 coproc_list
.ncoproc
--; /* keep running count, fix up pointers later */
1783 itrace("cpl_reap: deleting %d", p
->coproc
->c_pid
);
1786 coproc_dispose (p
->coproc
);
1798 if (coproc_list
.ncoproc
== 0)
1799 coproc_list
.head
= coproc_list
.tail
= 0;
1804 coproc_list
.head
= nh
;
1805 coproc_list
.tail
= nt
;
1806 if (coproc_list
.ncoproc
== 1)
1807 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1811 /* Clear out the list of saved statuses */
1815 struct cpelement
*cpe
, *p
;
1817 for (cpe
= coproc_list
.head
; cpe
; )
1822 coproc_dispose (p
->coproc
);
1826 coproc_list
.head
= coproc_list
.tail
= 0;
1827 coproc_list
.ncoproc
= 0;
1833 struct cpelement
*cpe
;
1835 for (cpe
= coproc_list
.head
; cpe
; cpe
= cpe
->next
)
1836 coproc_close (cpe
->coproc
);
1843 struct cpelement
*cpe
;
1845 for (cpe
= coproc_list
.head
; cpe
; cpe
= cpe
->next
)
1846 coproc_checkfd (cpe
->coproc
, fd
);
1849 /* Search for PID in the list of coprocs; return the cpelement struct if
1850 found. If not found, return NULL. */
1851 static struct cpelement
*
1855 struct cpelement
*cpe
;
1857 for (cpe
= coproc_list
.head
; cpe
; cpe
= cpe
->next
)
1858 if (cpe
->coproc
->c_pid
== pid
)
1860 return (struct cpelement
*)NULL
;
1863 /* Search for the coproc named NAME in the list of coprocs; return the
1864 cpelement struct if found. If not found, return NULL. */
1865 static struct cpelement
*
1866 cpl_searchbyname (name
)
1869 struct cpelement
*cp
;
1871 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1872 if (STREQ (cp
->coproc
->c_name
, name
))
1874 return (struct cpelement
*)NULL
;
1881 struct cpelement
*cp
;
1883 while (coproc_list
.head
&& coproc_list
.ncoproc
> COPROC_MAX
)
1885 cp
= coproc_list
.head
;
1886 coproc_list
.head
= coproc_list
.head
->next
;
1887 coproc_dispose (cp
->coproc
);
1889 coproc_list
.ncoproc
--;
1894 /* These currently use a single global "shell coproc" but are written in a
1895 way to not preclude additional coprocs later (using the list management
1899 getcoprocbypid (pid
)
1902 #if MULTIPLE_COPROCS
1903 struct cpelement
*p
;
1905 p
= cpl_search (pid
);
1906 return (p
? p
->coproc
: 0);
1908 return (pid
== sh_coproc
.c_pid
? &sh_coproc
: 0);
1913 getcoprocbyname (name
)
1916 #if MULTIPLE_COPROCS
1917 struct cpelement
*p
;
1919 p
= cpl_searchbyname (name
);
1920 return (p
? p
->coproc
: 0);
1922 return ((sh_coproc
.c_name
&& STREQ (sh_coproc
.c_name
, name
)) ? &sh_coproc
: 0);
1932 cp
->c_rfd
= cp
->c_wfd
= -1;
1933 cp
->c_rsave
= cp
->c_wsave
= -1;
1934 cp
->c_flags
= cp
->c_status
= cp
->c_lock
= 0;
1938 coproc_alloc (name
, pid
)
1944 #if MULTIPLE_COPROCS
1945 cp
= (struct coproc
*)xmalloc (sizeof (struct coproc
));
1953 cp
->c_name
= savestring (name
);
1954 #if MULTIPLE_COPROCS
1977 BLOCK_SIGNAL (SIGCHLD
, set
, oset
);
1979 coproc_unsetvars (cp
);
1982 #if MULTIPLE_COPROCS
1988 UNBLOCK_SIGNAL (oset
);
1991 /* Placeholder for now. Will require changes for multiple coprocs */
1995 #if MULTIPLE_COPROCS
1998 coproc_dispose (&sh_coproc
);
2016 cp
->c_rsave
= cp
->c_wsave
= -1;
2022 #if MULTIPLE_COPROCS
2025 coproc_close (&sh_coproc
); /* XXX - will require changes for multiple coprocs */
2032 #if MULTIPLE_COPROCS
2037 cp
= &sh_coproc
; /* XXX - will require changes for multiple coprocs */
2038 if (cp
&& (cp
->c_flags
& COPROC_DEAD
))
2039 coproc_dispose (cp
);
2044 coproc_rclose (cp
, fd
)
2048 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
2056 coproc_wclose (cp
, fd
)
2060 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
2068 coproc_checkfd (cp
, fd
)
2075 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
2076 update
= cp
->c_rfd
= -1;
2077 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
2078 update
= cp
->c_wfd
= -1;
2080 coproc_setvars (cp
);
2087 #if MULTIPLE_COPROCS
2090 coproc_checkfd (&sh_coproc
, fd
);
2095 coproc_fdclose (cp
, fd
)
2099 coproc_rclose (cp
, fd
);
2100 coproc_wclose (cp
, fd
);
2101 coproc_setvars (cp
);
2108 cp
->c_rsave
= cp
->c_rfd
;
2109 cp
->c_wsave
= cp
->c_wfd
;
2113 coproc_fdrestore (cp
)
2116 cp
->c_rfd
= cp
->c_rsave
;
2117 cp
->c_wfd
= cp
->c_wsave
;
2121 coproc_pidchk (pid
, status
)
2127 #if MULTIPLE_COPROCS
2128 struct cpelement
*cpe
;
2130 cpe
= cpl_delete (pid
);
2131 cp
= cpe
? cpe
->coproc
: 0;
2133 cp
= getcoprocbypid (pid
);
2138 cp
->c_status
= status
;
2139 cp
->c_flags
|= COPROC_DEAD
;
2140 cp
->c_flags
&= ~COPROC_RUNNING
;
2141 /* Don't dispose the coproc or unset the COPROC_XXX variables because
2142 this is executed in a signal handler context. Wait until coproc_reap
2143 takes care of it. */
2156 #if defined (ARRAY_VARS)
2160 if (cp
->c_name
== 0)
2163 /* We could do more here but right now we only check the name, warn if it's
2164 not a valid identifier, and refuse to create variables with invalid names
2165 if a coproc with such a name is supplied. */
2166 w
.word
= cp
->c_name
;
2168 if (check_identifier (&w
, 1) == 0)
2171 l
= strlen (cp
->c_name
);
2172 namevar
= xmalloc (l
+ 16);
2174 #if defined (ARRAY_VARS)
2175 v
= find_variable (cp
->c_name
);
2177 /* This is the same code as in find_or_make_array_variable */
2180 v
= find_variable_nameref_for_create (cp
->c_name
, 1);
2181 if (v
== INVALID_NAMEREF_VALUE
)
2183 if (v
&& nameref_p (v
))
2186 cp
->c_name
= savestring (nameref_cell (v
));
2187 v
= make_new_array_variable (cp
->c_name
);
2191 if (v
&& (readonly_p (v
) || noassign_p (v
)))
2194 err_readonly (cp
->c_name
);
2198 v
= make_new_array_variable (cp
->c_name
);
2199 if (array_p (v
) == 0)
2200 v
= convert_var_to_array (v
);
2202 t
= itos (cp
->c_rfd
);
2204 v
= bind_array_variable (cp
->c_name
, ind
, t
, 0);
2207 t
= itos (cp
->c_wfd
);
2209 bind_array_variable (cp
->c_name
, ind
, t
, 0);
2212 sprintf (namevar
, "%s_READ", cp
->c_name
);
2213 t
= itos (cp
->c_rfd
);
2214 bind_variable (namevar
, t
, 0);
2216 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
2217 t
= itos (cp
->c_wfd
);
2218 bind_variable (namevar
, t
, 0);
2222 sprintf (namevar
, "%s_PID", cp
->c_name
);
2223 t
= itos (cp
->c_pid
);
2224 bind_variable (namevar
, t
, 0);
2231 coproc_unsetvars (cp
)
2237 if (cp
->c_name
== 0)
2240 l
= strlen (cp
->c_name
);
2241 namevar
= xmalloc (l
+ 16);
2243 sprintf (namevar
, "%s_PID", cp
->c_name
);
2244 unbind_variable_noref (namevar
);
2246 #if defined (ARRAY_VARS)
2247 check_unbind_variable (cp
->c_name
);
2249 sprintf (namevar
, "%s_READ", cp
->c_name
);
2250 unbind_variable (namevar
);
2251 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
2252 unbind_variable (namevar
);
2259 execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
)
2261 int pipe_in
, pipe_out
;
2262 struct fd_bitmap
*fds_to_close
;
2264 int rpipe
[2], wpipe
[2], estat
, invert
;
2270 /* XXX -- can be removed after changes to handle multiple coprocs */
2271 #if !MULTIPLE_COPROCS
2272 if (sh_coproc
.c_pid
!= NO_PID
)
2273 internal_warning (_("execute_coproc: coproc [%d:%s] still exists"), sh_coproc
.c_pid
, sh_coproc
.c_name
);
2274 coproc_init (&sh_coproc
);
2277 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
2278 command_string_index
= 0;
2279 tcmd
= make_command_string (command
);
2281 sh_openpipe ((int *)&rpipe
); /* 0 = parent read, 1 = child write */
2282 sh_openpipe ((int *)&wpipe
); /* 0 = child read, 1 = parent write */
2284 BLOCK_SIGNAL (SIGCHLD
, set
, oset
);
2286 coproc_pid
= make_child (savestring (tcmd
), 1);
2288 if (coproc_pid
== 0)
2293 UNBLOCK_SIGNAL (oset
);
2294 estat
= execute_in_subshell (command
, 1, wpipe
[0], rpipe
[1], fds_to_close
);
2305 /* XXX - possibly run Coproc->name through word expansion? */
2306 cp
= coproc_alloc (command
->value
.Coproc
->name
, coproc_pid
);
2307 cp
->c_rfd
= rpipe
[0];
2308 cp
->c_wfd
= wpipe
[1];
2310 SET_CLOSE_ON_EXEC (cp
->c_rfd
);
2311 SET_CLOSE_ON_EXEC (cp
->c_wfd
);
2313 coproc_setvars (cp
);
2315 UNBLOCK_SIGNAL (oset
);
2318 itrace ("execute_coproc: [%d] %s", coproc_pid
, the_printed_command
);
2321 close_pipes (pipe_in
, pipe_out
);
2322 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2323 unlink_fifo_list ();
2325 stop_pipeline (1, (COMMAND
*)NULL
);
2326 DESCRIBE_PID (coproc_pid
);
2327 run_pending_traps ();
2329 return (invert
? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
2341 /* Catch-all cleanup function for lastpipe code for unwind-protects */
2343 lastpipe_cleanup (s
)
2346 unfreeze_jobs_list ();
2350 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2352 int asynchronous
, pipe_in
, pipe_out
;
2353 struct fd_bitmap
*fds_to_close
;
2355 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
2356 int lstdin
, lastpipe_flag
, lastpipe_jid
;
2358 struct fd_bitmap
*fd_bitmap
;
2361 #if defined (JOB_CONTROL)
2363 BLOCK_CHILD (set
, oset
);
2364 #endif /* JOB_CONTROL */
2366 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2371 while (cmd
&& cmd
->type
== cm_connection
&&
2372 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
2374 /* Make a pipeline between the two commands. */
2375 if (pipe (fildes
) < 0)
2377 sys_error (_("pipe error"));
2378 #if defined (JOB_CONTROL)
2379 terminate_current_pipeline ();
2380 kill_current_pipeline ();
2381 UNBLOCK_CHILD (oset
);
2382 #endif /* JOB_CONTROL */
2383 last_command_exit_value
= EXECUTION_FAILURE
;
2384 /* The unwind-protects installed below will take care
2385 of closing all of the open file descriptors. */
2386 throw_to_top_level ();
2387 return (EXECUTION_FAILURE
); /* XXX */
2390 /* Here is a problem: with the new file close-on-exec
2391 code, the read end of the pipe (fildes[0]) stays open
2392 in the first process, so that process will never get a
2393 SIGPIPE. There is no way to signal the first process
2394 that it should close fildes[0] after forking, so it
2395 remains open. No SIGPIPE is ever sent because there
2396 is still a file descriptor open for reading connected
2397 to the pipe. We take care of that here. This passes
2398 around a bitmap of file descriptors that must be
2399 closed after making a child process in execute_simple_command. */
2401 /* We need fd_bitmap to be at least as big as fildes[0].
2402 If fildes[0] is less than fds_to_close->size, then
2403 use fds_to_close->size. */
2404 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
2405 ? fds_to_close
->size
2408 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
2410 /* Now copy the old information into the new bitmap. */
2411 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
2413 /* And mark the pipe file descriptors to be closed. */
2414 fd_bitmap
->bitmap
[fildes
[0]] = 1;
2416 /* In case there are pipe or out-of-processes errors, we
2417 want all these file descriptors to be closed when
2418 unwind-protects are run, and the storage used for the
2419 bitmaps freed up. */
2420 begin_unwind_frame ("pipe-file-descriptors");
2421 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
2422 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
2424 add_unwind_protect (close
, prev
);
2425 dummyfd
= fildes
[1];
2426 add_unwind_protect (close
, dummyfd
);
2428 #if defined (JOB_CONTROL)
2429 add_unwind_protect (restore_signal_mask
, &oset
);
2430 #endif /* JOB_CONTROL */
2432 if (ignore_return
&& cmd
->value
.Connection
->first
)
2433 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2434 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
2435 prev
, fildes
[1], fd_bitmap
);
2443 dispose_fd_bitmap (fd_bitmap
);
2444 discard_unwind_frame ("pipe-file-descriptors");
2446 cmd
= cmd
->value
.Connection
->second
;
2449 lastpid
= last_made_pid
;
2451 /* Now execute the rightmost command in the pipeline. */
2452 if (ignore_return
&& cmd
)
2453 cmd
->flags
|= CMD_IGNORE_RETURN
;
2457 begin_unwind_frame ("lastpipe-exec");
2459 /* If the `lastpipe' option is set with shopt, and job control is not
2460 enabled, execute the last element of non-async pipelines in the
2461 current shell environment. */
2462 if (lastpipe_opt
&& job_control
== 0 && asynchronous
== 0 && pipe_out
== NO_PIPE
&& prev
> 0)
2464 lstdin
= move_to_high_fd (0, 1, -1);
2467 do_piping (prev
, pipe_out
);
2469 add_unwind_protect (restore_stdin
, lstdin
);
2471 freeze_jobs_list ();
2472 lastpipe_jid
= stop_pipeline (0, (COMMAND
*)NULL
); /* XXX */
2473 add_unwind_protect (lastpipe_cleanup
, lastpipe_jid
);
2476 cmd
->flags
|= CMD_LASTPIPE
;
2479 add_unwind_protect (close
, prev
);
2481 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
2484 restore_stdin (lstdin
);
2489 #if defined (JOB_CONTROL)
2490 UNBLOCK_CHILD (oset
);
2497 #if defined (JOB_CONTROL)
2498 if (INVALID_JOB (lastpipe_jid
) == 0)
2500 append_process (savestring (the_printed_command_except_trap
), dollar_dollar_pid
, exec_result
, lastpipe_jid
);
2501 lstdin
= wait_for (lastpid
);
2504 lstdin
= wait_for_single_pid (lastpid
, 0); /* checks bgpids list */
2506 lstdin
= wait_for (lastpid
);
2509 #if defined (JOB_CONTROL)
2510 /* If wait_for removes the job from the jobs table, use result of last
2511 command as pipeline's exit status as usual. The jobs list can get
2512 frozen and unfrozen at inconvenient times if there are multiple pipelines
2513 running simultaneously. */
2514 if (INVALID_JOB (lastpipe_jid
) == 0)
2515 exec_result
= job_exit_status (lastpipe_jid
);
2516 else if (pipefail_opt
)
2517 exec_result
= exec_result
| lstdin
; /* XXX */
2518 /* otherwise we use exec_result */
2521 unfreeze_jobs_list ();
2524 discard_unwind_frame ("lastpipe-exec");
2526 return (exec_result
);
2530 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2532 int asynchronous
, pipe_in
, pipe_out
;
2533 struct fd_bitmap
*fds_to_close
;
2535 COMMAND
*tc
, *second
;
2536 int ignore_return
, exec_result
, was_error_trap
, invert
;
2537 volatile int save_line_number
;
2539 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2541 switch (command
->value
.Connection
->connector
)
2543 /* Do the first command asynchronously. */
2545 tc
= command
->value
.Connection
->first
;
2547 return (EXECUTION_SUCCESS
);
2550 tc
->flags
|= CMD_IGNORE_RETURN
;
2551 tc
->flags
|= CMD_AMPERSAND
;
2553 /* If this shell was compiled without job control support,
2554 if we are currently in a subshell via `( xxx )', or if job
2555 control is not active then the standard input for an
2556 asynchronous command is forced to /dev/null. */
2557 #if defined (JOB_CONTROL)
2558 if ((subshell_environment
|| !job_control
) && !stdin_redir
)
2561 #endif /* JOB_CONTROL */
2562 tc
->flags
|= CMD_STDIN_REDIR
;
2564 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
2567 if (tc
->flags
& CMD_STDIN_REDIR
)
2568 tc
->flags
&= ~CMD_STDIN_REDIR
;
2570 second
= command
->value
.Connection
->second
;
2574 second
->flags
|= CMD_IGNORE_RETURN
;
2576 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2581 /* Just call execute command on both sides. */
2585 if (command
->value
.Connection
->first
)
2586 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2587 if (command
->value
.Connection
->second
)
2588 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2592 execute_command (command
->value
.Connection
->first
);
2594 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
2595 asynchronous
, pipe_in
, pipe_out
,
2601 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
2602 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
2603 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2605 line_number_for_err_trap
= line_number
; /* XXX - save value? */
2606 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2610 exec_result
= EXECUTION_SUCCESS
;
2614 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
2616 last_command_exit_value
= exec_result
;
2617 save_line_number
= line_number
;
2618 line_number
= line_number_for_err_trap
;
2620 line_number
= save_line_number
;
2623 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
2625 last_command_exit_value
= exec_result
;
2626 run_pending_traps ();
2627 jump_to_top_level (ERREXIT
);
2636 /* If we have something like `a && b &' or `a || b &', run the
2637 && or || stuff in a subshell. Force a subshell and just call
2638 execute_command_internal again. Leave asynchronous on
2639 so that we get a report from the parent shell about the
2641 command
->flags
|= CMD_FORCE_SUBSHELL
;
2642 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
2646 /* Execute the first command. If the result of that is successful
2647 and the connector is AND_AND, or the result is not successful
2648 and the connector is OR_OR, then execute the second command,
2649 otherwise return. */
2652 if (command
->value
.Connection
->first
)
2653 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2655 exec_result
= execute_command (command
->value
.Connection
->first
);
2657 if (((command
->value
.Connection
->connector
== AND_AND
) &&
2658 (exec_result
== EXECUTION_SUCCESS
)) ||
2659 ((command
->value
.Connection
->connector
== OR_OR
) &&
2660 (exec_result
!= EXECUTION_SUCCESS
)))
2662 second
= command
->value
.Connection
->second
;
2663 if (ignore_return
&& second
)
2664 second
->flags
|= CMD_IGNORE_RETURN
;
2666 exec_result
= execute_command (second
);
2672 command_error ("execute_connection", CMDERR_BADCONN
, command
->value
.Connection
->connector
, 0);
2673 jump_to_top_level (DISCARD
);
2674 exec_result
= EXECUTION_FAILURE
;
2680 /* The test used to be only for interactive_shell, but we don't want to report
2681 job status when the shell is not interactive or when job control isn't
2686 if (job_control == 0 || interactive_shell == 0) \
2687 reap_dead_jobs (); \
2691 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2694 execute_for_command (for_command
)
2695 FOR_COM
*for_command
;
2697 register WORD_LIST
*releaser
, *list
;
2700 int retval
, save_line_number
;
2702 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
2705 save_line_number
= line_number
;
2706 if (check_identifier (for_command
->name
, 1) == 0)
2708 if (posixly_correct
&& interactive_shell
== 0)
2710 last_command_exit_value
= EX_BADUSAGE
;
2711 jump_to_top_level (ERREXIT
);
2713 return (EXECUTION_FAILURE
);
2717 identifier
= for_command
->name
->word
;
2719 line_number
= for_command
->line
; /* for expansion error messages */
2720 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
2722 begin_unwind_frame ("for");
2723 add_unwind_protect (dispose_words
, releaser
);
2726 if (lexical_scoping
)
2728 old_value
= copy_variable (find_variable (identifier
));
2730 add_unwind_protect (dispose_variable
, old_value
);
2734 if (for_command
->flags
& CMD_IGNORE_RETURN
)
2735 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2737 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
2741 line_number
= for_command
->line
;
2743 /* Remember what this command looks like, for debugger. */
2744 command_string_index
= 0;
2745 print_for_command_head (for_command
);
2747 if (echo_command_at_execute
)
2748 xtrace_print_for_command_head (for_command
);
2750 /* Save this command unless it's a trap command and we're not running
2752 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2754 FREE (the_printed_command_except_trap
);
2755 the_printed_command_except_trap
= savestring (the_printed_command
);
2758 retval
= run_debug_trap ();
2759 #if defined (DEBUGGER)
2760 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2761 skip the command. */
2762 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2766 this_command_name
= (char *)NULL
;
2767 /* XXX - special ksh93 for command index variable handling */
2768 v
= find_variable_last_nameref (identifier
, 1);
2769 if (v
&& nameref_p (v
))
2771 if (valid_nameref_value (list
->word
->word
, 1) == 0)
2773 sh_invalidid (list
->word
->word
);
2777 v
= bind_variable_value (v
, list
->word
->word
, 0);
2780 v
= bind_variable (identifier
, list
->word
->word
, 0);
2782 if (v
== 0 || readonly_p (v
) || noassign_p (v
))
2784 line_number
= save_line_number
;
2785 if (v
&& readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2787 last_command_exit_value
= EXECUTION_FAILURE
;
2788 jump_to_top_level (FORCE_EOF
);
2792 dispose_words (releaser
);
2793 discard_unwind_frame ("for");
2795 return (EXECUTION_FAILURE
);
2799 if (ifsname (identifier
))
2802 retval
= execute_command (for_command
->action
);
2821 line_number
= save_line_number
;
2824 if (lexical_scoping
)
2827 unbind_variable (identifier
);
2830 SHELL_VAR
*new_value
;
2832 new_value
= bind_variable (identifier
, value_cell(old_value
), 0);
2833 new_value
->attributes
= old_value
->attributes
;
2834 dispose_variable (old_value
);
2839 dispose_words (releaser
);
2840 discard_unwind_frame ("for");
2844 #if defined (ARITH_FOR_COMMAND)
2845 /* Execute an arithmetic for command. The syntax is
2847 for (( init ; step ; test ))
2852 The execution should be exactly equivalent to
2855 while eval \(\( test \)\) ; do
2861 eval_arith_for_expr (l
, okp
)
2869 new = expand_words_no_vars (l
);
2872 if (echo_command_at_execute
)
2873 xtrace_print_arith_cmd (new);
2874 this_command_name
= "(("; /* )) for expression error messages */
2876 command_string_index
= 0;
2877 print_arith_command (new);
2878 if (signal_in_progress (DEBUG_TRAP
) == 0)
2880 FREE (the_printed_command_except_trap
);
2881 the_printed_command_except_trap
= savestring (the_printed_command
);
2884 r
= run_debug_trap ();
2885 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2886 skip the command. */
2887 #if defined (DEBUGGER)
2888 if (debugging_mode
== 0 || r
== EXECUTION_SUCCESS
)
2889 expresult
= evalexp (new->word
->word
, okp
);
2897 expresult
= evalexp (new->word
->word
, okp
);
2899 dispose_words (new);
2911 execute_arith_for_command (arith_for_command
)
2912 ARITH_FOR_COM
*arith_for_command
;
2915 int expok
, body_status
, arith_lineno
, save_lineno
;
2917 body_status
= EXECUTION_SUCCESS
;
2919 save_lineno
= line_number
;
2921 if (arith_for_command
->flags
& CMD_IGNORE_RETURN
)
2922 arith_for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2924 this_command_name
= "(("; /* )) for expression error messages */
2926 /* save the starting line number of the command so we can reset
2927 line_number before executing each expression -- for $LINENO
2928 and the DEBUG trap. */
2929 line_number
= arith_lineno
= arith_for_command
->line
;
2930 if (variable_context
&& interactive_shell
)
2932 line_number
-= function_line_number
;
2933 if (line_number
< 0)
2937 /* Evaluate the initialization expression. */
2938 expresult
= eval_arith_for_expr (arith_for_command
->init
, &expok
);
2941 line_number
= save_lineno
;
2942 return (EXECUTION_FAILURE
);
2947 /* Evaluate the test expression. */
2948 line_number
= arith_lineno
;
2949 expresult
= eval_arith_for_expr (arith_for_command
->test
, &expok
);
2950 line_number
= save_lineno
;
2954 body_status
= EXECUTION_FAILURE
;
2961 /* Execute the body of the arithmetic for command. */
2963 body_status
= execute_command (arith_for_command
->action
);
2966 /* Handle any `break' or `continue' commands executed by the body. */
2980 /* Evaluate the step expression. */
2981 line_number
= arith_lineno
;
2982 expresult
= eval_arith_for_expr (arith_for_command
->step
, &expok
);
2983 line_number
= save_lineno
;
2987 body_status
= EXECUTION_FAILURE
;
2993 line_number
= save_lineno
;
2995 return (body_status
);
2999 #if defined (SELECT_COMMAND)
3000 static int LINES
, COLS
, tabsize
;
3002 #define RP_SPACE ") "
3003 #define RP_SPACE_LEN 2
3005 /* XXX - does not handle numbers > 1000000 at all. */
3006 #define NUMBER_LEN(s) \
3010 : ((s < 10000) ? 4 \
3011 : ((s < 100000) ? 5 \
3018 #if defined (HANDLE_MULTIBYTE)
3024 slen
= mbstowcs (wcstr
, s
, 0);
3027 wcstr
= (wchar_t *)xmalloc (sizeof (wchar_t) * (slen
+ 1));
3028 mbstowcs (wcstr
, s
, slen
+ 1);
3029 wclen
= wcswidth (wcstr
, slen
);
3031 return (wclen
< 0 ? STRLEN(s
) : wclen
);
3033 return (STRLEN (s
));
3038 print_index_and_element (len
, ind
, list
)
3042 register WORD_LIST
*l
;
3047 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
3049 if (l
== 0) /* don't think this can happen */
3051 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
3052 return (displen (l
->word
->word
));
3061 if ((to
/ tabsize
) > (from
/ tabsize
))
3063 putc ('\t', stderr
);
3064 from
+= tabsize
- from
% tabsize
;
3075 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
3077 int list_len
, max_elem_len
, indices_len
;
3079 int ind
, row
, elem_len
, pos
, cols
, rows
;
3080 int first_column_indices_len
, other_indices_len
;
3084 putc ('\n', stderr
);
3088 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
3091 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
3092 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
3100 first_column_indices_len
= NUMBER_LEN (rows
);
3101 other_indices_len
= indices_len
;
3103 for (row
= 0; row
< rows
; row
++)
3109 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
3110 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
3111 elem_len
+= indices_len
+ RP_SPACE_LEN
;
3113 if (ind
>= list_len
)
3115 indent (pos
+ elem_len
, pos
+ max_elem_len
);
3116 pos
+= max_elem_len
;
3118 putc ('\n', stderr
);
3122 /* Print the elements of LIST, one per line, preceded by an index from 1 to
3123 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
3124 If the number is between 1 and LIST_LEN, return that selection. If EOF
3125 is read, return a null string. If a blank line is entered, or an invalid
3126 number is entered, the loop is executed again. */
3128 select_query (list
, list_len
, prompt
, print_menu
)
3134 int max_elem_len
, indices_len
, len
;
3137 char *repl_string
, *t
;
3140 t
= get_string_value ("LINES");
3141 LINES
= (t
&& *t
) ? atoi (t
) : 24;
3143 t
= get_string_value ("COLUMNS");
3144 COLS
= (t
&& *t
) ? atoi (t
) : 80;
3147 t
= get_string_value ("TABSIZE");
3148 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
3156 for (l
= list
; l
; l
= l
->next
)
3158 len
= displen (l
->word
->word
);
3159 if (len
> max_elem_len
)
3162 indices_len
= NUMBER_LEN (list_len
);
3163 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
3168 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
3169 fprintf (stderr
, "%s", prompt
);
3173 if (read_builtin ((WORD_LIST
*)NULL
) != EXECUTION_SUCCESS
)
3176 return ((char *)NULL
);
3178 repl_string
= get_string_value ("REPLY");
3179 if (repl_string
== 0)
3180 return ((char *)NULL
);
3181 if (*repl_string
== 0)
3186 if (legal_number (repl_string
, &reply
) == 0)
3188 if (reply
< 1 || reply
> list_len
)
3191 for (l
= list
; l
&& --reply
; l
= l
->next
)
3193 return (l
->word
->word
); /* XXX - can't be null? */
3197 /* Execute a SELECT command. The syntax is:
3198 SELECT word IN list DO command_list DONE
3199 Only `break' or `return' in command_list will terminate
3202 execute_select_command (select_command
)
3203 SELECT_COM
*select_command
;
3205 WORD_LIST
*releaser
, *list
;
3207 char *identifier
, *ps3_prompt
, *selection
;
3208 int retval
, list_len
, show_menu
, save_line_number
;
3210 if (check_identifier (select_command
->name
, 1) == 0)
3211 return (EXECUTION_FAILURE
);
3213 save_line_number
= line_number
;
3214 line_number
= select_command
->line
;
3216 command_string_index
= 0;
3217 print_select_command_head (select_command
);
3219 if (echo_command_at_execute
)
3220 xtrace_print_select_command_head (select_command
);
3223 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3225 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3228 FREE (the_printed_command_except_trap
);
3229 the_printed_command_except_trap
= savestring (the_printed_command
);
3232 retval
= run_debug_trap ();
3233 #if defined (DEBUGGER)
3234 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3235 skip the command. */
3236 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3237 return (EXECUTION_SUCCESS
);
3241 identifier
= select_command
->name
->word
;
3243 /* command and arithmetic substitution, parameter and variable expansion,
3244 word splitting, pathname expansion, and quote removal. */
3245 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
3246 list_len
= list_length (list
);
3247 if (list
== 0 || list_len
== 0)
3250 dispose_words (list
);
3251 line_number
= save_line_number
;
3252 return (EXECUTION_SUCCESS
);
3255 begin_unwind_frame ("select");
3256 add_unwind_protect (dispose_words
, releaser
);
3258 if (select_command
->flags
& CMD_IGNORE_RETURN
)
3259 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
3261 retval
= EXECUTION_SUCCESS
;
3266 line_number
= select_command
->line
;
3267 ps3_prompt
= get_string_value ("PS3");
3268 if (ps3_prompt
== 0)
3272 selection
= select_query (list
, list_len
, ps3_prompt
, show_menu
);
3276 /* select_query returns EXECUTION_FAILURE if the read builtin
3277 fails, so we want to return failure in this case. */
3278 retval
= EXECUTION_FAILURE
;
3282 v
= bind_variable (identifier
, selection
, 0);
3283 if (v
== 0 || readonly_p (v
) || noassign_p (v
))
3285 if (v
&& readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
3287 last_command_exit_value
= EXECUTION_FAILURE
;
3288 jump_to_top_level (FORCE_EOF
);
3292 dispose_words (releaser
);
3293 discard_unwind_frame ("select");
3295 line_number
= save_line_number
;
3296 return (EXECUTION_FAILURE
);
3300 retval
= execute_command (select_command
->action
);
3318 #if defined (KSH_COMPATIBLE_SELECT)
3320 selection
= get_string_value ("REPLY");
3321 if (selection
&& *selection
== '\0')
3327 line_number
= save_line_number
;
3329 dispose_words (releaser
);
3330 discard_unwind_frame ("select");
3333 #endif /* SELECT_COMMAND */
3335 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
3336 The pattern_list is a linked list of pattern clauses; each clause contains
3337 some patterns to compare word_desc against, and an associated command to
3340 execute_case_command (case_command
)
3341 CASE_COM
*case_command
;
3343 register WORD_LIST
*list
;
3344 WORD_LIST
*wlist
, *es
;
3345 PATTERN_LIST
*clauses
;
3346 char *word
, *pattern
;
3347 int retval
, match
, ignore_return
, save_line_number
;
3349 save_line_number
= line_number
;
3350 line_number
= case_command
->line
;
3352 command_string_index
= 0;
3353 print_case_command_head (case_command
);
3355 if (echo_command_at_execute
)
3356 xtrace_print_case_command_head (case_command
);
3359 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3361 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3364 FREE (the_printed_command_except_trap
);
3365 the_printed_command_except_trap
= savestring (the_printed_command
);
3368 retval
= run_debug_trap();
3369 #if defined (DEBUGGER)
3370 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3371 skip the command. */
3372 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3374 line_number
= save_line_number
;
3375 return (EXECUTION_SUCCESS
);
3379 wlist
= expand_word_unsplit (case_command
->word
, 0);
3380 word
= wlist
? string_list (wlist
) : savestring ("");
3381 dispose_words (wlist
);
3383 retval
= EXECUTION_SUCCESS
;
3384 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
3386 begin_unwind_frame ("case");
3387 add_unwind_protect (xfree
, word
);
3389 #define EXIT_CASE() goto exit_case_command
3391 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
3394 for (list
= clauses
->patterns
; list
; list
= list
->next
)
3396 es
= expand_word_leave_quoted (list
->word
, 0);
3398 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
3399 pattern
= quote_string_for_globbing (es
->word
->word
, QGLOB_CVTNULL
);
3402 pattern
= (char *)xmalloc (1);
3406 /* Since the pattern does not undergo quote removal (as per
3407 Posix.2, section 3.9.4.3), the strmatch () call must be able
3408 to recognize backslashes as escape characters. */
3409 match
= strmatch (pattern
, word
, FNMATCH_EXTFLAG
|FNMATCH_IGNCASE
) != FNM_NOMATCH
;
3418 if (clauses
->action
&& ignore_return
)
3419 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
3420 retval
= execute_command (clauses
->action
);
3422 while ((clauses
->flags
& CASEPAT_FALLTHROUGH
) && (clauses
= clauses
->next
));
3423 if (clauses
== 0 || (clauses
->flags
& CASEPAT_TESTNEXT
) == 0)
3435 discard_unwind_frame ("case");
3436 line_number
= save_line_number
;
3443 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3444 Repeatedly execute action while executing test produces
3445 EXECUTION_SUCCESS. */
3447 execute_while_command (while_command
)
3448 WHILE_COM
*while_command
;
3450 return (execute_while_or_until (while_command
, CMD_WHILE
));
3453 /* UNTIL is just like WHILE except that the test result is negated. */
3455 execute_until_command (while_command
)
3456 WHILE_COM
*while_command
;
3458 return (execute_while_or_until (while_command
, CMD_UNTIL
));
3461 /* The body for both while and until. The only difference between the
3462 two is that the test value is treated differently. TYPE is
3463 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3464 be EXECUTION_SUCCESS if no commands in the body are executed, and
3465 the status of the last command executed in the body otherwise. */
3467 execute_while_or_until (while_command
, type
)
3468 WHILE_COM
*while_command
;
3471 int return_value
, body_status
;
3473 body_status
= EXECUTION_SUCCESS
;
3476 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
3477 if (while_command
->flags
& CMD_IGNORE_RETURN
)
3478 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
3482 return_value
= execute_command (while_command
->test
);
3485 /* Need to handle `break' in the test when we would break out of the
3486 loop. The job control code will set `breaking' to loop_level
3487 when a job in a loop is stopped with SIGTSTP. If the stopped job
3488 is in the loop test, `breaking' will not be reset unless we do
3489 this, and the shell will cease to execute commands. The same holds
3490 true for `continue'. */
3491 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
3499 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
3509 body_status
= execute_command (while_command
->action
);
3527 return (body_status
);
3530 /* IF test THEN command [ELSE command].
3531 IF also allows ELIF in the place of ELSE IF, but
3532 the parser makes *that* stupidity transparent. */
3534 execute_if_command (if_command
)
3537 int return_value
, save_line_number
;
3539 save_line_number
= line_number
;
3540 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
3541 return_value
= execute_command (if_command
->test
);
3542 line_number
= save_line_number
;
3544 if (return_value
== EXECUTION_SUCCESS
)
3548 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
3549 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
3551 return (execute_command (if_command
->true_case
));
3557 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
3558 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
3560 return (execute_command (if_command
->false_case
));
3564 #if defined (DPAREN_ARITHMETIC)
3566 execute_arith_command (arith_command
)
3567 ARITH_COM
*arith_command
;
3569 int expok
, save_line_number
, retval
;
3576 save_line_number
= line_number
;
3577 this_command_name
= "(("; /* )) */
3578 line_number
= arith_command
->line
;
3579 /* If we're in a function, update the line number information. */
3580 if (variable_context
&& interactive_shell
)
3582 line_number
-= function_line_number
;
3583 if (line_number
< 0)
3587 command_string_index
= 0;
3588 print_arith_command (arith_command
->exp
);
3590 if (signal_in_progress (DEBUG_TRAP
) == 0)
3592 FREE (the_printed_command_except_trap
);
3593 the_printed_command_except_trap
= savestring (the_printed_command
);
3596 /* Run the debug trap before each arithmetic command, but do it after we
3597 update the line number information and before we expand the various
3598 words in the expression. */
3599 retval
= run_debug_trap ();
3600 #if defined (DEBUGGER)
3601 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3602 skip the command. */
3603 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3605 line_number
= save_line_number
;
3606 return (EXECUTION_SUCCESS
);
3610 new = expand_words_no_vars (arith_command
->exp
);
3612 /* If we're tracing, make a new word list with `((' at the front and `))'
3613 at the back and print it. */
3614 if (echo_command_at_execute
)
3615 xtrace_print_arith_cmd (new);
3619 exp
= new->next
? string_list (new) : new->word
->word
;
3620 expresult
= evalexp (exp
, &expok
);
3621 line_number
= save_line_number
;
3622 if (exp
!= new->word
->word
)
3624 dispose_words (new);
3633 return (EXECUTION_FAILURE
);
3635 return (expresult
== 0 ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
3637 #endif /* DPAREN_ARITHMETIC */
3639 #if defined (COND_COMMAND)
3641 static char * const nullstr
= "";
3643 /* XXX - can COND ever be NULL when this is called? */
3645 execute_cond_node (cond
)
3648 int result
, invert
, patmatch
, rmatch
, mflags
, ignore
;
3654 invert
= (cond
->flags
& CMD_INVERT_RETURN
);
3655 ignore
= (cond
->flags
& CMD_IGNORE_RETURN
);
3659 cond
->left
->flags
|= CMD_IGNORE_RETURN
;
3661 cond
->right
->flags
|= CMD_IGNORE_RETURN
;
3664 if (cond
->type
== COND_EXPR
)
3665 result
= execute_cond_node (cond
->left
);
3666 else if (cond
->type
== COND_OR
)
3668 result
= execute_cond_node (cond
->left
);
3669 if (result
!= EXECUTION_SUCCESS
)
3670 result
= execute_cond_node (cond
->right
);
3672 else if (cond
->type
== COND_AND
)
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_UNARY
)
3681 comsub_ignore_return
++;
3682 arg1
= cond_expand_word (cond
->left
->op
, 0);
3684 comsub_ignore_return
--;
3687 if (echo_command_at_execute
)
3688 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, (char *)NULL
);
3689 result
= unary_test (cond
->op
->word
, arg1
) ? EXECUTION_SUCCESS
: EXECUTION_FAILURE
;
3690 if (arg1
!= nullstr
)
3693 else if (cond
->type
== COND_BINARY
)
3696 patmatch
= (((cond
->op
->word
[1] == '=') && (cond
->op
->word
[2] == '\0') &&
3697 (cond
->op
->word
[0] == '!' || cond
->op
->word
[0] == '=')) ||
3698 (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '\0'));
3699 #if defined (COND_REGEXP)
3700 rmatch
= (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '~' &&
3701 cond
->op
->word
[2] == '\0');
3705 comsub_ignore_return
++;
3706 arg1
= cond_expand_word (cond
->left
->op
, 0);
3708 comsub_ignore_return
--;
3712 comsub_ignore_return
++;
3713 arg2
= cond_expand_word (cond
->right
->op
,
3714 (rmatch
&& shell_compatibility_level
> 31) ? 2 : (patmatch
? 1 : 0));
3716 comsub_ignore_return
--;
3720 if (echo_command_at_execute
)
3721 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, arg2
);
3723 #if defined (COND_REGEXP)
3726 mflags
= SHMAT_PWARN
;
3727 #if defined (ARRAY_VARS)
3728 mflags
|= SHMAT_SUBEXP
;
3732 t1
= strescape(arg1
);
3733 t2
= strescape(arg2
);
3734 itrace("execute_cond_node: sh_regmatch on `%s' and `%s'", t1
, t2
);
3739 result
= sh_regmatch (arg1
, arg2
, mflags
);
3742 #endif /* COND_REGEXP */
3747 result
= binary_test (cond
->op
->word
, arg1
, arg2
, TEST_PATMATCH
|TEST_ARITHEXP
|TEST_LOCALE
)
3749 : EXECUTION_FAILURE
;
3752 if (arg1
!= nullstr
)
3754 if (arg2
!= nullstr
)
3759 command_error ("execute_cond_node", CMDERR_BADTYPE
, cond
->type
, 0);
3760 jump_to_top_level (DISCARD
);
3761 result
= EXECUTION_FAILURE
;
3765 result
= (result
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
;
3771 execute_cond_command (cond_command
)
3772 COND_COM
*cond_command
;
3774 int retval
, save_line_number
;
3776 retval
= EXECUTION_SUCCESS
;
3777 save_line_number
= line_number
;
3779 this_command_name
= "[[";
3780 line_number
= cond_command
->line
;
3781 /* If we're in a function, update the line number information. */
3782 if (variable_context
&& interactive_shell
)
3784 line_number
-= function_line_number
;
3785 if (line_number
< 0)
3788 command_string_index
= 0;
3789 print_cond_command (cond_command
);
3791 if (signal_in_progress (DEBUG_TRAP
) == 0)
3793 FREE (the_printed_command_except_trap
);
3794 the_printed_command_except_trap
= savestring (the_printed_command
);
3797 /* Run the debug trap before each conditional command, but do it after we
3798 update the line number information. */
3799 retval
= run_debug_trap ();
3800 #if defined (DEBUGGER)
3801 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3802 skip the command. */
3803 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3805 line_number
= save_line_number
;
3806 return (EXECUTION_SUCCESS
);
3811 debug_print_cond_command (cond_command
);
3814 last_command_exit_value
= retval
= execute_cond_node (cond_command
);
3815 line_number
= save_line_number
;
3818 #endif /* COND_COMMAND */
3828 var
= bind_variable ("_", arg
, 0);
3830 VUNSETATTR (var
, att_exported
);
3833 /* Execute a null command. Fork a subshell if the command uses pipes or is
3834 to be run asynchronously. This handles all the side effects that are
3835 supposed to take place. */
3837 execute_null_command (redirects
, pipe_in
, pipe_out
, async
)
3838 REDIRECT
*redirects
;
3839 int pipe_in
, pipe_out
, async
;
3845 for (forcefork
= 0, rd
= redirects
; rd
; rd
= rd
->next
)
3846 forcefork
+= rd
->rflags
& REDIR_VARASSIGN
;
3848 if (forcefork
|| pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
3850 /* We have a null command, but we really want a subshell to take
3851 care of it. Just fork, do piping and redirections, and exit. */
3852 if (make_child ((char *)NULL
, async
) == 0)
3854 /* Cancel traps, in trap.c. */
3855 restore_original_signals (); /* XXX */
3857 do_piping (pipe_in
, pipe_out
);
3859 #if defined (COPROCESS_SUPPORT)
3863 subshell_environment
= 0;
3865 subshell_environment
|= SUBSHELL_ASYNC
;
3866 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3867 subshell_environment
|= SUBSHELL_PIPE
;
3869 if (do_redirections (redirects
, RX_ACTIVE
) == 0)
3870 exit (EXECUTION_SUCCESS
);
3872 exit (EXECUTION_FAILURE
);
3876 close_pipes (pipe_in
, pipe_out
);
3877 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3878 if (pipe_out
== NO_PIPE
)
3879 unlink_fifo_list ();
3881 return (EXECUTION_SUCCESS
);
3886 /* Even if there aren't any command names, pretend to do the
3887 redirections that are specified. The user expects the side
3888 effects to take place. If the redirections fail, then return
3889 failure. Otherwise, if a command substitution took place while
3890 expanding the command or a redirection, return the value of that
3891 substitution. Otherwise, return EXECUTION_SUCCESS. */
3893 r
= do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
);
3894 cleanup_redirects (redirection_undo_list
);
3895 redirection_undo_list
= (REDIRECT
*)NULL
;
3898 return (EXECUTION_FAILURE
);
3899 else if (last_command_subst_pid
!= NO_PID
)
3900 return (last_command_exit_value
);
3902 return (EXECUTION_SUCCESS
);
3906 /* This is a hack to suppress word splitting for assignment statements
3907 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3909 fix_assignment_words (words
)
3912 WORD_LIST
*w
, *wcmd
;
3914 int assoc
, global
, array
, integer
;
3920 assoc
= global
= array
= integer
= 0;
3922 /* Skip over assignment statements preceding a command name */
3924 for (wcmd
= words
; wcmd
; wcmd
= wcmd
->next
)
3925 if ((wcmd
->word
->flags
& W_ASSIGNMENT
) == 0)
3927 /* Posix (post-2008) says that `command' doesn't change whether
3928 or not the builtin it shadows is a `declaration command', even
3929 though it removes other special builtin properties. In Posix
3930 mode, we skip over one or more instances of `command' and
3931 deal with the next word as the assignment builtin. */
3932 while (posixly_correct
&& wcmd
&& wcmd
->word
&& wcmd
->word
->word
&& STREQ (wcmd
->word
->word
, "command"))
3935 for (w
= wcmd
; w
; w
= w
->next
)
3936 if (w
->word
->flags
& W_ASSIGNMENT
)
3938 /* Lazy builtin lookup, only do it if we find an assignment */
3941 b
= builtin_address_internal (wcmd
->word
->word
, 0);
3942 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3944 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3945 wcmd
->word
->flags
|= W_ASSNBLTIN
;
3947 w
->word
->flags
|= (W_NOSPLIT
|W_NOGLOB
|W_TILDEEXP
|W_ASSIGNARG
);
3948 #if defined (ARRAY_VARS)
3950 w
->word
->flags
|= W_ASSIGNASSOC
;
3952 w
->word
->flags
|= W_ASSIGNARRAY
;
3955 w
->word
->flags
|= W_ASSNGLOBAL
;
3957 /* If we have an assignment builtin that does not create local variables,
3958 make sure we create global variables even if we internally call
3960 if (b
&& ((b
->flags
& (ASSIGNMENT_BUILTIN
|LOCALVAR_BUILTIN
)) == ASSIGNMENT_BUILTIN
))
3961 w
->word
->flags
|= W_ASSNGLOBAL
;
3963 #if defined (ARRAY_VARS)
3964 /* Note that we saw an associative array option to a builtin that takes
3965 assignment statements. This is a bit of a kludge. */
3966 else if (w
->word
->word
[0] == '-' && (strpbrk (w
->word
->word
+1, "Aag") != 0))
3968 else if (w
->word
->word
[0] == '-' && strchr (w
->word
->word
+1, 'g'))
3973 b
= builtin_address_internal (wcmd
->word
->word
, 0);
3974 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3976 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3977 wcmd
->word
->flags
|= W_ASSNBLTIN
;
3979 if ((wcmd
->word
->flags
& W_ASSNBLTIN
) && strchr (w
->word
->word
+1, 'A'))
3981 else if ((wcmd
->word
->flags
& W_ASSNBLTIN
) && strchr (w
->word
->word
+1, 'a'))
3983 if ((wcmd
->word
->flags
& W_ASSNBLTIN
) && strchr (w
->word
->word
+1, 'g'))
3988 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3989 to PATHNAME, is a directory. Used by the autocd code below. */
3991 is_dirname (pathname
)
3997 temp
= search_for_command (pathname
, 0);
3998 ret
= temp
? file_isdir (temp
) : file_isdir (pathname
);
4003 /* The meaty part of all the executions. We have to start hacking the
4004 real execution of commands here. Fork a process, set things up,
4005 execute the command. */
4007 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
4008 SIMPLE_COM
*simple_command
;
4009 int pipe_in
, pipe_out
, async
;
4010 struct fd_bitmap
*fds_to_close
;
4012 WORD_LIST
*words
, *lastword
;
4013 char *command_line
, *lastarg
, *temp
;
4014 int first_word_quoted
, result
, builtin_is_special
, already_forked
, dofork
;
4015 pid_t old_last_async_pid
;
4016 sh_builtin_func_t
*builtin
;
4018 volatile int old_builtin
, old_command_builtin
;
4020 result
= EXECUTION_SUCCESS
;
4021 special_builtin_failed
= builtin_is_special
= 0;
4022 command_line
= (char *)0;
4026 /* If we're in a function, update the line number information. */
4027 if (variable_context
&& interactive_shell
&& sourcelevel
== 0)
4029 line_number
-= function_line_number
;
4030 if (line_number
< 0)
4034 /* Remember what this command line looks like at invocation. */
4035 command_string_index
= 0;
4036 print_simple_command (simple_command
);
4039 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
4041 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
4044 FREE (the_printed_command_except_trap
);
4045 the_printed_command_except_trap
= the_printed_command
? savestring (the_printed_command
) : (char *)0;
4048 /* Run the debug trap before each simple command, but do it after we
4049 update the line number information. */
4050 result
= run_debug_trap ();
4051 #if defined (DEBUGGER)
4052 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4053 skip the command. */
4054 if (debugging_mode
&& result
!= EXECUTION_SUCCESS
)
4055 return (EXECUTION_SUCCESS
);
4059 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
) : 0;
4061 last_command_subst_pid
= NO_PID
;
4062 old_last_async_pid
= last_asynchronous_pid
;
4064 already_forked
= dofork
= 0;
4066 /* If we're in a pipeline or run in the background, set DOFORK so we
4067 make the child early, before word expansion. This keeps assignment
4068 statements from affecting the parent shell's environment when they
4070 dofork
= pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
;
4072 /* Something like `%2 &' should restart job 2 in the background, not cause
4073 the shell to fork here. */
4074 if (dofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&&
4075 simple_command
->words
&& simple_command
->words
->word
&&
4076 simple_command
->words
->word
->word
&&
4077 (simple_command
->words
->word
->word
[0] == '%'))
4082 /* Do this now, because execute_disk_command will do it anyway in the
4083 vast majority of cases. */
4084 maybe_make_export_env ();
4086 /* Don't let a DEBUG trap overwrite the command string to be saved with
4087 the process/job associated with this child. */
4088 if (make_child (savestring (the_printed_command_except_trap
), async
) == 0)
4091 simple_command
->flags
|= CMD_NO_FORK
;
4093 subshell_environment
= SUBSHELL_FORK
; /* XXX */
4094 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4095 subshell_environment
|= SUBSHELL_PIPE
;
4097 subshell_environment
|= SUBSHELL_ASYNC
;
4099 /* We need to do this before piping to handle some really
4100 pathological cases where one of the pipe file descriptors
4103 close_fd_bitmap (fds_to_close
);
4105 /* If we fork because of an input pipe, note input pipe for later to
4106 inhibit async commands from redirecting stdin from /dev/null */
4107 stdin_redir
|= pipe_in
!= NO_PIPE
;
4109 do_piping (pipe_in
, pipe_out
);
4110 pipe_in
= pipe_out
= NO_PIPE
;
4111 #if defined (COPROCESS_SUPPORT)
4115 last_asynchronous_pid
= old_last_async_pid
;
4120 subshell_level
++; /* not for pipes yet */
4124 /* Don't let simple commands that aren't the last command in a
4125 pipeline change $? for the rest of the pipeline (or at all). */
4126 if (pipe_out
!= NO_PIPE
)
4127 result
= last_command_exit_value
;
4128 close_pipes (pipe_in
, pipe_out
);
4129 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4130 /* Close /dev/fd file descriptors in the parent after forking the
4131 last child in a (possibly one-element) pipeline. Defer this
4132 until any running shell function completes. */
4133 if (pipe_out
== NO_PIPE
&& variable_context
== 0) /* XXX */
4134 unlink_fifo_list (); /* XXX */
4136 command_line
= (char *)NULL
; /* don't free this. */
4137 bind_lastarg ((char *)NULL
);
4144 /* If we are re-running this as the result of executing the `command'
4145 builtin, do not expand the command words a second time. */
4146 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
4148 current_fds_to_close
= fds_to_close
;
4149 fix_assignment_words (simple_command
->words
);
4150 /* Pass the ignore return flag down to command substitutions */
4151 if (simple_command
->flags
& CMD_IGNORE_RETURN
) /* XXX */
4152 comsub_ignore_return
++;
4153 words
= expand_words (simple_command
->words
);
4154 if (simple_command
->flags
& CMD_IGNORE_RETURN
)
4155 comsub_ignore_return
--;
4156 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
4159 words
= copy_word_list (simple_command
->words
);
4161 /* It is possible for WORDS not to have anything left in it.
4162 Perhaps all the words consisted of `$foo', and there was
4163 no variable `$foo'. */
4166 this_command_name
= 0;
4167 result
= execute_null_command (simple_command
->redirects
,
4169 already_forked
? 0 : async
);
4174 bind_lastarg ((char *)NULL
);
4175 set_pipestatus_from_exit (result
);
4180 lastarg
= (char *)NULL
;
4182 begin_unwind_frame ("simple-command");
4184 if (echo_command_at_execute
)
4185 xtrace_print_word_list (words
, 1);
4187 builtin
= (sh_builtin_func_t
*)NULL
;
4188 func
= (SHELL_VAR
*)NULL
;
4189 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
4191 /* Posix.2 says special builtins are found before functions. We
4192 don't set builtin_is_special anywhere other than here, because
4193 this path is followed only when the `command' builtin is *not*
4194 being used, and we don't want to exit the shell if a special
4195 builtin executed with `command builtin' fails. `command' is not
4196 a special builtin. */
4197 if (posixly_correct
)
4199 builtin
= find_special_builtin (words
->word
->word
);
4201 builtin_is_special
= 1;
4204 func
= find_function (words
->word
->word
);
4207 /* In POSIX mode, assignment errors in the temporary environment cause a
4208 non-interactive shell to exit. */
4209 if (posixly_correct
&& builtin_is_special
&& interactive_shell
== 0 && tempenv_assign_error
)
4211 last_command_exit_value
= EXECUTION_FAILURE
;
4212 jump_to_top_level (ERREXIT
);
4214 tempenv_assign_error
= 0; /* don't care about this any more */
4216 add_unwind_protect (dispose_words
, words
);
4219 /* Bind the last word in this command to "$_" after execution. */
4220 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
4222 lastarg
= lastword
->word
->word
;
4224 #if defined (JOB_CONTROL)
4225 /* Is this command a job control related thing? */
4226 if (words
->word
->word
[0] == '%' && already_forked
== 0)
4228 this_command_name
= async
? "bg" : "fg";
4229 last_shell_builtin
= this_shell_builtin
;
4230 this_shell_builtin
= builtin_address (this_command_name
);
4231 result
= (*this_shell_builtin
) (words
);
4235 /* One other possibililty. The user may want to resume an existing job.
4236 If they do, find out whether this word is a candidate for a running
4238 if (job_control
&& already_forked
== 0 && async
== 0 &&
4239 !first_word_quoted
&&
4241 words
->word
->word
[0] &&
4242 !simple_command
->redirects
&&
4243 pipe_in
== NO_PIPE
&&
4244 pipe_out
== NO_PIPE
&&
4245 (temp
= get_string_value ("auto_resume")))
4247 int job
, jflags
, started_status
;
4249 jflags
= JM_STOPPED
|JM_FIRSTMATCH
;
4250 if (STREQ (temp
, "exact"))
4252 else if (STREQ (temp
, "substring"))
4253 jflags
|= JM_SUBSTRING
;
4255 jflags
|= JM_PREFIX
;
4256 job
= get_job_by_name (words
->word
->word
, jflags
);
4259 run_unwind_frame ("simple-command");
4260 this_command_name
= "fg";
4261 last_shell_builtin
= this_shell_builtin
;
4262 this_shell_builtin
= builtin_address ("fg");
4264 started_status
= start_job (job
, 1);
4265 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
4268 #endif /* JOB_CONTROL */
4271 /* Remember the name of this command globally. */
4272 this_command_name
= words
->word
->word
;
4276 /* This command could be a shell builtin or a user-defined function.
4277 We have already found special builtins by this time, so we do not
4278 set builtin_is_special. If this is a function or builtin, and we
4279 have pipes, then fork a subshell in here. Otherwise, just execute
4280 the command directly. */
4281 if (func
== 0 && builtin
== 0)
4282 builtin
= find_shell_builtin (this_command_name
);
4284 last_shell_builtin
= this_shell_builtin
;
4285 this_shell_builtin
= builtin
;
4287 if (builtin
|| func
)
4291 old_builtin
= executing_builtin
;
4292 old_command_builtin
= executing_command_builtin
;
4293 unwind_protect_int (executing_builtin
); /* modified in execute_builtin */
4294 unwind_protect_int (executing_command_builtin
); /* ditto */
4298 /* reset_terminating_signals (); */ /* XXX */
4299 /* Reset the signal handlers in the child, but don't free the
4300 trap strings. Set a flag noting that we have to free the
4301 trap strings if we run trap to change a signal disposition. */
4302 reset_signal_handlers ();
4303 subshell_environment
|= SUBSHELL_RESETTRAP
;
4307 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
4308 pipe_in
== NO_PIPE
&&
4309 (stdin_redirects (simple_command
->redirects
) == 0))
4310 async_redirect_stdin ();
4311 setup_async_signals ();
4316 execute_subshell_builtin_or_function
4317 (words
, simple_command
->redirects
, builtin
, func
,
4318 pipe_in
, pipe_out
, async
, fds_to_close
,
4319 simple_command
->flags
);
4324 result
= execute_builtin_or_function
4325 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
4326 simple_command
->flags
);
4329 if (result
> EX_SHERRBASE
)
4336 /* These errors cause non-interactive posix mode shells to exit */
4337 if (posixly_correct
&& builtin_is_special
&& interactive_shell
== 0)
4339 last_command_exit_value
= EXECUTION_FAILURE
;
4340 jump_to_top_level (ERREXIT
);
4343 result
= builtin_status (result
);
4344 if (builtin_is_special
)
4345 special_builtin_failed
= 1;
4347 /* In POSIX mode, if there are assignment statements preceding
4348 a special builtin, they persist after the builtin
4350 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
4351 merge_temporary_env ();
4355 if (result
== EX_USAGE
)
4356 result
= EX_BADUSAGE
;
4357 else if (result
> EX_SHERRBASE
)
4358 result
= EXECUTION_FAILURE
;
4361 set_pipestatus_from_exit (result
);
4367 if (autocd
&& interactive
&& words
->word
&& is_dirname (words
->word
->word
))
4369 words
= make_word_list (make_word ("--"), words
);
4370 words
= make_word_list (make_word ("cd"), words
);
4371 xtrace_print_word_list (words
, 0);
4372 func
= find_function ("cd");
4376 if (command_line
== 0)
4377 command_line
= savestring (the_printed_command_except_trap
? the_printed_command_except_trap
: "");
4379 #if defined (PROCESS_SUBSTITUTION)
4380 /* The old code did not test already_forked and only did this if
4381 subshell_environment&SUBSHELL_COMSUB != 0 (comsubs and procsubs). Other
4382 uses of the no-fork optimization left FIFOs in $TMPDIR */
4383 if (already_forked
== 0 && (simple_command
->flags
& CMD_NO_FORK
) && fifos_pending() > 0)
4384 simple_command
->flags
&= ~CMD_NO_FORK
;
4386 result
= execute_disk_command (words
, simple_command
->redirects
, command_line
,
4387 pipe_in
, pipe_out
, async
, fds_to_close
,
4388 simple_command
->flags
);
4391 bind_lastarg (lastarg
);
4392 FREE (command_line
);
4393 dispose_words (words
);
4396 executing_builtin
= old_builtin
;
4397 executing_command_builtin
= old_command_builtin
;
4399 discard_unwind_frame ("simple-command");
4400 this_command_name
= (char *)NULL
; /* points to freed memory now */
4404 /* Translate the special builtin exit statuses. We don't really need a
4405 function for this; it's a placeholder for future work. */
4407 builtin_status (result
)
4421 r
= EXECUTION_FAILURE
;
4424 r
= EXECUTION_SUCCESS
;
4431 execute_builtin (builtin
, words
, flags
, subshell
)
4432 sh_builtin_func_t
*builtin
;
4434 int flags
, subshell
;
4436 int result
, eval_unwind
, ignexit_flag
, old_e_flag
;
4442 /* The eval builtin calls parse_and_execute, which does not know about
4443 the setting of flags, and always calls the execution functions with
4444 flags that will exit the shell on an error if -e is set. If the
4445 eval builtin is being called, and we're supposed to ignore the exit
4446 value of the command, we turn the -e flag off ourselves and disable
4447 the ERR trap, then restore them when the command completes. This is
4448 also a problem (as below) for the command and source/. builtins. */
4449 if (subshell
== 0 && (flags
& CMD_IGNORE_RETURN
) &&
4450 (builtin
== eval_builtin
|| builtin
== command_builtin
|| builtin
== source_builtin
))
4452 begin_unwind_frame ("eval_builtin");
4453 unwind_protect_int (exit_immediately_on_error
);
4454 unwind_protect_int (builtin_ignoring_errexit
);
4455 error_trap
= TRAP_STRING (ERROR_TRAP
);
4458 error_trap
= savestring (error_trap
);
4459 add_unwind_protect (xfree
, error_trap
);
4460 add_unwind_protect (set_error_trap
, error_trap
);
4461 restore_default_signal (ERROR_TRAP
);
4463 exit_immediately_on_error
= 0;
4464 ignexit_flag
= builtin_ignoring_errexit
;
4465 builtin_ignoring_errexit
= 1;
4471 /* The temporary environment for a builtin is supposed to apply to
4472 all commands executed by that builtin. Currently, this is a
4473 problem only with the `unset', `source' and `eval' builtins.
4474 `mapfile' is a special case because it uses evalstring (same as
4475 eval or source) to run its callbacks. */
4476 isbltinenv
= (builtin
== source_builtin
|| builtin
== eval_builtin
|| builtin
== unset_builtin
|| builtin
== mapfile_builtin
);
4481 begin_unwind_frame ("builtin_env");
4485 push_scope (VC_BLTNENV
, temporary_env
);
4487 add_unwind_protect (pop_scope
, (flags
& CMD_COMMAND_BUILTIN
) ? 0 : "1");
4488 temporary_env
= (HASH_TABLE
*)NULL
;
4492 if (subshell
== 0 && builtin
== eval_builtin
)
4494 if (evalnest_max
> 0 && evalnest
>= evalnest_max
)
4496 internal_error (_("eval: maximum eval nesting level exceeded (%d)"), evalnest
);
4498 jump_to_top_level (DISCARD
);
4500 unwind_protect_int (evalnest
);
4501 /* The test for subshell == 0 above doesn't make a difference */
4502 evalnest
++; /* execute_subshell_builtin_or_function sets this to 0 */
4504 else if (subshell
== 0 && builtin
== source_builtin
)
4506 if (sourcenest_max
> 0 && sourcenest
>= sourcenest_max
)
4508 internal_error (_("%s: maximum source nesting level exceeded (%d)"), this_command_name
, sourcenest
);
4510 jump_to_top_level (DISCARD
);
4512 unwind_protect_int (sourcenest
);
4513 /* The test for subshell == 0 above doesn't make a difference */
4514 sourcenest
++; /* execute_subshell_builtin_or_function sets this to 0 */
4517 /* `return' does a longjmp() back to a saved environment in execute_function.
4518 If a variable assignment list preceded the command, and the shell is
4519 running in POSIX mode, we need to merge that into the shell_variables
4520 table, since `return' is a POSIX special builtin. */
4521 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
4523 begin_unwind_frame ("return_temp_env");
4524 add_unwind_protect (merge_temporary_env
, (char *)NULL
);
4527 executing_builtin
++;
4528 executing_command_builtin
|= builtin
== command_builtin
;
4529 result
= ((*builtin
) (words
->next
));
4531 /* This shouldn't happen, but in case `return' comes back instead of
4532 longjmp'ing, we need to unwind. */
4533 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
4534 discard_unwind_frame ("return_temp_env");
4536 if (subshell
== 0 && isbltinenv
)
4537 run_unwind_frame ("builtin_env");
4541 builtin_ignoring_errexit
= ignexit_flag
;
4542 exit_immediately_on_error
= builtin_ignoring_errexit
? 0 : errexit_flag
;
4545 set_error_trap (error_trap
);
4548 discard_unwind_frame ("eval_builtin");
4555 maybe_restore_getopt_state (gs
)
4556 sh_getopt_state_t
*gs
;
4560 /* If we have a local copy of OPTIND and it's at the right (current)
4561 context, then we restore getopt's internal state. If not, we just
4562 let it go. We know there is a local OPTIND if gs->gs_flags & 1.
4563 This is set below in execute_function() before the context is run. */
4564 if (gs
->gs_flags
& 1)
4565 sh_getopt_restore_istate (gs
);
4570 #if defined (ARRAY_VARS)
4572 restore_funcarray_state (fa
)
4573 struct func_array_state
*fa
;
4578 array_pop (fa
->source_a
);
4579 array_pop (fa
->lineno_a
);
4581 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv
, funcname_a
);
4582 if (nfv
== fa
->funcname_v
)
4583 array_pop (funcname_a
);
4590 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
4594 struct fd_bitmap
*fds_to_close
;
4595 int async
, subshell
;
4597 int return_val
, result
;
4598 COMMAND
*tc
, *fc
, *save_current
;
4599 char *debug_trap
, *error_trap
, *return_trap
;
4600 #if defined (ARRAY_VARS)
4601 SHELL_VAR
*funcname_v
, *bash_source_v
, *bash_lineno_v
;
4603 volatile ARRAY
*bash_source_a
;
4604 volatile ARRAY
*bash_lineno_a
;
4605 struct func_array_state
*fa
;
4607 FUNCTION_DEF
*shell_fn
;
4609 sh_getopt_state_t
*gs
;
4614 if (funcnest_max
> 0 && funcnest
>= funcnest_max
)
4616 internal_error (_("%s: maximum function nesting level exceeded (%d)"), var
->name
, funcnest
);
4617 funcnest
= 0; /* XXX - should we reset it somewhere else? */
4618 jump_to_top_level (DISCARD
);
4621 #if defined (ARRAY_VARS)
4622 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v
, funcname_a
);
4623 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v
, bash_source_a
);
4624 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v
, bash_lineno_a
);
4627 tc
= (COMMAND
*)copy_command (function_cell (var
));
4628 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
4629 tc
->flags
|= CMD_IGNORE_RETURN
;
4631 gs
= sh_getopt_save_istate ();
4634 begin_unwind_frame ("function_calling");
4635 push_context (var
->name
, subshell
, temporary_env
);
4636 /* This has to be before the pop_context(), because the unwinding of
4637 local variables may cause the restore of a local declaration of
4638 OPTIND to force a getopts state reset. */
4639 add_unwind_protect (maybe_restore_getopt_state
, gs
);
4640 add_unwind_protect (pop_context
, (char *)NULL
);
4641 unwind_protect_int (line_number
);
4642 unwind_protect_int (line_number_for_err_trap
);
4643 unwind_protect_int (function_line_number
);
4644 unwind_protect_int (return_catch_flag
);
4645 unwind_protect_jmp_buf (return_catch
);
4646 add_unwind_protect (dispose_command
, (char *)tc
);
4647 unwind_protect_pointer (this_shell_function
);
4648 unwind_protect_int (funcnest
);
4649 unwind_protect_int (loop_level
);
4652 push_context (var
->name
, subshell
, temporary_env
); /* don't unwind-protect for subshells */
4654 temporary_env
= (HASH_TABLE
*)NULL
;
4656 this_shell_function
= var
;
4657 make_funcname_visible (1);
4659 debug_trap
= TRAP_STRING(DEBUG_TRAP
);
4660 error_trap
= TRAP_STRING(ERROR_TRAP
);
4661 return_trap
= TRAP_STRING(RETURN_TRAP
);
4663 /* The order of the unwind protects for debug_trap, error_trap and
4664 return_trap is important here! unwind-protect commands are run
4665 in reverse order of registration. If this causes problems, take
4666 out the xfree unwind-protect calls and live with the small memory leak. */
4668 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4669 if the function has the trace attribute set, it inherits the DEBUG trap */
4670 if (debug_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
4674 debug_trap
= savestring (debug_trap
);
4675 add_unwind_protect (xfree
, debug_trap
);
4676 add_unwind_protect (maybe_set_debug_trap
, debug_trap
);
4678 restore_default_signal (DEBUG_TRAP
);
4681 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4682 if (error_trap
&& error_trace_mode
== 0)
4686 error_trap
= savestring (error_trap
);
4687 add_unwind_protect (xfree
, error_trap
);
4688 add_unwind_protect (maybe_set_error_trap
, error_trap
);
4690 restore_default_signal (ERROR_TRAP
);
4693 /* Shell functions inherit the RETURN trap if function tracing is on
4694 globally or on individually for this function. */
4696 if (return_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
4698 if (return_trap
&& (signal_in_progress (DEBUG_TRAP
) || ((trace_p (var
) == 0) && function_trace_mode
== 0)))
4703 return_trap
= savestring (return_trap
);
4704 add_unwind_protect (xfree
, return_trap
);
4705 add_unwind_protect (maybe_set_return_trap
, return_trap
);
4707 restore_default_signal (RETURN_TRAP
);
4711 #if defined (ARRAY_VARS)
4712 /* This is quite similar to the code in shell.c and elsewhere. */
4713 shell_fn
= find_function_def (this_shell_function
->name
);
4714 sfile
= shell_fn
? shell_fn
->source_file
: "";
4715 array_push ((ARRAY
*)funcname_a
, this_shell_function
->name
);
4717 array_push ((ARRAY
*)bash_source_a
, sfile
);
4718 t
= itos (executing_line_number ());
4719 array_push ((ARRAY
*)bash_lineno_a
, t
);
4723 #if defined (ARRAY_VARS)
4724 fa
= (struct func_array_state
*)xmalloc (sizeof (struct func_array_state
));
4725 fa
->source_a
= (ARRAY
*)bash_source_a
;
4726 fa
->source_v
= bash_source_v
;
4727 fa
->lineno_a
= (ARRAY
*)bash_lineno_a
;
4728 fa
->lineno_v
= bash_lineno_v
;
4729 fa
->funcname_a
= (ARRAY
*)funcname_a
;
4730 fa
->funcname_v
= funcname_v
;
4732 add_unwind_protect (restore_funcarray_state
, fa
);
4735 /* The temporary environment for a function is supposed to apply to
4736 all commands executed within the function body. */
4738 remember_args (words
->next
, 1);
4740 /* Update BASH_ARGV and BASH_ARGC */
4743 push_args (words
->next
);
4745 add_unwind_protect (pop_args
, 0);
4748 /* Number of the line on which the function body starts. */
4749 line_number
= function_line_number
= tc
->line
;
4751 #if defined (JOB_CONTROL)
4753 stop_pipeline (async
, (COMMAND
*)NULL
);
4756 if (shell_compatibility_level
> 43)
4761 from_return_trap
= 0;
4763 return_catch_flag
++;
4764 return_val
= setjmp_nosigs (return_catch
);
4768 result
= return_catch_value
;
4769 /* Run the RETURN trap in the function's context. */
4770 save_current
= currently_executing_command
;
4771 if (from_return_trap
== 0)
4773 currently_executing_command
= save_current
;
4777 /* Run the debug trap here so we can trap at the start of a function's
4778 execution rather than the execution of the body's first command. */
4779 showing_function_line
= 1;
4780 save_current
= currently_executing_command
;
4781 result
= run_debug_trap ();
4782 #if defined (DEBUGGER)
4783 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4784 skip the command. */
4785 if (debugging_mode
== 0 || result
== EXECUTION_SUCCESS
)
4787 showing_function_line
= 0;
4788 currently_executing_command
= save_current
;
4789 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
4791 /* Run the RETURN trap in the function's context */
4792 save_current
= currently_executing_command
;
4794 currently_executing_command
= save_current
;
4797 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
4799 save_current
= currently_executing_command
;
4801 currently_executing_command
= save_current
;
4803 showing_function_line
= 0;
4806 /* If we have a local copy of OPTIND, note it in the saved getopts state. */
4807 gv
= find_variable ("OPTIND");
4808 if (gv
&& gv
->context
== variable_context
)
4812 run_unwind_frame ("function_calling");
4813 #if defined (ARRAY_VARS)
4816 restore_funcarray_state (fa
);
4817 /* Restore BASH_ARGC and BASH_ARGV */
4823 if (variable_context
== 0 || this_shell_function
== 0)
4825 make_funcname_visible (0);
4826 #if defined (PROCESS_SUBSTITUTION)
4827 unlink_fifo_list ();
4834 /* A convenience routine for use by other parts of the shell to execute
4835 a particular shell function. */
4837 execute_shell_function (var
, words
)
4842 struct fd_bitmap
*bitmap
;
4844 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
4845 begin_unwind_frame ("execute-shell-function");
4846 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
4848 ret
= execute_function (var
, words
, 0, bitmap
, 0, 0);
4850 dispose_fd_bitmap (bitmap
);
4851 discard_unwind_frame ("execute-shell-function");
4856 /* Execute a shell builtin or function in a subshell environment. This
4857 routine does not return; it only calls exit(). If BUILTIN is non-null,
4858 it points to a function to call to execute a shell builtin; otherwise
4859 VAR points at the body of a function to execute. WORDS is the arguments
4860 to the command, REDIRECTS specifies redirections to perform before the
4861 command is executed. */
4863 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
4864 pipe_in
, pipe_out
, async
, fds_to_close
,
4867 REDIRECT
*redirects
;
4868 sh_builtin_func_t
*builtin
;
4870 int pipe_in
, pipe_out
, async
;
4871 struct fd_bitmap
*fds_to_close
;
4874 int result
, r
, funcvalue
;
4875 #if defined (JOB_CONTROL)
4878 jobs_hack
= (builtin
== jobs_builtin
) &&
4879 ((subshell_environment
& SUBSHELL_ASYNC
) == 0 || pipe_out
!= NO_PIPE
);
4882 /* A subshell is neither a login shell nor interactive. */
4883 login_shell
= interactive
= 0;
4884 if (builtin
== eval_builtin
)
4886 else if (builtin
== source_builtin
)
4890 subshell_environment
|= SUBSHELL_ASYNC
;
4891 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4892 subshell_environment
|= SUBSHELL_PIPE
;
4894 maybe_make_export_env (); /* XXX - is this needed? */
4896 #if defined (JOB_CONTROL)
4897 /* Eradicate all traces of job control after we fork the subshell, so
4898 all jobs begun by this subshell are in the same process group as
4899 the shell itself. */
4901 /* Allow the output of `jobs' to be piped. */
4903 kill_current_pipeline ();
4905 without_job_control ();
4907 set_sigchld_handler ();
4908 #endif /* JOB_CONTROL */
4910 set_sigint_handler ();
4913 close_fd_bitmap (fds_to_close
);
4915 do_piping (pipe_in
, pipe_out
);
4917 if (do_redirections (redirects
, RX_ACTIVE
) != 0)
4918 exit (EXECUTION_FAILURE
);
4922 /* Give builtins a place to jump back to on failure,
4923 so we don't go back up to main(). */
4924 result
= setjmp_nosigs (top_level
);
4926 /* Give the return builtin a place to jump to when executed in a subshell
4929 if (return_catch_flag
&& builtin
== return_builtin
)
4930 funcvalue
= setjmp_nosigs (return_catch
);
4932 if (result
== EXITPROG
)
4933 exit (last_command_exit_value
);
4935 exit (EXECUTION_FAILURE
);
4937 exit (return_catch_value
);
4940 r
= execute_builtin (builtin
, words
, flags
, 1);
4949 r
= execute_function (var
, words
, flags
, fds_to_close
, async
, 1);
4955 /* Execute a builtin or function in the current shell context. If BUILTIN
4956 is non-null, it is the builtin command to execute, otherwise VAR points
4957 to the body of a function. WORDS are the command's arguments, REDIRECTS
4958 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4959 file descriptors to close.
4961 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4962 not undone before this function returns. */
4964 execute_builtin_or_function (words
, builtin
, var
, redirects
,
4965 fds_to_close
, flags
)
4967 sh_builtin_func_t
*builtin
;
4969 REDIRECT
*redirects
;
4970 struct fd_bitmap
*fds_to_close
;
4974 REDIRECT
*saved_undo_list
;
4975 #if defined (PROCESS_SUBSTITUTION)
4976 int ofifo
, nfifo
, osize
;
4980 #if defined (PROCESS_SUBSTITUTION)
4981 ofifo
= num_fifos ();
4982 ofifo_list
= copy_fifo_list (&osize
);
4985 if (do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
4987 cleanup_redirects (redirection_undo_list
);
4988 redirection_undo_list
= (REDIRECT
*)NULL
;
4989 dispose_exec_redirects ();
4990 #if defined (PROCESS_SUBSTITUTION)
4993 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
4996 saved_undo_list
= redirection_undo_list
;
4998 /* Calling the "exec" builtin changes redirections forever. */
4999 if (builtin
== exec_builtin
)
5001 dispose_redirects (saved_undo_list
);
5002 saved_undo_list
= exec_redirection_undo_list
;
5003 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
5006 dispose_exec_redirects ();
5008 if (saved_undo_list
)
5010 begin_unwind_frame ("saved-redirects");
5011 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
5014 redirection_undo_list
= (REDIRECT
*)NULL
;
5017 result
= execute_builtin (builtin
, words
, flags
, 0);
5019 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
5021 /* We do this before undoing the effects of any redirections. */
5024 if (ferror (stdout
))
5027 /* If we are executing the `command' builtin, but this_shell_builtin is
5028 set to `exec_builtin', we know that we have something like
5029 `command exec [redirection]', since otherwise `exec' would have
5030 overwritten the shell and we wouldn't get here. In this case, we
5031 want to behave as if the `command' builtin had not been specified
5032 and preserve the redirections. */
5033 if (builtin
== command_builtin
&& this_shell_builtin
== exec_builtin
)
5038 if (saved_undo_list
)
5040 dispose_redirects (saved_undo_list
);
5043 redirection_undo_list
= exec_redirection_undo_list
;
5044 saved_undo_list
= exec_redirection_undo_list
= (REDIRECT
*)NULL
;
5046 discard_unwind_frame ("saved-redirects");
5049 if (saved_undo_list
)
5051 redirection_undo_list
= saved_undo_list
;
5052 discard_unwind_frame ("saved-redirects");
5055 if (redirection_undo_list
)
5057 cleanup_redirects (redirection_undo_list
);
5058 redirection_undo_list
= (REDIRECT
*)NULL
;
5061 #if defined (PROCESS_SUBSTITUTION)
5062 /* Close any FIFOs created by this builtin or function. */
5063 nfifo
= num_fifos ();
5065 close_new_fifos (ofifo_list
, osize
);
5073 setup_async_signals ()
5075 #if defined (__BEOS__)
5076 set_signal_handler (SIGHUP
, SIG_IGN
); /* they want csh-like behavior */
5079 #if defined (JOB_CONTROL)
5080 if (job_control
== 0)
5083 /* Make sure we get the original signal dispositions now so we don't
5084 confuse the trap builtin later if the subshell tries to use it to
5085 reset SIGINT/SIGQUIT. Don't call set_signal_ignored; that sets
5086 the value of original_signals to SIG_IGN. Posix interpretation 751. */
5087 get_original_signal (SIGINT
);
5088 set_signal_handler (SIGINT
, SIG_IGN
);
5090 get_original_signal (SIGQUIT
);
5091 set_signal_handler (SIGQUIT
, SIG_IGN
);
5095 /* Execute a simple command that is hopefully defined in a disk file
5100 3) look up the command
5103 6) If the execve failed, see if the file has executable mode set.
5104 If so, and it isn't a directory, then execute its contents as
5107 Note that the filename hashing stuff has to take place up here,
5108 in the parent. This is probably why the Bourne style shells
5109 don't handle it, since that would require them to go through
5110 this gnarly hair, for no good reason.
5112 NOTE: callers expect this to fork or exit(). */
5114 /* Name of a shell function to call when a command name is not found. */
5115 #ifndef NOTFOUND_HOOK
5116 # define NOTFOUND_HOOK "command_not_found_handle"
5120 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
5121 async
, fds_to_close
, cmdflags
)
5123 REDIRECT
*redirects
;
5125 int pipe_in
, pipe_out
, async
;
5126 struct fd_bitmap
*fds_to_close
;
5129 char *pathname
, *command
, **args
;
5130 int nofork
, stdpath
, result
;
5135 stdpath
= (cmdflags
& CMD_STDPATH
); /* use command -p path */
5136 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
5137 pathname
= words
->word
->word
;
5139 result
= EXECUTION_SUCCESS
;
5140 #if defined (RESTRICTED_SHELL)
5141 command
= (char *)NULL
;
5142 if (restricted
&& mbschr (pathname
, '/'))
5144 internal_error (_("%s: restricted: cannot specify `/' in command names"),
5146 result
= last_command_exit_value
= EXECUTION_FAILURE
;
5148 /* If we're not going to fork below, we must already be in a child
5149 process or a context in which it's safe to call exit(2). */
5150 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
5151 exit (last_command_exit_value
);
5155 #endif /* RESTRICTED_SHELL */
5157 command
= search_for_command (pathname
, CMDSRCH_HASH
|(stdpath
? CMDSRCH_STDPATH
: 0));
5161 maybe_make_export_env ();
5162 put_command_name_into_env (command
);
5165 /* We have to make the child before we check for the non-existence
5166 of COMMAND, since we want the error messages to be redirected. */
5167 /* If we can get away without forking and there are no pipes to deal with,
5168 don't bother to fork, just directly exec the command. */
5169 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
5172 pid
= make_child (savestring (command_line
), async
);
5176 int old_interactive
;
5178 reset_terminating_signals (); /* XXX */
5179 /* Cancel traps, in trap.c. */
5180 restore_original_signals ();
5184 /* restore_original_signals may have undone the work done
5185 by make_child to ensure that SIGINT and SIGQUIT are ignored
5186 in asynchronous children. */
5189 if ((cmdflags
& CMD_STDIN_REDIR
) &&
5190 pipe_in
== NO_PIPE
&&
5191 (stdin_redirects (redirects
) == 0))
5192 async_redirect_stdin ();
5193 setup_async_signals ();
5196 /* This functionality is now provided by close-on-exec of the
5197 file descriptors manipulated by redirection and piping.
5198 Some file descriptors still need to be closed in all children
5199 because of the way bash does pipes; fds_to_close is a
5200 bitmap of all such file descriptors. */
5202 close_fd_bitmap (fds_to_close
);
5204 do_piping (pipe_in
, pipe_out
);
5206 old_interactive
= interactive
;
5210 subshell_environment
|= SUBSHELL_FORK
; /* XXX - was just = */
5212 if (redirects
&& (do_redirections (redirects
, RX_ACTIVE
) != 0))
5214 #if defined (PROCESS_SUBSTITUTION)
5215 /* Try to remove named pipes that may have been created as the
5216 result of redirections. */
5217 unlink_fifo_list ();
5218 #endif /* PROCESS_SUBSTITUTION */
5219 exit (EXECUTION_FAILURE
);
5223 interactive
= old_interactive
;
5227 hookf
= find_function (NOTFOUND_HOOK
);
5230 /* Make sure filenames are displayed using printable characters */
5231 pathname
= printable_filename (pathname
, 0);
5232 internal_error (_("%s: command not found"), pathname
);
5233 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
5236 #if defined (JOB_CONTROL)
5237 /* May need to reinitialize more of the job control state here. */
5238 kill_current_pipeline ();
5241 wl
= make_word_list (make_word (NOTFOUND_HOOK
), words
);
5242 exit (execute_shell_function (hookf
, wl
));
5247 /* Execve expects the command name to be in args[0]. So we
5248 leave it there, in the same format that the user used to
5250 args
= strvec_from_word_list (words
, 0, 0, (int *)NULL
);
5251 exit (shell_execve (command
, args
, export_env
));
5258 /* Make sure that the pipes are closed in the parent. */
5259 close_pipes (pipe_in
, pipe_out
);
5260 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5261 if (variable_context
== 0)
5262 unlink_fifo_list ();
5269 /* CPP defines to decide whether a particular index into the #! line
5270 corresponds to a valid interpreter name or argument character, or
5271 whitespace. The MSDOS define is to allow \r to be treated the same
5274 #if !defined (MSDOS)
5275 # define STRINGCHAR(ind) \
5276 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
5277 # define WHITECHAR(ind) \
5278 (ind < sample_len && whitespace (sample[ind]))
5280 # define STRINGCHAR(ind) \
5281 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
5282 # define WHITECHAR(ind) \
5283 (ind < sample_len && whitespace (sample[ind]))
5287 getinterp (sample
, sample_len
, endp
)
5289 int sample_len
, *endp
;
5295 /* Find the name of the interpreter to exec. */
5296 for (i
= 2; i
< sample_len
&& whitespace (sample
[i
]); i
++)
5299 for (start
= i
; STRINGCHAR(i
); i
++)
5302 execname
= substring (sample
, start
, i
);
5309 #if !defined (HAVE_HASH_BANG_EXEC)
5310 /* If the operating system on which we're running does not handle
5311 the #! executable format, then help out. SAMPLE is the text read
5312 from the file, SAMPLE_LEN characters. COMMAND is the name of
5313 the script; it and ARGS, the arguments given by the user, will
5314 become arguments to the specified interpreter. ENV is the environment
5315 to pass to the interpreter.
5317 The word immediately following the #! is the interpreter to execute.
5318 A single argument to the interpreter is allowed. */
5321 execute_shell_script (sample
, sample_len
, command
, args
, env
)
5327 char *execname
, *firstarg
;
5328 int i
, start
, size_increment
, larry
;
5330 /* Find the name of the interpreter to exec. */
5331 execname
= getinterp (sample
, sample_len
, &i
);
5334 /* Now the argument, if any. */
5335 for (firstarg
= (char *)NULL
, start
= i
; WHITECHAR(i
); i
++)
5338 /* If there is more text on the line, then it is an argument for the
5343 for (start
= i
; STRINGCHAR(i
); i
++)
5345 firstarg
= substring ((char *)sample
, start
, i
);
5349 larry
= strvec_len (args
) + size_increment
;
5350 args
= strvec_resize (args
, larry
+ 1);
5352 for (i
= larry
- 1; i
; i
--)
5353 args
[i
] = args
[i
- size_increment
];
5364 args
[larry
] = (char *)NULL
;
5366 return (shell_execve (execname
, args
, env
));
5371 #endif /* !HAVE_HASH_BANG_EXEC */
5374 initialize_subshell ()
5377 /* Forget about any aliases that we knew of. We are in a subshell. */
5378 delete_all_aliases ();
5381 #if defined (HISTORY)
5382 /* Forget about the history lines we have read. This is a non-interactive
5384 history_lines_this_session
= 0;
5387 /* Forget about the way job control was working. We are in a subshell. */
5388 without_job_control ();
5390 #if defined (JOB_CONTROL)
5391 set_sigchld_handler ();
5393 #endif /* JOB_CONTROL */
5395 /* Reset the values of the shell flags and options. */
5396 reset_shell_flags ();
5397 reset_shell_options ();
5398 reset_shopt_options ();
5400 /* Zero out builtin_env, since this could be a shell script run from a
5401 sourced file with a temporary environment supplied to the `source/.'
5402 builtin. Such variables are not supposed to be exported (empirical
5403 testing with sh and ksh). Just throw it away; don't worry about a
5405 if (vc_isbltnenv (shell_variables
))
5406 shell_variables
= shell_variables
->down
;
5408 clear_unwind_protect_list (0);
5409 /* XXX -- are there other things we should be resetting here? */
5410 parse_and_execute_level
= 0; /* nothing left to restore it */
5412 /* We're no longer inside a shell function. */
5413 variable_context
= return_catch_flag
= funcnest
= evalnest
= sourcenest
= 0;
5415 executing_list
= 0; /* XXX */
5417 /* If we're not interactive, close the file descriptor from which we're
5418 reading the current shell script. */
5419 if (interactive_shell
== 0)
5420 unset_bash_input (0);
5423 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
5424 # define SETOSTYPE(x) __setostype(x)
5426 # define SETOSTYPE(x)
5429 #define HASH_BANG_BUFSIZ 128
5431 #define READ_SAMPLE_BUF(file, buf, len) \
5434 fd = open(file, O_RDONLY); \
5437 len = read (fd, buf, HASH_BANG_BUFSIZ); \
5445 /* Call execve (), handling interpreting shell scripts, and handling
5448 shell_execve (command
, args
, env
)
5453 char sample
[HASH_BANG_BUFSIZ
];
5456 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
5457 execve (command
, args
, env
);
5458 i
= errno
; /* error from execve() */
5462 /* If we get to this point, then start checking out the file.
5463 Maybe it is something we can hack ourselves. */
5466 /* make sure this is set correctly for file_error/report_error */
5467 last_command_exit_value
= (i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
; /* XXX Posix.2 says that exit status is 126 */
5468 if (file_isdir (command
))
5469 #if defined (EISDIR)
5470 internal_error (_("%s: %s"), command
, strerror (EISDIR
));
5472 internal_error (_("%s: is a directory"), command
);
5474 else if (executable_file (command
) == 0)
5477 file_error (command
);
5479 /* errors not involving the path argument to execve. */
5480 else if (i
== E2BIG
|| i
== ENOMEM
)
5483 file_error (command
);
5487 /* The file has the execute bits set, but the kernel refuses to
5488 run it for some reason. See why. */
5489 #if defined (HAVE_HASH_BANG_EXEC)
5490 READ_SAMPLE_BUF (command
, sample
, sample_len
);
5492 sample
[sample_len
- 1] = '\0';
5493 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
5498 interp
= getinterp (sample
, sample_len
, (int *)NULL
);
5499 ilen
= strlen (interp
);
5501 if (interp
[ilen
- 1] == '\r')
5503 interp
= xrealloc (interp
, ilen
+ 2);
5504 interp
[ilen
- 1] = '^';
5506 interp
[ilen
+ 1] = '\0';
5508 sys_error (_("%s: %s: bad interpreter"), command
, interp
? interp
: "");
5514 file_error (command
);
5516 return (last_command_exit_value
);
5519 /* This file is executable.
5520 If it begins with #!, then help out people with losing operating
5521 systems. Otherwise, check to see if it is a binary file by seeing
5522 if the contents of the first line (or up to 80 characters) are in the
5523 ASCII set. If it's a text file, execute the contents as shell commands,
5524 otherwise return 126 (EX_BINARY_FILE). */
5525 READ_SAMPLE_BUF (command
, sample
, sample_len
);
5527 if (sample_len
== 0)
5528 return (EXECUTION_SUCCESS
);
5530 /* Is this supposed to be an executable script?
5531 If so, the format of the line is "#! interpreter [argument]".
5532 A single argument is allowed. The BSD kernel restricts
5533 the length of the entire line to 32 characters (32 bytes
5534 being the size of the BSD exec header), but we allow 80
5538 #if !defined (HAVE_HASH_BANG_EXEC)
5539 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
5540 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
5543 if (check_binary_file (sample
, sample_len
))
5545 internal_error (_("%s: cannot execute binary file: %s"), command
, strerror (i
));
5547 return (EX_BINARY_FILE
);
5551 /* We have committed to attempting to execute the contents of this file
5552 as shell commands. */
5555 initialize_subshell ();
5557 set_sigint_handler ();
5559 /* Insert the name of this shell into the argument list. */
5560 larray
= strvec_len (args
) + 1;
5561 args
= strvec_resize (args
, larray
+ 1);
5563 for (i
= larray
- 1; i
; i
--)
5564 args
[i
] = args
[i
- 1];
5566 args
[0] = shell_name
;
5568 args
[larray
] = (char *)NULL
;
5570 if (args
[0][0] == '-')
5573 #if defined (RESTRICTED_SHELL)
5575 change_flag ('r', FLAG_OFF
);
5580 /* Can't free subshell_argv[0]; that is shell_name. */
5581 for (i
= 1; i
< subshell_argc
; i
++)
5582 free (subshell_argv
[i
]);
5583 free (subshell_argv
);
5586 dispose_command (currently_executing_command
); /* XXX */
5587 currently_executing_command
= (COMMAND
*)NULL
;
5589 subshell_argc
= larray
;
5590 subshell_argv
= args
;
5591 subshell_envp
= env
;
5593 unbind_args (); /* remove the positional parameters */
5595 #if defined (PROCESS_SUBSTITUTION)
5596 clear_fifo_list (); /* pipe fds are what they are now */
5599 sh_longjmp (subshell_top_level
, 1);
5604 execute_intern_function (name
, funcdef
)
5606 FUNCTION_DEF
*funcdef
;
5610 if (check_identifier (name
, posixly_correct
) == 0)
5612 if (posixly_correct
&& interactive_shell
== 0)
5614 last_command_exit_value
= EX_BADUSAGE
;
5615 jump_to_top_level (ERREXIT
);
5617 return (EXECUTION_FAILURE
);
5620 /* Posix interpretation 383 */
5621 if (posixly_correct
&& find_special_builtin (name
->word
))
5623 internal_error (_("`%s': is a special builtin"), name
->word
);
5624 last_command_exit_value
= EX_BADUSAGE
;
5625 jump_to_top_level (interactive_shell
? DISCARD
: ERREXIT
);
5628 var
= find_function (name
->word
);
5629 if (var
&& (readonly_p (var
) || noassign_p (var
)))
5631 if (readonly_p (var
))
5632 internal_error (_("%s: readonly function"), var
->name
);
5633 return (EXECUTION_FAILURE
);
5636 #if defined (DEBUGGER)
5637 bind_function_def (name
->word
, funcdef
);
5640 bind_function (name
->word
, funcdef
->command
);
5641 return (EXECUTION_SUCCESS
);
5644 #if defined (INCLUDE_UNUSED)
5645 #if defined (PROCESS_SUBSTITUTION)
5649 register int i
, fd_table_size
;
5651 fd_table_size
= getdtablesize ();
5652 if (fd_table_size
> 256) /* clamp to a reasonable value */
5653 fd_table_size
= 256;
5655 for (i
= 3; i
< fd_table_size
; i
++)
5658 #endif /* PROCESS_SUBSTITUTION */
5662 close_pipes (in
, out
)
5672 dup_error (oldd
, newd
)
5675 sys_error (_("cannot duplicate fd %d to fd %d"), oldd
, newd
);
5678 /* Redirect input and output to be from and to the specified pipes.
5679 NO_PIPE and REDIRECT_BOTH are handled correctly. */
5681 do_piping (pipe_in
, pipe_out
)
5682 int pipe_in
, pipe_out
;
5684 if (pipe_in
!= NO_PIPE
)
5686 if (dup2 (pipe_in
, 0) < 0)
5687 dup_error (pipe_in
, 0);
5691 /* Let stdio know the fd may have changed from text to binary mode. */
5692 freopen (NULL
, "r", stdin
);
5693 #endif /* __CYGWIN__ */
5695 if (pipe_out
!= NO_PIPE
)
5697 if (pipe_out
!= REDIRECT_BOTH
)
5699 if (dup2 (pipe_out
, 1) < 0)
5700 dup_error (pipe_out
, 1);
5701 if (pipe_out
== 0 || pipe_out
> 1)
5706 if (dup2 (1, 2) < 0)
5710 /* Let stdio know the fd may have changed from text to binary mode, and
5711 make sure to preserve stdout line buffering. */
5712 freopen (NULL
, "w", stdout
);
5713 sh_setlinebuf (stdout
);
5714 #endif /* __CYGWIN__ */