1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
34 #include "posixstat.h"
37 # include <sys/param.h>
40 #if defined (HAVE_UNISTD_H)
44 #include "posixtime.h"
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 # include <sys/resource.h>
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 # include <sys/times.h>
65 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
70 #include "execute_cmd.h"
77 #if defined (COND_COMMAND)
81 #include "builtins/common.h"
82 #include "builtins/builtext.h" /* list of builtins */
84 #include <glob/strmatch.h>
85 #include <tilde/tilde.h>
87 #if defined (BUFFERED_INPUT)
96 # include "bashhist.h"
99 extern int posixly_correct
;
100 extern int expand_aliases
;
102 extern int breaking
, continuing
, loop_level
;
103 extern int parse_and_execute_level
, running_trap
;
104 extern int command_string_index
, line_number
;
105 extern int dot_found_in_search
;
106 extern int already_making_children
;
107 extern int tempenv_assign_error
;
108 extern char *the_printed_command
, *shell_name
;
109 extern pid_t last_command_subst_pid
;
110 extern sh_builtin_func_t
*last_shell_builtin
, *this_shell_builtin
;
111 extern char **subshell_argv
, **subshell_envp
;
112 extern int subshell_argc
;
114 extern char *glob_argv_flags
;
117 extern int close
__P((int));
119 /* Static functions defined and used in this file. */
120 static void close_pipes
__P((int, int));
121 static void do_piping
__P((int, int));
122 static void bind_lastarg
__P((char *));
123 static int shell_control_structure
__P((enum command_type
));
124 static void cleanup_redirects
__P((REDIRECT
*));
126 #if defined (JOB_CONTROL)
127 static int restore_signal_mask
__P((sigset_t
*));
130 static void async_redirect_stdin
__P((void));
132 static int builtin_status
__P((int));
134 static int execute_for_command
__P((FOR_COM
*));
135 #if defined (SELECT_COMMAND)
136 static int print_index_and_element
__P((int, int, WORD_LIST
*));
137 static void indent
__P((int, int));
138 static void print_select_list
__P((WORD_LIST
*, int, int, int));
139 static char *select_query
__P((WORD_LIST
*, int, char *, int));
140 static int execute_select_command
__P((SELECT_COM
*));
142 #if defined (DPAREN_ARITHMETIC)
143 static int execute_arith_command
__P((ARITH_COM
*));
145 #if defined (COND_COMMAND)
146 static int execute_cond_node
__P((COND_COM
*));
147 static int execute_cond_command
__P((COND_COM
*));
149 #if defined (COMMAND_TIMING)
150 static int mkfmt
__P((char *, int, int, time_t, int));
151 static void print_formatted_time
__P((FILE *, char *,
152 time_t, int, time_t, int,
154 static int time_command
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
156 #if defined (ARITH_FOR_COMMAND)
157 static intmax_t eval_arith_for_expr
__P((WORD_LIST
*, int *));
158 static int execute_arith_for_command
__P((ARITH_FOR_COM
*));
160 static int execute_case_command
__P((CASE_COM
*));
161 static int execute_while_command
__P((WHILE_COM
*));
162 static int execute_until_command
__P((WHILE_COM
*));
163 static int execute_while_or_until
__P((WHILE_COM
*, int));
164 static int execute_if_command
__P((IF_COM
*));
165 static int execute_null_command
__P((REDIRECT
*, int, int, int));
166 static void fix_assignment_words
__P((WORD_LIST
*));
167 static int execute_simple_command
__P((SIMPLE_COM
*, int, int, int, struct fd_bitmap
*));
168 static int execute_builtin
__P((sh_builtin_func_t
*, WORD_LIST
*, int, int));
169 static int execute_function
__P((SHELL_VAR
*, WORD_LIST
*, int, struct fd_bitmap
*, int, int));
170 static int execute_builtin_or_function
__P((WORD_LIST
*, sh_builtin_func_t
*,
172 REDIRECT
*, struct fd_bitmap
*, int));
173 static void execute_subshell_builtin_or_function
__P((WORD_LIST
*, REDIRECT
*,
179 static void execute_disk_command
__P((WORD_LIST
*, REDIRECT
*, char *,
180 int, int, int, struct fd_bitmap
*, int));
182 static char *getinterp
__P((char *, int, int *));
183 static void initialize_subshell
__P((void));
184 static int execute_in_subshell
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
185 #if defined (COPROCESS_SUPPORT)
186 static int execute_coproc
__P((COMMAND
*, int, int, struct fd_bitmap
*));
189 static int execute_pipeline
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
191 static int execute_connection
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
193 static int execute_intern_function
__P((WORD_DESC
*, COMMAND
*));
195 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
196 so that reader_loop can set it to zero before executing a command. */
199 /* The name of the command that is currently being executed.
200 `test' needs this, for example. */
201 char *this_command_name
;
203 /* The printed representation of the currently-executing command (same as
204 the_printed_command), except when a trap is being executed. Useful for
205 a debugger to know where exactly the program is currently executing. */
206 char *the_printed_command_except_trap
;
208 /* For catching RETURN in a function. */
209 int return_catch_flag
;
210 int return_catch_value
;
211 procenv_t return_catch
;
213 /* The value returned by the last synchronous command. */
214 int last_command_exit_value
;
216 /* Whether or not the last command (corresponding to last_command_exit_value)
217 was terminated by a signal, and, if so, which one. */
218 int last_command_exit_signal
;
220 /* The list of redirections to perform which will undo the redirections
221 that I made in the shell. */
222 REDIRECT
*redirection_undo_list
= (REDIRECT
*)NULL
;
224 /* The list of redirections to perform which will undo the internal
225 redirections performed by the `exec' builtin. These are redirections
226 that must be undone even when exec discards redirection_undo_list. */
227 REDIRECT
*exec_redirection_undo_list
= (REDIRECT
*)NULL
;
229 /* When greater than zero, value is the `level' of builtins we are
230 currently executing (e.g. `eval echo a' would have it set to 2). */
231 int executing_builtin
= 0;
233 /* Non-zero if we are executing a command list (a;b;c, etc.) */
234 int executing_list
= 0;
236 /* Non-zero if failing commands in a command substitution should not exit the
237 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
238 commands run in command substitutions by parse_and_execute. */
239 int comsub_ignore_return
= 0;
241 /* Non-zero if we have just forked and are currently running in a subshell
243 int subshell_environment
;
245 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
246 int subshell_level
= 0;
248 /* Currently-executing shell function. */
249 SHELL_VAR
*this_shell_function
;
251 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
252 int match_ignore_case
= 0;
254 struct stat SB
; /* used for debugging */
256 static int special_builtin_failed
;
258 static COMMAND
*currently_executing_command
;
260 /* The line number that the currently executing function starts on. */
261 static int function_line_number
;
263 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
264 number containing the function name. Used by executing_line_number to
265 report the correct line number. Kind of a hack. */
266 static int showing_function_line
;
268 static int line_number_for_err_trap
;
270 struct fd_bitmap
*current_fds_to_close
= (struct fd_bitmap
*)NULL
;
272 #define FD_BITMAP_DEFAULT_SIZE 32
274 /* Functions to allocate and deallocate the structures used to pass
275 information from the shell to its children about file descriptors
281 struct fd_bitmap
*ret
;
283 ret
= (struct fd_bitmap
*)xmalloc (sizeof (struct fd_bitmap
));
289 ret
->bitmap
= (char *)xmalloc (size
);
290 memset (ret
->bitmap
, '\0', size
);
293 ret
->bitmap
= (char *)NULL
;
298 dispose_fd_bitmap (fdbp
)
299 struct fd_bitmap
*fdbp
;
306 close_fd_bitmap (fdbp
)
307 struct fd_bitmap
*fdbp
;
313 for (i
= 0; i
< fdbp
->size
; i
++)
322 /* Return the line number of the currently executing command. */
324 executing_line_number ()
326 if (executing
&& showing_function_line
== 0 &&
327 (variable_context
== 0 || interactive_shell
== 0) &&
328 currently_executing_command
)
330 #if defined (COND_COMMAND)
331 if (currently_executing_command
->type
== cm_cond
)
332 return currently_executing_command
->value
.Cond
->line
;
334 #if defined (DPAREN_ARITHMETIC)
335 else if (currently_executing_command
->type
== cm_arith
)
336 return currently_executing_command
->value
.Arith
->line
;
338 #if defined (ARITH_FOR_COMMAND)
339 else if (currently_executing_command
->type
== cm_arith_for
)
340 return currently_executing_command
->value
.ArithFor
->line
;
349 /* Execute the command passed in COMMAND. COMMAND is exactly what
350 read_command () places into GLOBAL_COMMAND. See "command.h" for the
351 details of the command structure.
353 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
354 return values. Executing a command with nothing in it returns
355 EXECUTION_SUCCESS. */
357 execute_command (command
)
360 struct fd_bitmap
*bitmap
;
363 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
364 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
365 begin_unwind_frame ("execute-command");
366 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
368 /* Just do the command, but not asynchronously. */
369 result
= execute_command_internal (command
, 0, NO_PIPE
, NO_PIPE
, bitmap
);
371 dispose_fd_bitmap (bitmap
);
372 discard_unwind_frame ("execute-command");
374 #if defined (PROCESS_SUBSTITUTION)
375 /* don't unlink fifos if we're in a shell function; wait until the function
377 if (variable_context
== 0)
379 #endif /* PROCESS_SUBSTITUTION */
385 /* Return 1 if TYPE is a shell control structure type. */
387 shell_control_structure (type
)
388 enum command_type type
;
392 #if defined (ARITH_FOR_COMMAND)
395 #if defined (SELECT_COMMAND)
398 #if defined (DPAREN_ARITHMETIC)
401 #if defined (COND_COMMAND)
410 case cm_function_def
:
418 /* A function to use to unwind_protect the redirection undo list
421 cleanup_redirects (list
)
424 do_redirections (list
, RX_ACTIVE
);
425 dispose_redirects (list
);
429 /* Function to unwind_protect the redirections for functions and builtins. */
431 cleanup_func_redirects (list
)
434 do_redirections (list
, RX_ACTIVE
);
439 dispose_exec_redirects ()
441 if (exec_redirection_undo_list
)
443 dispose_redirects (exec_redirection_undo_list
);
444 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
448 #if defined (JOB_CONTROL)
449 /* A function to restore the signal mask to its proper value when the shell
450 is interrupted or errors occur while creating a pipeline. */
452 restore_signal_mask (set
)
455 return (sigprocmask (SIG_SETMASK
, set
, (sigset_t
*)NULL
));
457 #endif /* JOB_CONTROL */
460 /* A debugging function that can be called from gdb, for instance. */
465 int f
, fd_table_size
;
467 fd_table_size
= getdtablesize ();
469 fprintf (stderr
, "pid %ld open files:", (long)getpid ());
470 for (i
= 3; i
< fd_table_size
; i
++)
472 if ((f
= fcntl (i
, F_GETFD
, 0)) != -1)
473 fprintf (stderr
, " %d (%s)", i
, f
? "close" : "open");
475 fprintf (stderr
, "\n");
480 async_redirect_stdin ()
484 fd
= open ("/dev/null", O_RDONLY
);
491 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno
));
494 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
496 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
497 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
498 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
499 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
500 from and where it goes. They can have the value of NO_PIPE, which means
502 FDS_TO_CLOSE is a list of file descriptors to close once the child has
503 been forked. This list often contains the unusable sides of pipes, etc.
505 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
506 return values. Executing a command with nothing in it returns
507 EXECUTION_SUCCESS. */
509 execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
,
513 int pipe_in
, pipe_out
;
514 struct fd_bitmap
*fds_to_close
;
516 int exec_result
, invert
, ignore_return
, was_error_trap
;
517 REDIRECT
*my_undo_list
, *exec_undo_list
;
518 volatile int last_pid
;
519 volatile int save_line_number
;
522 if (command
== 0 || breaking
|| continuing
|| read_but_dont_execute
)
523 return (EXECUTION_SUCCESS
);
525 if (breaking
|| continuing
)
526 return (last_command_exit_value
);
527 if (command
== 0 || read_but_dont_execute
)
528 return (EXECUTION_SUCCESS
);
532 run_pending_traps ();
535 if (running_trap
== 0)
537 currently_executing_command
= command
;
539 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
541 /* If we're inverting the return value and `set -e' has been executed,
542 we don't want a failing command to inadvertently cause the shell
544 if (exit_immediately_on_error
&& invert
) /* XXX */
545 command
->flags
|= CMD_IGNORE_RETURN
; /* XXX */
547 exec_result
= EXECUTION_SUCCESS
;
549 /* If a command was being explicitly run in a subshell, or if it is
550 a shell control-structure, and it has a pipe, then we do the command
552 if (command
->type
== cm_subshell
&& (command
->flags
& CMD_NO_FORK
))
553 return (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
555 #if defined (COPROCESS_SUPPORT)
556 if (command
->type
== cm_coproc
)
557 return (execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
));
560 if (command
->type
== cm_subshell
||
561 (command
->flags
& (CMD_WANT_SUBSHELL
|CMD_FORCE_SUBSHELL
)) ||
562 (shell_control_structure (command
->type
) &&
563 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
|| asynchronous
)))
567 /* Fork a subshell, turn off the subshell bit, turn off job
568 control and call execute_command () on the command again. */
569 paren_pid
= make_child (savestring (make_command_string (command
)),
572 exit (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
576 close_pipes (pipe_in
, pipe_out
);
578 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
581 /* If we are part of a pipeline, and not the end of the pipeline,
582 then we should simply return and let the last command in the
583 pipe be waited for. If we are not in a pipeline, or are the
584 last command in the pipeline, then we wait for the subshell
585 and return its exit status as usual. */
586 if (pipe_out
!= NO_PIPE
)
587 return (EXECUTION_SUCCESS
);
589 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
591 if (asynchronous
== 0)
593 last_command_exit_value
= wait_for (paren_pid
);
595 /* If we have to, invert the return value. */
597 exec_result
= ((last_command_exit_value
== EXECUTION_SUCCESS
)
599 : EXECUTION_SUCCESS
);
601 exec_result
= last_command_exit_value
;
603 return (last_command_exit_value
= exec_result
);
607 DESCRIBE_PID (paren_pid
);
609 run_pending_traps ();
611 return (EXECUTION_SUCCESS
);
616 #if defined (COMMAND_TIMING)
617 if (command
->flags
& CMD_TIME_PIPELINE
)
621 command
->flags
|= CMD_FORCE_SUBSHELL
;
622 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
626 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
628 if (running_trap
== 0)
630 currently_executing_command
= (COMMAND
*)NULL
;
632 return (exec_result
);
634 #endif /* COMMAND_TIMING */
636 if (shell_control_structure (command
->type
) && command
->redirects
)
637 stdin_redir
= stdin_redirects (command
->redirects
);
639 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
641 if (do_redirections (command
->redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
643 cleanup_redirects (redirection_undo_list
);
644 redirection_undo_list
= (REDIRECT
*)NULL
;
645 dispose_exec_redirects ();
646 return (last_command_exit_value
= EXECUTION_FAILURE
);
649 if (redirection_undo_list
)
651 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
652 dispose_redirects (redirection_undo_list
);
653 redirection_undo_list
= (REDIRECT
*)NULL
;
656 my_undo_list
= (REDIRECT
*)NULL
;
658 if (exec_redirection_undo_list
)
660 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
661 dispose_redirects (exec_redirection_undo_list
);
662 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
665 exec_undo_list
= (REDIRECT
*)NULL
;
667 if (my_undo_list
|| exec_undo_list
)
668 begin_unwind_frame ("loop_redirections");
671 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
674 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
676 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
680 switch (command
->type
)
684 save_line_number
= line_number
;
685 /* We can't rely on variables retaining their values across a
686 call to execute_simple_command if a longjmp occurs as the
687 result of a `return' builtin. This is true for sure with gcc. */
688 #if defined (RECYCLES_PIDS)
689 last_made_pid
= NO_PID
;
691 last_pid
= last_made_pid
;
692 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
694 if (ignore_return
&& command
->value
.Simple
)
695 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
696 if (command
->flags
& CMD_STDIN_REDIR
)
697 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
699 line_number_for_err_trap
= line_number
= command
->value
.Simple
->line
;
701 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
702 asynchronous
, fds_to_close
);
703 line_number
= save_line_number
;
705 /* The temporary environment should be used for only the simple
706 command immediately following its definition. */
707 dispose_used_env_vars ();
709 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
710 /* Reclaim memory allocated with alloca () on machines which
711 may be using the alloca emulation code. */
713 #endif /* (ultrix && mips) || C_ALLOCA */
715 /* If we forked to do the command, then we must wait_for ()
718 /* XXX - this is something to watch out for if there are problems
719 when the shell is compiled without job control. */
720 if (already_making_children
&& pipe_out
== NO_PIPE
&&
721 last_made_pid
!= last_pid
)
723 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
727 DESCRIBE_PID (last_made_pid
);
730 #if !defined (JOB_CONTROL)
731 /* Do not wait for asynchronous processes started from
733 if (last_made_pid
!= last_asynchronous_pid
)
735 /* When executing a shell function that executes other
736 commands, this causes the last simple command in
737 the function to be waited for twice. This also causes
738 subshells forked to execute builtin commands (e.g., in
739 pipelines) to be waited for twice. */
740 exec_result
= wait_for (last_made_pid
);
744 /* 10/6/2008 -- added test for pipe_in and pipe_out because they indicate
745 the presence of a pipeline, and (until Posix changes things), a
746 pipeline failure should not cause the parent shell to exit on an
747 unsuccessful return status, even in the presence of errexit.. */
748 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)
750 last_command_exit_value
= exec_result
;
754 if (ignore_return
== 0 && invert
== 0 &&
755 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
756 (exit_immediately_on_error
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)))
758 last_command_exit_value
= exec_result
;
759 run_pending_traps ();
760 jump_to_top_level (ERREXIT
);
767 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
768 exec_result
= execute_for_command (command
->value
.For
);
771 #if defined (ARITH_FOR_COMMAND)
774 command
->value
.ArithFor
->flags
|= CMD_IGNORE_RETURN
;
775 exec_result
= execute_arith_for_command (command
->value
.ArithFor
);
779 #if defined (SELECT_COMMAND)
782 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
783 exec_result
= execute_select_command (command
->value
.Select
);
789 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
790 exec_result
= execute_case_command (command
->value
.Case
);
795 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
796 exec_result
= execute_while_command (command
->value
.While
);
801 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
802 exec_result
= execute_until_command (command
->value
.While
);
807 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
808 exec_result
= execute_if_command (command
->value
.If
);
813 /* This code can be executed from either of two paths: an explicit
814 '{}' command, or via a function call. If we are executed via a
815 function call, we have already taken care of the function being
816 executed in the background (down there in execute_simple_command ()),
817 and this command should *not* be marked as asynchronous. If we
818 are executing a regular '{}' group command, and asynchronous == 1,
819 we must want to execute the whole command in the background, so we
820 need a subshell, and we want the stuff executed in that subshell
821 (this group command) to be executed in the foreground of that
822 subshell (i.e. there will not be *another* subshell forked).
824 What we do is to force a subshell if asynchronous, and then call
825 execute_command_internal again with asynchronous still set to 1,
826 but with the original group command, so the printed command will
829 The code above that handles forking off subshells will note that
830 both subshell and async are on, and turn off async in the child
831 after forking the subshell (but leave async set in the parent, so
832 the normal call to describe_pid is made). This turning off
833 async is *crucial*; if it is not done, this will fall into an
834 infinite loop of executions through this spot in subshell after
835 subshell until the process limit is exhausted. */
839 command
->flags
|= CMD_FORCE_SUBSHELL
;
841 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
846 if (ignore_return
&& command
->value
.Group
->command
)
847 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
849 execute_command_internal (command
->value
.Group
->command
,
850 asynchronous
, pipe_in
, pipe_out
,
856 exec_result
= execute_connection (command
, asynchronous
,
857 pipe_in
, pipe_out
, fds_to_close
);
860 #if defined (DPAREN_ARITHMETIC)
863 command
->value
.Arith
->flags
|= CMD_IGNORE_RETURN
;
864 exec_result
= execute_arith_command (command
->value
.Arith
);
868 #if defined (COND_COMMAND)
871 command
->value
.Cond
->flags
|= CMD_IGNORE_RETURN
;
872 save_line_number
= line_number
;
873 exec_result
= execute_cond_command (command
->value
.Cond
);
874 line_number
= save_line_number
;
878 case cm_function_def
:
879 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
880 command
->value
.Function_def
->command
);
884 command_error ("execute_command", CMDERR_BADTYPE
, command
->type
, 0);
889 do_redirections (my_undo_list
, RX_ACTIVE
);
890 dispose_redirects (my_undo_list
);
894 dispose_redirects (exec_undo_list
);
896 if (my_undo_list
|| exec_undo_list
)
897 discard_unwind_frame ("loop_redirections");
899 /* Invert the return value if we have to */
901 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
905 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
906 /* This is where we set PIPESTATUS from the exit status of the appropriate
907 compound commands (the ones that look enough like simple commands to
908 cause confusion). We might be able to optimize by not doing this if
909 subshell_environment != 0. */
910 switch (command
->type
)
912 # if defined (DPAREN_ARITHMETIC)
915 # if defined (COND_COMMAND)
918 set_pipestatus_from_exit (exec_result
);
923 last_command_exit_value
= exec_result
;
924 run_pending_traps ();
926 if (running_trap
== 0)
928 currently_executing_command
= (COMMAND
*)NULL
;
929 return (last_command_exit_value
);
932 #if defined (COMMAND_TIMING)
934 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
935 extern struct timeval
*difftimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
936 extern struct timeval
*addtimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
937 extern int timeval_to_cpu
__P((struct timeval
*, struct timeval
*, struct timeval
*));
940 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
941 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
943 static const int precs
[] = { 0, 100, 10, 1 };
945 /* Expand one `%'-prefixed escape sequence from a time format string. */
947 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
954 char abuf
[INT_STRLEN_BOUND(time_t) + 1];
958 abuf
[sizeof(abuf
) - 1] = '\0';
960 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
965 aind
= sizeof(abuf
) - 2;
967 abuf
[aind
--] = (min
% 10) + '0';
971 buf
[ind
++] = abuf
[aind
++];
975 /* Now add the seconds. */
976 aind
= sizeof (abuf
) - 2;
978 abuf
[aind
--] = (sec
% 10) + '0';
982 buf
[ind
++] = abuf
[aind
++];
984 /* We want to add a decimal point and PREC places after it if PREC is
985 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
990 for (aind
= 1; aind
<= prec
; aind
++)
992 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
993 sec_fraction
%= precs
[aind
];
1004 /* Interpret the format string FORMAT, interpolating the following escape
1008 where the optional `prec' is a precision, meaning the number of
1009 characters after the decimal point, the optional `l' means to format
1010 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1011 and the last character is one of
1013 R number of seconds of `real' time
1014 U number of seconds of `user' time
1015 S number of seconds of `system' time
1017 An occurrence of `%%' in the format string is translated to a `%'. The
1018 result is printed to FP, a pointer to a FILE. The other variables are
1019 the seconds and thousandths of a second of real, user, and system time,
1022 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1033 char *str
, *s
, ts
[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1038 len
= strlen (format
);
1039 ssize
= (len
+ 64) - (len
% 64);
1040 str
= (char *)xmalloc (ssize
);
1043 for (s
= format
; *s
; s
++)
1045 if (*s
!= '%' || s
[1] == '\0')
1047 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1050 else if (s
[1] == '%')
1053 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1056 else if (s
[1] == 'P')
1062 sum_frac
= (cpu
% 100) * 10;
1063 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1064 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1065 strcpy (str
+ sindex
, ts
);
1070 prec
= 3; /* default is three places past the decimal point. */
1071 lng
= 0; /* default is to not use minutes or append `s' */
1073 if (DIGIT (*s
)) /* `precision' */
1076 if (prec
> 3) prec
= 3;
1078 if (*s
== 'l') /* `length extender' */
1083 if (*s
== 'R' || *s
== 'E')
1084 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1086 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1088 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1091 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s
);
1095 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1096 strcpy (str
+ sindex
, ts
);
1102 fprintf (fp
, "%s\n", str
);
1109 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1111 int asynchronous
, pipe_in
, pipe_out
;
1112 struct fd_bitmap
*fds_to_close
;
1114 int rv
, posix_time
, old_flags
;
1120 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1121 struct timeval real
, user
, sys
;
1122 struct timeval before
, after
;
1123 # if defined (HAVE_STRUCT_TIMEZONE)
1124 struct timezone dtz
; /* posix doesn't define this */
1126 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1128 # if defined (HAVE_TIMES)
1129 clock_t tbefore
, tafter
, real
, user
, sys
;
1130 struct tms before
, after
;
1134 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1135 # if defined (HAVE_STRUCT_TIMEZONE)
1136 gettimeofday (&before
, &dtz
);
1138 gettimeofday (&before
, (void *)NULL
);
1139 # endif /* !HAVE_STRUCT_TIMEZONE */
1140 getrusage (RUSAGE_SELF
, &selfb
);
1141 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1143 # if defined (HAVE_TIMES)
1144 tbefore
= times (&before
);
1148 posix_time
= (command
->flags
& CMD_TIME_POSIX
);
1150 old_flags
= command
->flags
;
1151 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1152 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1153 command
->flags
= old_flags
;
1156 rsf
= usf
= ssf
= cpu
= 0;
1158 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1159 # if defined (HAVE_STRUCT_TIMEZONE)
1160 gettimeofday (&after
, &dtz
);
1162 gettimeofday (&after
, (void *)NULL
);
1163 # endif /* !HAVE_STRUCT_TIMEZONE */
1164 getrusage (RUSAGE_SELF
, &selfa
);
1165 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1167 difftimeval (&real
, &before
, &after
);
1168 timeval_to_secs (&real
, &rs
, &rsf
);
1170 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1171 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1172 timeval_to_secs (&user
, &us
, &usf
);
1174 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1175 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1176 timeval_to_secs (&sys
, &ss
, &ssf
);
1178 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1180 # if defined (HAVE_TIMES)
1181 tafter
= times (&after
);
1183 real
= tafter
- tbefore
;
1184 clock_t_to_secs (real
, &rs
, &rsf
);
1186 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1187 clock_t_to_secs (user
, &us
, &usf
);
1189 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1190 clock_t_to_secs (sys
, &ss
, &ssf
);
1192 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1196 rsf
= usf
= ssf
= cpu
= 0;
1201 time_format
= POSIX_TIMEFORMAT
;
1202 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1203 time_format
= BASH_TIMEFORMAT
;
1205 if (time_format
&& *time_format
)
1206 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1210 #endif /* COMMAND_TIMING */
1212 /* Execute a command that's supposed to be in a subshell. This must be
1213 called after make_child and we must be running in the child process.
1214 The caller will return or exit() immediately with the value this returns. */
1216 execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1219 int pipe_in
, pipe_out
;
1220 struct fd_bitmap
*fds_to_close
;
1222 int user_subshell
, return_code
, function_value
, should_redir_stdin
, invert
;
1223 int ois
, user_coproc
;
1226 USE_VAR(user_subshell
);
1227 USE_VAR(user_coproc
);
1230 USE_VAR(asynchronous
);
1233 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
1234 pipe_in
== NO_PIPE
&&
1235 stdin_redirects (command
->redirects
) == 0);
1237 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
1238 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
1239 user_coproc
= command
->type
== cm_coproc
;
1241 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
1243 /* If a command is asynchronous in a subshell (like ( foo ) & or
1244 the special case of an asynchronous GROUP command where the
1245 the subshell bit is turned on down in case cm_group: below),
1246 turn off `asynchronous', so that two subshells aren't spawned.
1247 XXX - asynchronous used to be set to 0 in this block, but that
1248 means that setup_async_signals was never run. Now it's set to
1249 0 after subshell_environment is set appropriately and setup_async_signals
1252 This seems semantically correct to me. For example,
1253 ( foo ) & seems to say ``do the command `foo' in a subshell
1254 environment, but don't wait for that subshell to finish'',
1255 and "{ foo ; bar ; } &" seems to me to be like functions or
1256 builtins in the background, which executed in a subshell
1257 environment. I just don't see the need to fork two subshells. */
1259 /* Don't fork again, we are already in a subshell. A `doubly
1260 async' shell is not interactive, however. */
1263 #if defined (JOB_CONTROL)
1264 /* If a construct like ( exec xxx yyy ) & is given while job
1265 control is active, we want to prevent exec from putting the
1266 subshell back into the original process group, carefully
1267 undoing all the work we just did in make_child. */
1269 #endif /* JOB_CONTROL */
1270 ois
= interactive_shell
;
1271 interactive_shell
= 0;
1272 /* This test is to prevent alias expansion by interactive shells that
1273 run `(command) &' but to allow scripts that have enabled alias
1274 expansion with `shopt -s expand_alias' to continue to expand
1276 if (ois
!= interactive_shell
)
1280 /* Subshells are neither login nor interactive. */
1281 login_shell
= interactive
= 0;
1284 subshell_environment
= SUBSHELL_PAREN
;
1287 subshell_environment
= 0; /* XXX */
1289 subshell_environment
|= SUBSHELL_ASYNC
;
1290 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
1291 subshell_environment
|= SUBSHELL_PIPE
;
1293 subshell_environment
|= SUBSHELL_COPROC
;
1296 reset_terminating_signals (); /* in sig.c */
1297 /* Cancel traps, in trap.c. */
1298 restore_original_signals ();
1300 /* Make sure restore_original_signals doesn't undo the work done by
1301 make_child to ensure that asynchronous children are immune to SIGINT
1302 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1306 setup_async_signals ();
1310 #if defined (JOB_CONTROL)
1311 set_sigchld_handler ();
1312 #endif /* JOB_CONTROL */
1314 set_sigint_handler ();
1316 #if defined (JOB_CONTROL)
1317 /* Delete all traces that there were any jobs running. This is
1318 only for subshells. */
1319 without_job_control ();
1320 #endif /* JOB_CONTROL */
1323 close_fd_bitmap (fds_to_close
);
1325 do_piping (pipe_in
, pipe_out
);
1327 #if defined (COPROCESS_SUPPORT)
1331 /* If this is a user subshell, set a flag if stdin was redirected.
1332 This is used later to decide whether to redirect fd 0 to
1333 /dev/null for async commands in the subshell. This adds more
1334 sh compatibility, but I'm not sure it's the right thing to do. */
1337 stdin_redir
= stdin_redirects (command
->redirects
);
1338 restore_default_signal (0);
1341 /* If this is an asynchronous command (command &), we want to
1342 redirect the standard input from /dev/null in the absence of
1343 any specific redirection involving stdin. */
1344 if (should_redir_stdin
&& stdin_redir
== 0)
1345 async_redirect_stdin ();
1347 /* Do redirections, then dispose of them before recursive call. */
1348 if (command
->redirects
)
1350 if (do_redirections (command
->redirects
, RX_ACTIVE
) != 0)
1351 exit (invert
? EXECUTION_SUCCESS
: EXECUTION_FAILURE
);
1353 dispose_redirects (command
->redirects
);
1354 command
->redirects
= (REDIRECT
*)NULL
;
1357 if (command
->type
== cm_subshell
)
1358 tcom
= command
->value
.Subshell
->command
;
1359 else if (user_coproc
)
1360 tcom
= command
->value
.Coproc
->command
;
1364 if (command
->flags
& CMD_TIME_PIPELINE
)
1365 tcom
->flags
|= CMD_TIME_PIPELINE
;
1366 if (command
->flags
& CMD_TIME_POSIX
)
1367 tcom
->flags
|= CMD_TIME_POSIX
;
1369 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1370 if ((command
->flags
& CMD_IGNORE_RETURN
) && tcom
!= command
)
1371 tcom
->flags
|= CMD_IGNORE_RETURN
;
1373 /* If this is a simple command, tell execute_disk_command that it
1374 might be able to get away without forking and simply exec.
1375 This means things like ( sleep 10 ) will only cause one fork.
1376 If we're timing the command or inverting its return value, however,
1377 we cannot do this optimization. */
1378 if ((user_subshell
|| user_coproc
) && (tcom
->type
== cm_simple
|| tcom
->type
== cm_subshell
) &&
1379 ((tcom
->flags
& CMD_TIME_PIPELINE
) == 0) &&
1380 ((tcom
->flags
& CMD_INVERT_RETURN
) == 0))
1382 tcom
->flags
|= CMD_NO_FORK
;
1383 if (tcom
->type
== cm_simple
)
1384 tcom
->value
.Simple
->flags
|= CMD_NO_FORK
;
1387 invert
= (tcom
->flags
& CMD_INVERT_RETURN
) != 0;
1388 tcom
->flags
&= ~CMD_INVERT_RETURN
;
1390 /* If we're inside a function while executing this subshell, we
1391 need to handle a possible `return'. */
1393 if (return_catch_flag
)
1394 function_value
= setjmp (return_catch
);
1397 return_code
= return_catch_value
;
1399 return_code
= execute_command_internal (tcom
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
1401 /* If we are asked to, invert the return value. */
1403 return_code
= (return_code
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
1404 : EXECUTION_SUCCESS
;
1406 /* If we were explicitly placed in a subshell with (), we need
1407 to do the `shell cleanup' things, such as running traps[0]. */
1408 if (user_subshell
&& signal_is_trapped (0))
1410 last_command_exit_value
= return_code
;
1411 return_code
= run_exit_trap ();
1415 return (return_code
);
1419 #if defined (COPROCESS_SUPPORT)
1420 #define COPROC_MAX 16
1422 typedef struct cpelement
1424 struct cpelement
*next
;
1425 struct coproc
*coproc
;
1429 typedef struct cplist
1431 struct cpelement
*head
;
1432 struct cpelement
*tail
;
1437 static struct cpelement
*cpe_alloc
__P((struct coproc
*));
1438 static void cpe_dispose
__P((struct cpelement
*));
1439 static struct cpelement
*cpl_add
__P((struct coproc
*));
1440 static struct cpelement
*cpl_delete
__P((pid_t
));
1441 static void cpl_flush
__P((void));
1442 static struct cpelement
*cpl_search
__P((pid_t
));
1443 static struct cpelement
*cpl_searchbyname
__P((char *));
1444 static void cpl_prune
__P((void));
1446 Coproc sh_coproc
= { 0, NO_PID
, -1, -1, 0, 0 };
1448 cplist_t coproc_list
= {0, 0, 0};
1450 /* Functions to manage the list of exited background pids whose status has
1453 static struct cpelement
*
1457 struct cpelement
*cpe
;
1459 cpe
= (struct cpelement
*)xmalloc (sizeof (struct cpelement
));
1461 cpe
->next
= (struct cpelement
*)0;
1467 struct cpelement
*cpe
;
1472 static struct cpelement
*
1476 struct cpelement
*cpe
;
1478 cpe
= cpe_alloc (cp
);
1480 if (coproc_list
.head
== 0)
1482 coproc_list
.head
= coproc_list
.tail
= cpe
;
1483 coproc_list
.ncoproc
= 0; /* just to make sure */
1487 coproc_list
.tail
->next
= cpe
;
1488 coproc_list
.tail
= cpe
;
1490 coproc_list
.ncoproc
++;
1495 static struct cpelement
*
1499 struct cpelement
*prev
, *p
;
1501 for (prev
= p
= coproc_list
.head
; p
; prev
= p
, p
= p
->next
)
1502 if (p
->coproc
->c_pid
== pid
)
1504 prev
->next
= p
->next
; /* remove from list */
1509 return 0; /* not found */
1512 itrace("cpl_delete: deleting %d", pid
);
1515 /* Housekeeping in the border cases. */
1516 if (p
== coproc_list
.head
)
1517 coproc_list
.head
= coproc_list
.head
->next
;
1518 else if (p
== coproc_list
.tail
)
1519 coproc_list
.tail
= prev
;
1521 coproc_list
.ncoproc
--;
1522 if (coproc_list
.ncoproc
== 0)
1523 coproc_list
.head
= coproc_list
.tail
= 0;
1524 else if (coproc_list
.ncoproc
== 1)
1525 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1530 /* Clear out the list of saved statuses */
1534 struct cpelement
*cpe
, *p
;
1536 for (cpe
= coproc_list
.head
; cpe
; )
1541 coproc_dispose (p
->coproc
);
1545 coproc_list
.head
= coproc_list
.tail
= 0;
1546 coproc_list
.ncoproc
= 0;
1549 /* Search for PID in the list of coprocs; return the cpelement struct if
1550 found. If not found, return NULL. */
1551 static struct cpelement
*
1555 struct cpelement
*cp
;
1557 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1558 if (cp
->coproc
->c_pid
== pid
)
1560 return (struct cpelement
*)NULL
;
1563 /* Search for the coproc named NAME in the list of coprocs; return the
1564 cpelement struct if found. If not found, return NULL. */
1565 static struct cpelement
*
1566 cpl_searchbyname (name
)
1569 struct cpelement
*cp
;
1571 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1572 if (STREQ (cp
->coproc
->c_name
, name
))
1574 return (struct cpelement
*)NULL
;
1581 struct cpelement
*cp
;
1583 while (coproc_list
.head
&& coproc_list
.ncoproc
> COPROC_MAX
)
1585 cp
= coproc_list
.head
;
1586 coproc_list
.head
= coproc_list
.head
->next
;
1587 coproc_dispose (cp
->coproc
);
1589 coproc_list
.ncoproc
--;
1594 /* These currently use a single global "shell coproc" but are written in a
1595 way to not preclude additional coprocs later (using the list management
1599 getcoprocbypid (pid
)
1602 return (pid
== sh_coproc
.c_pid
? &sh_coproc
: 0);
1606 getcoprocbyname (name
)
1609 return ((sh_coproc
.c_name
&& STREQ (sh_coproc
.c_name
, name
)) ? &sh_coproc
: 0);
1618 cp
->c_rfd
= cp
->c_wfd
= -1;
1619 cp
->c_rsave
= cp
->c_wsave
= -1;
1620 cp
->c_flags
= cp
->c_status
= 0;
1624 coproc_alloc (name
, pid
)
1630 cp
= &sh_coproc
; /* XXX */
1633 cp
->c_name
= savestring (name
);
1646 coproc_unsetvars (cp
);
1652 /* Placeholder for now. */
1656 coproc_dispose (&sh_coproc
);
1673 cp
->c_rsave
= cp
->c_wsave
= -1;
1679 coproc_close (&sh_coproc
);
1683 coproc_rclose (cp
, fd
)
1687 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
1695 coproc_wclose (cp
, fd
)
1699 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
1707 coproc_checkfd (cp
, fd
)
1714 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
1715 update
= cp
->c_rfd
= -1;
1716 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
1717 update
= cp
->c_wfd
= -1;
1719 coproc_setvars (cp
);
1726 coproc_checkfd (&sh_coproc
, fd
);
1730 coproc_fdclose (cp
, fd
)
1734 coproc_rclose (cp
, fd
);
1735 coproc_wclose (cp
, fd
);
1736 coproc_setvars (cp
);
1743 cp
->c_rsave
= cp
->c_rfd
;
1744 cp
->c_wsave
= cp
->c_wfd
;
1748 coproc_fdrestore (cp
)
1751 cp
->c_rfd
= cp
->c_rsave
;
1752 cp
->c_wfd
= cp
->c_wsave
;
1761 cp
= getcoprocbypid (pid
);
1764 itrace("coproc_pidchk: pid %d has died", pid
);
1767 coproc_dispose (cp
);
1777 #if defined (ARRAY_VARS)
1781 if (cp
->c_name
== 0)
1784 l
= strlen (cp
->c_name
);
1785 namevar
= xmalloc (l
+ 16);
1787 #if defined (ARRAY_VARS)
1788 v
= find_variable (cp
->c_name
);
1790 v
= make_new_array_variable (cp
->c_name
);
1791 if (array_p (v
) == 0)
1792 v
= convert_var_to_array (v
);
1794 t
= itos (cp
->c_rfd
);
1796 v
= bind_array_variable (cp
->c_name
, ind
, t
, 0);
1799 t
= itos (cp
->c_wfd
);
1801 bind_array_variable (cp
->c_name
, ind
, t
, 0);
1804 sprintf (namevar
, "%s_READ", cp
->c_name
);
1805 t
= itos (cp
->c_rfd
);
1806 bind_variable (namevar
, t
, 0);
1808 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
1809 t
= itos (cp
->c_wfd
);
1810 bind_variable (namevar
, t
, 0);
1814 sprintf (namevar
, "%s_PID", cp
->c_name
);
1815 t
= itos (cp
->c_pid
);
1816 bind_variable (namevar
, t
, 0);
1823 coproc_unsetvars (cp
)
1829 if (cp
->c_name
== 0)
1832 l
= strlen (cp
->c_name
);
1833 namevar
= xmalloc (l
+ 16);
1835 sprintf (namevar
, "%s_PID", cp
->c_name
);
1836 unbind_variable (namevar
);
1838 #if defined (ARRAY_VARS)
1839 unbind_variable (cp
->c_name
);
1841 sprintf (namevar
, "%s_READ", cp
->c_name
);
1842 unbind_variable (namevar
);
1843 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
1844 unbind_variable (namevar
);
1851 execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
)
1853 int pipe_in
, pipe_out
;
1854 struct fd_bitmap
*fds_to_close
;
1856 int rpipe
[2], wpipe
[2];
1861 /* XXX -- will require changes to handle multiple coprocs */
1862 if (sh_coproc
.c_pid
!= NO_PID
)
1865 internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc
.c_pid
, sh_coproc
.c_name
);
1866 return (last_command_exit_value
= EXECUTION_FAILURE
);
1868 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc
.c_pid
, sh_coproc
.c_name
);
1871 coproc_init (&sh_coproc
);
1873 command_string_index
= 0;
1874 tcmd
= make_command_string (command
);
1876 sh_openpipe ((int *)&rpipe
); /* 0 = parent read, 1 = child write */
1877 sh_openpipe ((int *)&wpipe
); /* 0 = child read, 1 = parent write */
1879 coproc_pid
= make_child (savestring (tcmd
), 1);
1880 if (coproc_pid
== 0)
1885 exit (execute_in_subshell (command
, 1, wpipe
[0], rpipe
[1], fds_to_close
));
1891 cp
= coproc_alloc (command
->value
.Coproc
->name
, coproc_pid
);
1892 cp
->c_rfd
= rpipe
[0];
1893 cp
->c_wfd
= wpipe
[1];
1895 SET_CLOSE_ON_EXEC (cp
->c_rfd
);
1896 SET_CLOSE_ON_EXEC (cp
->c_wfd
);
1898 coproc_setvars (cp
);
1901 itrace ("execute_coproc: [%d] %s", coproc_pid
, the_printed_command
);
1904 close_pipes (pipe_in
, pipe_out
);
1905 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
1906 unlink_fifo_list ();
1908 stop_pipeline (1, (COMMAND
*)NULL
);
1909 DESCRIBE_PID (coproc_pid
);
1910 run_pending_traps ();
1912 return (EXECUTION_SUCCESS
);
1917 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1919 int asynchronous
, pipe_in
, pipe_out
;
1920 struct fd_bitmap
*fds_to_close
;
1922 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
1924 struct fd_bitmap
*fd_bitmap
;
1926 #if defined (JOB_CONTROL)
1928 BLOCK_CHILD (set
, oset
);
1929 #endif /* JOB_CONTROL */
1931 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1936 while (cmd
&& cmd
->type
== cm_connection
&&
1937 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
1939 /* Make a pipeline between the two commands. */
1940 if (pipe (fildes
) < 0)
1942 sys_error (_("pipe error"));
1943 #if defined (JOB_CONTROL)
1944 terminate_current_pipeline ();
1945 kill_current_pipeline ();
1946 UNBLOCK_CHILD (oset
);
1947 #endif /* JOB_CONTROL */
1948 last_command_exit_value
= EXECUTION_FAILURE
;
1949 /* The unwind-protects installed below will take care
1950 of closing all of the open file descriptors. */
1951 throw_to_top_level ();
1952 return (EXECUTION_FAILURE
); /* XXX */
1955 /* Here is a problem: with the new file close-on-exec
1956 code, the read end of the pipe (fildes[0]) stays open
1957 in the first process, so that process will never get a
1958 SIGPIPE. There is no way to signal the first process
1959 that it should close fildes[0] after forking, so it
1960 remains open. No SIGPIPE is ever sent because there
1961 is still a file descriptor open for reading connected
1962 to the pipe. We take care of that here. This passes
1963 around a bitmap of file descriptors that must be
1964 closed after making a child process in execute_simple_command. */
1966 /* We need fd_bitmap to be at least as big as fildes[0].
1967 If fildes[0] is less than fds_to_close->size, then
1968 use fds_to_close->size. */
1969 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
1970 ? fds_to_close
->size
1973 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
1975 /* Now copy the old information into the new bitmap. */
1976 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
1978 /* And mark the pipe file descriptors to be closed. */
1979 fd_bitmap
->bitmap
[fildes
[0]] = 1;
1981 /* In case there are pipe or out-of-processes errors, we
1982 want all these file descriptors to be closed when
1983 unwind-protects are run, and the storage used for the
1984 bitmaps freed up. */
1985 begin_unwind_frame ("pipe-file-descriptors");
1986 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
1987 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
1989 add_unwind_protect (close
, prev
);
1990 dummyfd
= fildes
[1];
1991 add_unwind_protect (close
, dummyfd
);
1993 #if defined (JOB_CONTROL)
1994 add_unwind_protect (restore_signal_mask
, &oset
);
1995 #endif /* JOB_CONTROL */
1997 if (ignore_return
&& cmd
->value
.Connection
->first
)
1998 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1999 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
2000 prev
, fildes
[1], fd_bitmap
);
2008 dispose_fd_bitmap (fd_bitmap
);
2009 discard_unwind_frame ("pipe-file-descriptors");
2011 cmd
= cmd
->value
.Connection
->second
;
2014 /* Now execute the rightmost command in the pipeline. */
2015 if (ignore_return
&& cmd
)
2016 cmd
->flags
|= CMD_IGNORE_RETURN
;
2017 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
2022 #if defined (JOB_CONTROL)
2023 UNBLOCK_CHILD (oset
);
2027 return (exec_result
);
2031 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2033 int asynchronous
, pipe_in
, pipe_out
;
2034 struct fd_bitmap
*fds_to_close
;
2037 COMMAND
*tc
, *second
;
2038 int ignore_return
, exec_result
;
2040 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2042 switch (command
->value
.Connection
->connector
)
2044 /* Do the first command asynchronously. */
2046 tc
= command
->value
.Connection
->first
;
2048 return (EXECUTION_SUCCESS
);
2053 tc
->flags
|= CMD_IGNORE_RETURN
;
2054 tc
->flags
|= CMD_AMPERSAND
;
2056 /* If this shell was compiled without job control support,
2057 if we are currently in a subshell via `( xxx )', or if job
2058 control is not active then the standard input for an
2059 asynchronous command is forced to /dev/null. */
2060 #if defined (JOB_CONTROL)
2061 if ((subshell_environment
|| !job_control
) && !stdin_redir
)
2064 #endif /* JOB_CONTROL */
2065 tc
->flags
|= CMD_STDIN_REDIR
;
2067 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
2070 if (tc
->flags
& CMD_STDIN_REDIR
)
2071 tc
->flags
&= ~CMD_STDIN_REDIR
;
2073 second
= command
->value
.Connection
->second
;
2077 second
->flags
|= CMD_IGNORE_RETURN
;
2079 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2084 /* Just call execute command on both sides. */
2088 if (command
->value
.Connection
->first
)
2089 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2090 if (command
->value
.Connection
->second
)
2091 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2095 execute_command (command
->value
.Connection
->first
);
2097 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
2098 asynchronous
, pipe_in
, pipe_out
,
2104 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2111 /* If we have something like `a && b &' or `a || b &', run the
2112 && or || stuff in a subshell. Force a subshell and just call
2113 execute_command_internal again. Leave asynchronous on
2114 so that we get a report from the parent shell about the
2116 command
->flags
|= CMD_FORCE_SUBSHELL
;
2117 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
2121 /* Execute the first command. If the result of that is successful
2122 and the connector is AND_AND, or the result is not successful
2123 and the connector is OR_OR, then execute the second command,
2124 otherwise return. */
2127 if (command
->value
.Connection
->first
)
2128 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2130 exec_result
= execute_command (command
->value
.Connection
->first
);
2132 if (((command
->value
.Connection
->connector
== AND_AND
) &&
2133 (exec_result
== EXECUTION_SUCCESS
)) ||
2134 ((command
->value
.Connection
->connector
== OR_OR
) &&
2135 (exec_result
!= EXECUTION_SUCCESS
)))
2137 if (ignore_return
&& command
->value
.Connection
->second
)
2138 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2140 exec_result
= execute_command (command
->value
.Connection
->second
);
2146 command_error ("execute_connection", CMDERR_BADCONN
, command
->value
.Connection
->connector
, 0);
2147 jump_to_top_level (DISCARD
);
2148 exec_result
= EXECUTION_FAILURE
;
2157 if (!interactive_shell) \
2158 reap_dead_jobs (); \
2162 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2165 execute_for_command (for_command
)
2166 FOR_COM
*for_command
;
2168 register WORD_LIST
*releaser
, *list
;
2171 int retval
, save_line_number
;
2173 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
2176 save_line_number
= line_number
;
2177 if (check_identifier (for_command
->name
, 1) == 0)
2179 if (posixly_correct
&& interactive_shell
== 0)
2181 last_command_exit_value
= EX_BADUSAGE
;
2182 jump_to_top_level (ERREXIT
);
2184 return (EXECUTION_FAILURE
);
2188 identifier
= for_command
->name
->word
;
2190 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
2192 begin_unwind_frame ("for");
2193 add_unwind_protect (dispose_words
, releaser
);
2196 if (lexical_scoping
)
2198 old_value
= copy_variable (find_variable (identifier
));
2200 add_unwind_protect (dispose_variable
, old_value
);
2204 if (for_command
->flags
& CMD_IGNORE_RETURN
)
2205 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2207 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
2211 line_number
= for_command
->line
;
2213 /* Remember what this command looks like, for debugger. */
2214 command_string_index
= 0;
2215 print_for_command_head (for_command
);
2217 if (echo_command_at_execute
)
2218 xtrace_print_for_command_head (for_command
);
2220 /* Save this command unless it's a trap command and we're not running
2223 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2225 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2228 FREE (the_printed_command_except_trap
);
2229 the_printed_command_except_trap
= savestring (the_printed_command
);
2232 retval
= run_debug_trap ();
2233 #if defined (DEBUGGER)
2234 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2235 skip the command. */
2236 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2240 this_command_name
= (char *)NULL
;
2241 v
= bind_variable (identifier
, list
->word
->word
, 0);
2242 if (readonly_p (v
) || noassign_p (v
))
2244 line_number
= save_line_number
;
2245 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2247 last_command_exit_value
= EXECUTION_FAILURE
;
2248 jump_to_top_level (FORCE_EOF
);
2252 dispose_words (releaser
);
2253 discard_unwind_frame ("for");
2255 return (EXECUTION_FAILURE
);
2258 retval
= execute_command (for_command
->action
);
2277 line_number
= save_line_number
;
2280 if (lexical_scoping
)
2283 unbind_variable (identifier
);
2286 SHELL_VAR
*new_value
;
2288 new_value
= bind_variable (identifier
, value_cell(old_value
), 0);
2289 new_value
->attributes
= old_value
->attributes
;
2290 dispose_variable (old_value
);
2295 dispose_words (releaser
);
2296 discard_unwind_frame ("for");
2300 #if defined (ARITH_FOR_COMMAND)
2301 /* Execute an arithmetic for command. The syntax is
2303 for (( init ; step ; test ))
2308 The execution should be exactly equivalent to
2311 while eval \(\( test \)\) ; do
2317 eval_arith_for_expr (l
, okp
)
2325 new = expand_words_no_vars (l
);
2328 if (echo_command_at_execute
)
2329 xtrace_print_arith_cmd (new);
2330 this_command_name
= "(("; /* )) for expression error messages */
2332 command_string_index
= 0;
2333 print_arith_command (new);
2334 if (signal_in_progress (DEBUG_TRAP
) == 0)
2336 FREE (the_printed_command_except_trap
);
2337 the_printed_command_except_trap
= savestring (the_printed_command
);
2340 r
= run_debug_trap ();
2341 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2342 skip the command. */
2343 #if defined (DEBUGGER)
2344 if (debugging_mode
== 0 || r
== EXECUTION_SUCCESS
)
2345 expresult
= evalexp (new->word
->word
, okp
);
2353 expresult
= evalexp (new->word
->word
, okp
);
2355 dispose_words (new);
2367 execute_arith_for_command (arith_for_command
)
2368 ARITH_FOR_COM
*arith_for_command
;
2371 int expok
, body_status
, arith_lineno
, save_lineno
;
2373 body_status
= EXECUTION_SUCCESS
;
2375 save_lineno
= line_number
;
2377 if (arith_for_command
->flags
& CMD_IGNORE_RETURN
)
2378 arith_for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2380 this_command_name
= "(("; /* )) for expression error messages */
2382 /* save the starting line number of the command so we can reset
2383 line_number before executing each expression -- for $LINENO
2384 and the DEBUG trap. */
2385 line_number
= arith_lineno
= arith_for_command
->line
;
2386 if (variable_context
&& interactive_shell
)
2387 line_number
-= function_line_number
;
2389 /* Evaluate the initialization expression. */
2390 expresult
= eval_arith_for_expr (arith_for_command
->init
, &expok
);
2393 line_number
= save_lineno
;
2394 return (EXECUTION_FAILURE
);
2399 /* Evaluate the test expression. */
2400 line_number
= arith_lineno
;
2401 expresult
= eval_arith_for_expr (arith_for_command
->test
, &expok
);
2402 line_number
= save_lineno
;
2406 body_status
= EXECUTION_FAILURE
;
2413 /* Execute the body of the arithmetic for command. */
2415 body_status
= execute_command (arith_for_command
->action
);
2418 /* Handle any `break' or `continue' commands executed by the body. */
2432 /* Evaluate the step expression. */
2433 line_number
= arith_lineno
;
2434 expresult
= eval_arith_for_expr (arith_for_command
->step
, &expok
);
2435 line_number
= save_lineno
;
2439 body_status
= EXECUTION_FAILURE
;
2445 line_number
= save_lineno
;
2447 return (body_status
);
2451 #if defined (SELECT_COMMAND)
2452 static int LINES
, COLS
, tabsize
;
2454 #define RP_SPACE ") "
2455 #define RP_SPACE_LEN 2
2457 /* XXX - does not handle numbers > 1000000 at all. */
2458 #define NUMBER_LEN(s) \
2462 : ((s < 10000) ? 4 \
2463 : ((s < 100000) ? 5 \
2467 print_index_and_element (len
, ind
, list
)
2471 register WORD_LIST
*l
;
2476 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
2478 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
2479 return (STRLEN (l
->word
->word
));
2488 if ((to
/ tabsize
) > (from
/ tabsize
))
2490 putc ('\t', stderr
);
2491 from
+= tabsize
- from
% tabsize
;
2502 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
2504 int list_len
, max_elem_len
, indices_len
;
2506 int ind
, row
, elem_len
, pos
, cols
, rows
;
2507 int first_column_indices_len
, other_indices_len
;
2511 putc ('\n', stderr
);
2515 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
2518 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
2519 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
2527 first_column_indices_len
= NUMBER_LEN (rows
);
2528 other_indices_len
= indices_len
;
2530 for (row
= 0; row
< rows
; row
++)
2536 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
2537 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
2538 elem_len
+= indices_len
+ RP_SPACE_LEN
;
2540 if (ind
>= list_len
)
2542 indent (pos
+ elem_len
, pos
+ max_elem_len
);
2543 pos
+= max_elem_len
;
2545 putc ('\n', stderr
);
2549 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2550 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2551 If the number is between 1 and LIST_LEN, return that selection. If EOF
2552 is read, return a null string. If a blank line is entered, or an invalid
2553 number is entered, the loop is executed again. */
2555 select_query (list
, list_len
, prompt
, print_menu
)
2561 int max_elem_len
, indices_len
, len
;
2564 char *repl_string
, *t
;
2566 t
= get_string_value ("LINES");
2567 LINES
= (t
&& *t
) ? atoi (t
) : 24;
2568 t
= get_string_value ("COLUMNS");
2569 COLS
= (t
&& *t
) ? atoi (t
) : 80;
2572 t
= get_string_value ("TABSIZE");
2573 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
2581 for (l
= list
; l
; l
= l
->next
)
2583 len
= STRLEN (l
->word
->word
);
2584 if (len
> max_elem_len
)
2587 indices_len
= NUMBER_LEN (list_len
);
2588 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
2593 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
2594 fprintf (stderr
, "%s", prompt
);
2598 if (read_builtin ((WORD_LIST
*)NULL
) == EXECUTION_FAILURE
)
2601 return ((char *)NULL
);
2603 repl_string
= get_string_value ("REPLY");
2604 if (*repl_string
== 0)
2609 if (legal_number (repl_string
, &reply
) == 0)
2611 if (reply
< 1 || reply
> list_len
)
2614 for (l
= list
; l
&& --reply
; l
= l
->next
)
2616 return (l
->word
->word
);
2620 /* Execute a SELECT command. The syntax is:
2621 SELECT word IN list DO command_list DONE
2622 Only `break' or `return' in command_list will terminate
2625 execute_select_command (select_command
)
2626 SELECT_COM
*select_command
;
2628 WORD_LIST
*releaser
, *list
;
2630 char *identifier
, *ps3_prompt
, *selection
;
2631 int retval
, list_len
, show_menu
, save_line_number
;
2633 if (check_identifier (select_command
->name
, 1) == 0)
2634 return (EXECUTION_FAILURE
);
2636 save_line_number
= line_number
;
2637 line_number
= select_command
->line
;
2639 command_string_index
= 0;
2640 print_select_command_head (select_command
);
2642 if (echo_command_at_execute
)
2643 xtrace_print_select_command_head (select_command
);
2646 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2648 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2651 FREE (the_printed_command_except_trap
);
2652 the_printed_command_except_trap
= savestring (the_printed_command
);
2655 retval
= run_debug_trap ();
2656 #if defined (DEBUGGER)
2657 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2658 skip the command. */
2659 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2660 return (EXECUTION_SUCCESS
);
2664 identifier
= select_command
->name
->word
;
2666 /* command and arithmetic substitution, parameter and variable expansion,
2667 word splitting, pathname expansion, and quote removal. */
2668 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
2669 list_len
= list_length (list
);
2670 if (list
== 0 || list_len
== 0)
2673 dispose_words (list
);
2674 line_number
= save_line_number
;
2675 return (EXECUTION_SUCCESS
);
2678 begin_unwind_frame ("select");
2679 add_unwind_protect (dispose_words
, releaser
);
2681 if (select_command
->flags
& CMD_IGNORE_RETURN
)
2682 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2684 retval
= EXECUTION_SUCCESS
;
2689 line_number
= select_command
->line
;
2690 ps3_prompt
= get_string_value ("PS3");
2691 if (ps3_prompt
== 0)
2695 selection
= select_query (list
, list_len
, ps3_prompt
, show_menu
);
2699 /* select_query returns EXECUTION_FAILURE if the read builtin
2700 fails, so we want to return failure in this case. */
2701 retval
= EXECUTION_FAILURE
;
2705 v
= bind_variable (identifier
, selection
, 0);
2706 if (readonly_p (v
) || noassign_p (v
))
2708 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2710 last_command_exit_value
= EXECUTION_FAILURE
;
2711 jump_to_top_level (FORCE_EOF
);
2715 dispose_words (releaser
);
2716 discard_unwind_frame ("select");
2718 line_number
= save_line_number
;
2719 return (EXECUTION_FAILURE
);
2723 retval
= execute_command (select_command
->action
);
2741 #if defined (KSH_COMPATIBLE_SELECT)
2743 selection
= get_string_value ("REPLY");
2744 if (selection
&& *selection
== '\0')
2750 line_number
= save_line_number
;
2752 dispose_words (releaser
);
2753 discard_unwind_frame ("select");
2756 #endif /* SELECT_COMMAND */
2758 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2759 The pattern_list is a linked list of pattern clauses; each clause contains
2760 some patterns to compare word_desc against, and an associated command to
2763 execute_case_command (case_command
)
2764 CASE_COM
*case_command
;
2766 register WORD_LIST
*list
;
2767 WORD_LIST
*wlist
, *es
;
2768 PATTERN_LIST
*clauses
;
2769 char *word
, *pattern
;
2770 int retval
, match
, ignore_return
, save_line_number
;
2772 save_line_number
= line_number
;
2773 line_number
= case_command
->line
;
2775 command_string_index
= 0;
2776 print_case_command_head (case_command
);
2778 if (echo_command_at_execute
)
2779 xtrace_print_case_command_head (case_command
);
2782 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2784 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2787 FREE (the_printed_command_except_trap
);
2788 the_printed_command_except_trap
= savestring (the_printed_command
);
2791 retval
= run_debug_trap();
2792 #if defined (DEBUGGER)
2793 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2794 skip the command. */
2795 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2797 line_number
= save_line_number
;
2798 return (EXECUTION_SUCCESS
);
2802 wlist
= expand_word_unsplit (case_command
->word
, 0);
2803 word
= wlist
? string_list (wlist
) : savestring ("");
2804 dispose_words (wlist
);
2806 retval
= EXECUTION_SUCCESS
;
2807 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
2809 begin_unwind_frame ("case");
2810 add_unwind_protect ((Function
*)xfree
, word
);
2812 #define EXIT_CASE() goto exit_case_command
2814 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
2817 for (list
= clauses
->patterns
; list
; list
= list
->next
)
2819 es
= expand_word_leave_quoted (list
->word
, 0);
2821 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
2822 pattern
= quote_string_for_globbing (es
->word
->word
, QGLOB_CVTNULL
);
2825 pattern
= (char *)xmalloc (1);
2829 /* Since the pattern does not undergo quote removal (as per
2830 Posix.2, section 3.9.4.3), the strmatch () call must be able
2831 to recognize backslashes as escape characters. */
2832 match
= strmatch (pattern
, word
, FNMATCH_EXTFLAG
|FNMATCH_IGNCASE
) != FNM_NOMATCH
;
2841 if (clauses
->action
&& ignore_return
)
2842 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
2843 retval
= execute_command (clauses
->action
);
2845 while ((clauses
->flags
& CASEPAT_FALLTHROUGH
) && (clauses
= clauses
->next
));
2846 if ((clauses
->flags
& CASEPAT_TESTNEXT
) == 0)
2858 discard_unwind_frame ("case");
2859 line_number
= save_line_number
;
2866 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2867 Repeatedly execute action while executing test produces
2868 EXECUTION_SUCCESS. */
2870 execute_while_command (while_command
)
2871 WHILE_COM
*while_command
;
2873 return (execute_while_or_until (while_command
, CMD_WHILE
));
2876 /* UNTIL is just like WHILE except that the test result is negated. */
2878 execute_until_command (while_command
)
2879 WHILE_COM
*while_command
;
2881 return (execute_while_or_until (while_command
, CMD_UNTIL
));
2884 /* The body for both while and until. The only difference between the
2885 two is that the test value is treated differently. TYPE is
2886 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2887 be EXECUTION_SUCCESS if no commands in the body are executed, and
2888 the status of the last command executed in the body otherwise. */
2890 execute_while_or_until (while_command
, type
)
2891 WHILE_COM
*while_command
;
2894 int return_value
, body_status
;
2896 body_status
= EXECUTION_SUCCESS
;
2899 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2900 if (while_command
->flags
& CMD_IGNORE_RETURN
)
2901 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2905 return_value
= execute_command (while_command
->test
);
2908 /* Need to handle `break' in the test when we would break out of the
2909 loop. The job control code will set `breaking' to loop_level
2910 when a job in a loop is stopped with SIGTSTP. If the stopped job
2911 is in the loop test, `breaking' will not be reset unless we do
2912 this, and the shell will cease to execute commands. */
2913 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
2919 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
2927 body_status
= execute_command (while_command
->action
);
2945 return (body_status
);
2948 /* IF test THEN command [ELSE command].
2949 IF also allows ELIF in the place of ELSE IF, but
2950 the parser makes *that* stupidity transparent. */
2952 execute_if_command (if_command
)
2955 int return_value
, save_line_number
;
2957 save_line_number
= line_number
;
2958 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2959 return_value
= execute_command (if_command
->test
);
2960 line_number
= save_line_number
;
2962 if (return_value
== EXECUTION_SUCCESS
)
2966 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2967 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
2969 return (execute_command (if_command
->true_case
));
2975 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2976 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
2978 return (execute_command (if_command
->false_case
));
2982 #if defined (DPAREN_ARITHMETIC)
2984 execute_arith_command (arith_command
)
2985 ARITH_COM
*arith_command
;
2987 int expok
, save_line_number
, retval
;
2994 save_line_number
= line_number
;
2995 this_command_name
= "(("; /* )) */
2996 line_number
= arith_command
->line
;
2997 /* If we're in a function, update the line number information. */
2998 if (variable_context
&& interactive_shell
)
2999 line_number
-= function_line_number
;
3001 command_string_index
= 0;
3002 print_arith_command (arith_command
->exp
);
3004 if (signal_in_progress (DEBUG_TRAP
) == 0)
3006 FREE (the_printed_command_except_trap
);
3007 the_printed_command_except_trap
= savestring (the_printed_command
);
3010 /* Run the debug trap before each arithmetic command, but do it after we
3011 update the line number information and before we expand the various
3012 words in the expression. */
3013 retval
= run_debug_trap ();
3014 #if defined (DEBUGGER)
3015 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3016 skip the command. */
3017 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3019 line_number
= save_line_number
;
3020 return (EXECUTION_SUCCESS
);
3024 new = expand_words_no_vars (arith_command
->exp
);
3026 /* If we're tracing, make a new word list with `((' at the front and `))'
3027 at the back and print it. */
3028 if (echo_command_at_execute
)
3029 xtrace_print_arith_cmd (new);
3033 exp
= new->next
? string_list (new) : new->word
->word
;
3034 expresult
= evalexp (exp
, &expok
);
3035 line_number
= save_line_number
;
3036 if (exp
!= new->word
->word
)
3038 dispose_words (new);
3047 return (EXECUTION_FAILURE
);
3049 return (expresult
== 0 ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
3051 #endif /* DPAREN_ARITHMETIC */
3053 #if defined (COND_COMMAND)
3055 static char * const nullstr
= "";
3058 execute_cond_node (cond
)
3061 int result
, invert
, patmatch
, rmatch
, mflags
;
3064 invert
= (cond
->flags
& CMD_INVERT_RETURN
);
3066 if (cond
->type
== COND_EXPR
)
3067 result
= execute_cond_node (cond
->left
);
3068 else if (cond
->type
== COND_OR
)
3070 result
= execute_cond_node (cond
->left
);
3071 if (result
!= EXECUTION_SUCCESS
)
3072 result
= execute_cond_node (cond
->right
);
3074 else if (cond
->type
== COND_AND
)
3076 result
= execute_cond_node (cond
->left
);
3077 if (result
== EXECUTION_SUCCESS
)
3078 result
= execute_cond_node (cond
->right
);
3080 else if (cond
->type
== COND_UNARY
)
3082 arg1
= cond_expand_word (cond
->left
->op
, 0);
3085 if (echo_command_at_execute
)
3086 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, (char *)NULL
);
3087 result
= unary_test (cond
->op
->word
, arg1
) ? EXECUTION_SUCCESS
: EXECUTION_FAILURE
;
3088 if (arg1
!= nullstr
)
3091 else if (cond
->type
== COND_BINARY
)
3094 patmatch
= ((cond
->op
->word
[1] == '=') && (cond
->op
->word
[2] == '\0') &&
3095 (cond
->op
->word
[0] == '!' || cond
->op
->word
[0] == '=') ||
3096 (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '\0'));
3097 #if defined (COND_REGEXP)
3098 rmatch
= (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '~' &&
3099 cond
->op
->word
[2] == '\0');
3102 arg1
= cond_expand_word (cond
->left
->op
, 0);
3105 arg2
= cond_expand_word (cond
->right
->op
,
3106 (rmatch
&& shell_compatibility_level
> 31) ? 2 : (patmatch
? 1 : 0));
3110 if (echo_command_at_execute
)
3111 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, arg2
);
3113 #if defined (COND_REGEXP)
3116 mflags
= SHMAT_PWARN
;
3117 #if defined (ARRAY_VARS)
3118 mflags
|= SHMAT_SUBEXP
;
3121 result
= sh_regmatch (arg1
, arg2
, mflags
);
3124 #endif /* COND_REGEXP */
3129 result
= binary_test (cond
->op
->word
, arg1
, arg2
, TEST_PATMATCH
|TEST_ARITHEXP
)
3131 : EXECUTION_FAILURE
;
3134 if (arg1
!= nullstr
)
3136 if (arg2
!= nullstr
)
3141 command_error ("execute_cond_node", CMDERR_BADTYPE
, cond
->type
, 0);
3142 jump_to_top_level (DISCARD
);
3143 result
= EXECUTION_FAILURE
;
3147 result
= (result
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
;
3153 execute_cond_command (cond_command
)
3154 COND_COM
*cond_command
;
3156 int retval
, save_line_number
;
3158 retval
= EXECUTION_SUCCESS
;
3159 save_line_number
= line_number
;
3161 this_command_name
= "[[";
3162 line_number
= cond_command
->line
;
3163 /* If we're in a function, update the line number information. */
3164 if (variable_context
&& interactive_shell
)
3165 line_number
-= function_line_number
;
3167 command_string_index
= 0;
3168 print_cond_command (cond_command
);
3170 if (signal_in_progress (DEBUG_TRAP
) == 0)
3172 FREE (the_printed_command_except_trap
);
3173 the_printed_command_except_trap
= savestring (the_printed_command
);
3176 /* Run the debug trap before each conditional command, but do it after we
3177 update the line number information. */
3178 retval
= run_debug_trap ();
3179 #if defined (DEBUGGER)
3180 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3181 skip the command. */
3182 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3184 line_number
= save_line_number
;
3185 return (EXECUTION_SUCCESS
);
3190 debug_print_cond_command (cond_command
);
3193 last_command_exit_value
= retval
= execute_cond_node (cond_command
);
3194 line_number
= save_line_number
;
3197 #endif /* COND_COMMAND */
3207 var
= bind_variable ("_", arg
, 0);
3208 VUNSETATTR (var
, att_exported
);
3211 /* Execute a null command. Fork a subshell if the command uses pipes or is
3212 to be run asynchronously. This handles all the side effects that are
3213 supposed to take place. */
3215 execute_null_command (redirects
, pipe_in
, pipe_out
, async
)
3216 REDIRECT
*redirects
;
3217 int pipe_in
, pipe_out
, async
;
3221 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
3223 /* We have a null command, but we really want a subshell to take
3224 care of it. Just fork, do piping and redirections, and exit. */
3225 if (make_child ((char *)NULL
, async
) == 0)
3227 /* Cancel traps, in trap.c. */
3228 restore_original_signals (); /* XXX */
3230 do_piping (pipe_in
, pipe_out
);
3232 #if defined (COPROCESS_SUPPORT)
3236 subshell_environment
= 0;
3238 subshell_environment
|= SUBSHELL_ASYNC
;
3239 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3240 subshell_environment
|= SUBSHELL_PIPE
;
3242 if (do_redirections (redirects
, RX_ACTIVE
) == 0)
3243 exit (EXECUTION_SUCCESS
);
3245 exit (EXECUTION_FAILURE
);
3249 close_pipes (pipe_in
, pipe_out
);
3250 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3251 unlink_fifo_list ();
3253 return (EXECUTION_SUCCESS
);
3258 /* Even if there aren't any command names, pretend to do the
3259 redirections that are specified. The user expects the side
3260 effects to take place. If the redirections fail, then return
3261 failure. Otherwise, if a command substitution took place while
3262 expanding the command or a redirection, return the value of that
3263 substitution. Otherwise, return EXECUTION_SUCCESS. */
3265 r
= do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
);
3266 cleanup_redirects (redirection_undo_list
);
3267 redirection_undo_list
= (REDIRECT
*)NULL
;
3270 return (EXECUTION_FAILURE
);
3271 else if (last_command_subst_pid
!= NO_PID
)
3272 return (last_command_exit_value
);
3274 return (EXECUTION_SUCCESS
);
3278 /* This is a hack to suppress word splitting for assignment statements
3279 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3281 fix_assignment_words (words
)
3294 for (w
= words
; w
; w
= w
->next
)
3295 if (w
->word
->flags
& W_ASSIGNMENT
)
3299 b
= builtin_address_internal (words
->word
->word
, 0);
3300 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3302 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3303 words
->word
->flags
|= W_ASSNBLTIN
;
3305 w
->word
->flags
|= (W_NOSPLIT
|W_NOGLOB
|W_TILDEEXP
|W_ASSIGNARG
);
3306 #if defined (ARRAY_VARS)
3308 w
->word
->flags
|= W_ASSIGNASSOC
;
3311 #if defined (ARRAY_VARS)
3312 /* Note that we saw an associative array option to a builtin that takes
3313 assignment statements. This is a bit of a kludge. */
3314 else if (w
->word
->word
[0] == '-' && strchr (w
->word
->word
, 'A'))
3318 b
= builtin_address_internal (words
->word
->word
, 0);
3319 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3321 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3322 words
->word
->flags
|= W_ASSNBLTIN
;
3324 if (words
->word
->flags
& W_ASSNBLTIN
)
3330 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3331 to PATHNAME, is a directory. Used by the autocd code below. */
3333 is_dirname (pathname
)
3337 temp
= search_for_command (pathname
);
3338 return (temp
? file_isdir (temp
) : file_isdir (pathname
));
3341 /* The meaty part of all the executions. We have to start hacking the
3342 real execution of commands here. Fork a process, set things up,
3343 execute the command. */
3345 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
3346 SIMPLE_COM
*simple_command
;
3347 int pipe_in
, pipe_out
, async
;
3348 struct fd_bitmap
*fds_to_close
;
3350 WORD_LIST
*words
, *lastword
;
3351 char *command_line
, *lastarg
, *temp
;
3352 int first_word_quoted
, result
, builtin_is_special
, already_forked
, dofork
;
3353 pid_t old_last_async_pid
;
3354 sh_builtin_func_t
*builtin
;
3357 result
= EXECUTION_SUCCESS
;
3358 special_builtin_failed
= builtin_is_special
= 0;
3359 command_line
= (char *)0;
3361 /* If we're in a function, update the line number information. */
3362 if (variable_context
&& interactive_shell
)
3363 line_number
-= function_line_number
;
3365 /* Remember what this command line looks like at invocation. */
3366 command_string_index
= 0;
3367 print_simple_command (simple_command
);
3370 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3372 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3375 FREE (the_printed_command_except_trap
);
3376 the_printed_command_except_trap
= the_printed_command
? savestring (the_printed_command
) : (char *)0;
3379 /* Run the debug trap before each simple command, but do it after we
3380 update the line number information. */
3381 result
= run_debug_trap ();
3382 #if defined (DEBUGGER)
3383 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3384 skip the command. */
3385 if (debugging_mode
&& result
!= EXECUTION_SUCCESS
)
3386 return (EXECUTION_SUCCESS
);
3390 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
) : 0;
3392 last_command_subst_pid
= NO_PID
;
3393 old_last_async_pid
= last_asynchronous_pid
;
3395 already_forked
= dofork
= 0;
3397 /* If we're in a pipeline or run in the background, set DOFORK so we
3398 make the child early, before word expansion. This keeps assignment
3399 statements from affecting the parent shell's environment when they
3401 dofork
= pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
;
3403 /* Something like `%2 &' should restart job 2 in the background, not cause
3404 the shell to fork here. */
3405 if (dofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&&
3406 simple_command
->words
&& simple_command
->words
->word
&&
3407 simple_command
->words
->word
->word
&&
3408 (simple_command
->words
->word
->word
[0] == '%'))
3413 /* Do this now, because execute_disk_command will do it anyway in the
3414 vast majority of cases. */
3415 maybe_make_export_env ();
3417 /* Don't let a DEBUG trap overwrite the command string to be saved with
3418 the process/job associated with this child. */
3419 if (make_child (savestring (the_printed_command_except_trap
), async
) == 0)
3422 simple_command
->flags
|= CMD_NO_FORK
;
3424 subshell_environment
= SUBSHELL_FORK
;
3425 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3426 subshell_environment
|= SUBSHELL_PIPE
;
3428 subshell_environment
|= SUBSHELL_ASYNC
;
3430 /* We need to do this before piping to handle some really
3431 pathological cases where one of the pipe file descriptors
3434 close_fd_bitmap (fds_to_close
);
3436 do_piping (pipe_in
, pipe_out
);
3437 pipe_in
= pipe_out
= NO_PIPE
;
3438 #if defined (COPROCESS_SUPPORT)
3442 last_asynchronous_pid
= old_last_async_pid
;
3446 close_pipes (pipe_in
, pipe_out
);
3447 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3448 unlink_fifo_list ();
3450 command_line
= (char *)NULL
; /* don't free this. */
3451 bind_lastarg ((char *)NULL
);
3456 /* If we are re-running this as the result of executing the `command'
3457 builtin, do not expand the command words a second time. */
3458 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
3460 current_fds_to_close
= fds_to_close
;
3461 fix_assignment_words (simple_command
->words
);
3462 /* Pass the ignore return flag down to command substitutions */
3463 if (simple_command
->flags
& CMD_IGNORE_RETURN
) /* XXX */
3464 comsub_ignore_return
++;
3465 words
= expand_words (simple_command
->words
);
3466 if (simple_command
->flags
& CMD_IGNORE_RETURN
)
3467 comsub_ignore_return
--;
3468 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
3471 words
= copy_word_list (simple_command
->words
);
3473 /* It is possible for WORDS not to have anything left in it.
3474 Perhaps all the words consisted of `$foo', and there was
3475 no variable `$foo'. */
3478 this_command_name
= 0;
3479 result
= execute_null_command (simple_command
->redirects
,
3481 already_forked
? 0 : async
);
3486 bind_lastarg ((char *)NULL
);
3487 set_pipestatus_from_exit (result
);
3492 lastarg
= (char *)NULL
;
3494 begin_unwind_frame ("simple-command");
3496 if (echo_command_at_execute
)
3497 xtrace_print_word_list (words
, 1);
3499 builtin
= (sh_builtin_func_t
*)NULL
;
3500 func
= (SHELL_VAR
*)NULL
;
3501 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
3503 /* Posix.2 says special builtins are found before functions. We
3504 don't set builtin_is_special anywhere other than here, because
3505 this path is followed only when the `command' builtin is *not*
3506 being used, and we don't want to exit the shell if a special
3507 builtin executed with `command builtin' fails. `command' is not
3508 a special builtin. */
3509 if (posixly_correct
)
3511 builtin
= find_special_builtin (words
->word
->word
);
3513 builtin_is_special
= 1;
3516 func
= find_function (words
->word
->word
);
3519 /* In POSIX mode, assignment errors in the temporary environment cause a
3520 non-interactive shell to exit. */
3521 if (builtin_is_special
&& interactive_shell
== 0 && tempenv_assign_error
)
3523 last_command_exit_value
= EXECUTION_FAILURE
;
3524 jump_to_top_level (ERREXIT
);
3527 add_unwind_protect (dispose_words
, words
);
3530 /* Bind the last word in this command to "$_" after execution. */
3531 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
3533 lastarg
= lastword
->word
->word
;
3535 #if defined (JOB_CONTROL)
3536 /* Is this command a job control related thing? */
3537 if (words
->word
->word
[0] == '%' && already_forked
== 0)
3539 this_command_name
= async
? "bg" : "fg";
3540 last_shell_builtin
= this_shell_builtin
;
3541 this_shell_builtin
= builtin_address (this_command_name
);
3542 result
= (*this_shell_builtin
) (words
);
3546 /* One other possiblilty. The user may want to resume an existing job.
3547 If they do, find out whether this word is a candidate for a running
3549 if (job_control
&& already_forked
== 0 && async
== 0 &&
3550 !first_word_quoted
&&
3552 words
->word
->word
[0] &&
3553 !simple_command
->redirects
&&
3554 pipe_in
== NO_PIPE
&&
3555 pipe_out
== NO_PIPE
&&
3556 (temp
= get_string_value ("auto_resume")))
3558 int job
, jflags
, started_status
;
3560 jflags
= JM_STOPPED
|JM_FIRSTMATCH
;
3561 if (STREQ (temp
, "exact"))
3563 else if (STREQ (temp
, "substring"))
3564 jflags
|= JM_SUBSTRING
;
3566 jflags
|= JM_PREFIX
;
3567 job
= get_job_by_name (words
->word
->word
, jflags
);
3570 run_unwind_frame ("simple-command");
3571 this_command_name
= "fg";
3572 last_shell_builtin
= this_shell_builtin
;
3573 this_shell_builtin
= builtin_address ("fg");
3575 started_status
= start_job (job
, 1);
3576 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
3579 #endif /* JOB_CONTROL */
3582 /* Remember the name of this command globally. */
3583 this_command_name
= words
->word
->word
;
3587 /* This command could be a shell builtin or a user-defined function.
3588 We have already found special builtins by this time, so we do not
3589 set builtin_is_special. If this is a function or builtin, and we
3590 have pipes, then fork a subshell in here. Otherwise, just execute
3591 the command directly. */
3592 if (func
== 0 && builtin
== 0)
3593 builtin
= find_shell_builtin (this_command_name
);
3595 last_shell_builtin
= this_shell_builtin
;
3596 this_shell_builtin
= builtin
;
3598 if (builtin
|| func
)
3601 unwind_protect_int (executing_builtin
); /* modified in execute_builtin */
3604 /* reset_terminating_signals (); */ /* XXX */
3605 /* Cancel traps, in trap.c. */
3606 restore_original_signals ();
3610 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
3611 pipe_in
== NO_PIPE
&&
3612 (stdin_redirects (simple_command
->redirects
) == 0))
3613 async_redirect_stdin ();
3614 setup_async_signals ();
3618 execute_subshell_builtin_or_function
3619 (words
, simple_command
->redirects
, builtin
, func
,
3620 pipe_in
, pipe_out
, async
, fds_to_close
,
3621 simple_command
->flags
);
3626 result
= execute_builtin_or_function
3627 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
3628 simple_command
->flags
);
3631 if (result
> EX_SHERRBASE
)
3633 result
= builtin_status (result
);
3634 if (builtin_is_special
)
3635 special_builtin_failed
= 1;
3637 /* In POSIX mode, if there are assignment statements preceding
3638 a special builtin, they persist after the builtin
3640 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
3641 merge_temporary_env ();
3645 if (result
== EX_USAGE
)
3646 result
= EX_BADUSAGE
;
3647 else if (result
> EX_SHERRBASE
)
3648 result
= EXECUTION_FAILURE
;
3651 set_pipestatus_from_exit (result
);
3657 if (autocd
&& interactive
&& words
->word
&& is_dirname (words
->word
->word
))
3659 words
= make_word_list (make_word ("cd"), words
);
3660 xtrace_print_word_list (words
, 0);
3664 if (command_line
== 0)
3665 command_line
= savestring (the_printed_command_except_trap
);
3667 #if defined (PROCESS_SUBSTITUTION)
3668 if ((subshell_environment
& SUBSHELL_COMSUB
) && (simple_command
->flags
& CMD_NO_FORK
) && fifos_pending() > 0)
3669 simple_command
->flags
&= ~CMD_NO_FORK
;
3672 execute_disk_command (words
, simple_command
->redirects
, command_line
,
3673 pipe_in
, pipe_out
, async
, fds_to_close
,
3674 simple_command
->flags
);
3677 bind_lastarg (lastarg
);
3678 FREE (command_line
);
3679 dispose_words (words
);
3680 discard_unwind_frame ("simple-command");
3681 this_command_name
= (char *)NULL
; /* points to freed memory now */
3685 /* Translate the special builtin exit statuses. We don't really need a
3686 function for this; it's a placeholder for future work. */
3688 builtin_status (result
)
3702 r
= EXECUTION_FAILURE
;
3705 r
= EXECUTION_SUCCESS
;
3712 execute_builtin (builtin
, words
, flags
, subshell
)
3713 sh_builtin_func_t
*builtin
;
3715 int flags
, subshell
;
3717 int old_e_flag
, result
, eval_unwind
;
3721 /* XXX -- added 12/11 */
3722 terminate_immediately
++;
3725 old_e_flag
= exit_immediately_on_error
;
3726 /* The eval builtin calls parse_and_execute, which does not know about
3727 the setting of flags, and always calls the execution functions with
3728 flags that will exit the shell on an error if -e is set. If the
3729 eval builtin is being called, and we're supposed to ignore the exit
3730 value of the command, we turn the -e flag off ourselves, then
3731 restore it when the command completes. This is also a problem (as
3732 below) for the command and source/. builtins. */
3733 if (subshell
== 0 && (flags
& CMD_IGNORE_RETURN
) &&
3734 (builtin
== eval_builtin
|| builtin
== command_builtin
|| builtin
== source_builtin
))
3736 begin_unwind_frame ("eval_builtin");
3737 unwind_protect_int (exit_immediately_on_error
);
3738 exit_immediately_on_error
= 0;
3744 /* The temporary environment for a builtin is supposed to apply to
3745 all commands executed by that builtin. Currently, this is a
3746 problem only with the `unset', `source' and `eval' builtins. */
3748 isbltinenv
= (builtin
== source_builtin
|| builtin
== eval_builtin
|| builtin
== unset_builtin
);
3753 begin_unwind_frame ("builtin_env");
3757 push_scope (VC_BLTNENV
, temporary_env
);
3759 add_unwind_protect (pop_scope
, (flags
& CMD_COMMAND_BUILTIN
) ? 0 : "1");
3760 temporary_env
= (HASH_TABLE
*)NULL
;
3764 /* `return' does a longjmp() back to a saved environment in execute_function.
3765 If a variable assignment list preceded the command, and the shell is
3766 running in POSIX mode, we need to merge that into the shell_variables
3767 table, since `return' is a POSIX special builtin. */
3768 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3770 begin_unwind_frame ("return_temp_env");
3771 add_unwind_protect (merge_temporary_env
, (char *)NULL
);
3774 executing_builtin
++;
3775 result
= ((*builtin
) (words
->next
));
3777 /* This shouldn't happen, but in case `return' comes back instead of
3778 longjmp'ing, we need to unwind. */
3779 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3780 discard_unwind_frame ("return_temp_env");
3782 if (subshell
== 0 && isbltinenv
)
3783 run_unwind_frame ("builtin_env");
3787 exit_immediately_on_error
+= old_e_flag
;
3788 discard_unwind_frame ("eval_builtin");
3792 /* XXX -- added 12/11 */
3793 terminate_immediately
--;
3800 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
3804 struct fd_bitmap
*fds_to_close
;
3805 int async
, subshell
;
3807 int return_val
, result
;
3808 COMMAND
*tc
, *fc
, *save_current
;
3809 char *debug_trap
, *error_trap
, *return_trap
;
3810 #if defined (ARRAY_VARS)
3811 SHELL_VAR
*funcname_v
, *nfv
, *bash_source_v
, *bash_lineno_v
;
3812 ARRAY
*funcname_a
, *bash_source_a
, *bash_lineno_a
;
3814 FUNCTION_DEF
*shell_fn
;
3816 static int funcnest
= 0;
3820 #if defined (ARRAY_VARS)
3821 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v
, funcname_a
);
3822 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v
, bash_source_a
);
3823 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v
, bash_lineno_a
);
3826 tc
= (COMMAND
*)copy_command (function_cell (var
));
3827 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
3828 tc
->flags
|= CMD_IGNORE_RETURN
;
3832 begin_unwind_frame ("function_calling");
3833 push_context (var
->name
, subshell
, temporary_env
);
3834 add_unwind_protect (pop_context
, (char *)NULL
);
3835 unwind_protect_int (line_number
);
3836 unwind_protect_int (return_catch_flag
);
3837 unwind_protect_jmp_buf (return_catch
);
3838 add_unwind_protect (dispose_command
, (char *)tc
);
3839 unwind_protect_pointer (this_shell_function
);
3840 unwind_protect_int (loop_level
);
3843 push_context (var
->name
, subshell
, temporary_env
); /* don't unwind-protect for subshells */
3845 temporary_env
= (HASH_TABLE
*)NULL
;
3847 this_shell_function
= var
;
3848 make_funcname_visible (1);
3850 debug_trap
= TRAP_STRING(DEBUG_TRAP
);
3851 error_trap
= TRAP_STRING(ERROR_TRAP
);
3852 return_trap
= TRAP_STRING(RETURN_TRAP
);
3854 /* The order of the unwind protects for debug_trap, error_trap and
3855 return_trap is important here! unwind-protect commands are run
3856 in reverse order of registration. If this causes problems, take
3857 out the xfree unwind-protect calls and live with the small memory leak. */
3859 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3860 if the function has the trace attribute set, it inherits the DEBUG trap */
3861 if (debug_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
3865 debug_trap
= savestring (debug_trap
);
3866 add_unwind_protect (xfree
, debug_trap
);
3867 add_unwind_protect (set_debug_trap
, debug_trap
);
3869 restore_default_signal (DEBUG_TRAP
);
3872 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3873 if (error_trap
&& error_trace_mode
== 0)
3877 error_trap
= savestring (error_trap
);
3878 add_unwind_protect (xfree
, error_trap
);
3879 add_unwind_protect (set_error_trap
, error_trap
);
3881 restore_default_signal (ERROR_TRAP
);
3884 /* Shell functions inherit the RETURN trap if function tracing is on
3885 globally or on individually for this function. */
3887 if (return_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
3889 if (return_trap
&& (signal_in_progress (DEBUG_TRAP
) || ((trace_p (var
) == 0) && function_trace_mode
== 0)))
3894 return_trap
= savestring (return_trap
);
3895 add_unwind_protect (xfree
, return_trap
);
3896 add_unwind_protect (set_return_trap
, return_trap
);
3898 restore_default_signal (RETURN_TRAP
);
3902 #if defined (ARRAY_VARS)
3903 /* This is quite similar to the code in shell.c and elsewhere. */
3904 shell_fn
= find_function_def (this_shell_function
->name
);
3905 sfile
= shell_fn
? shell_fn
->source_file
: "";
3906 array_push (funcname_a
, this_shell_function
->name
);
3908 array_push (bash_source_a
, sfile
);
3909 t
= itos (executing_line_number ());
3910 array_push (bash_lineno_a
, t
);
3914 /* The temporary environment for a function is supposed to apply to
3915 all commands executed within the function body. */
3917 remember_args (words
->next
, 1);
3919 /* Update BASH_ARGV and BASH_ARGC */
3921 push_args (words
->next
);
3923 /* Number of the line on which the function body starts. */
3924 line_number
= function_line_number
= tc
->line
;
3926 #if defined (JOB_CONTROL)
3928 stop_pipeline (async
, (COMMAND
*)NULL
);
3933 return_catch_flag
++;
3934 return_val
= setjmp (return_catch
);
3938 result
= return_catch_value
;
3939 /* Run the RETURN trap in the function's context. */
3940 save_current
= currently_executing_command
;
3942 currently_executing_command
= save_current
;
3946 /* Run the debug trap here so we can trap at the start of a function's
3947 execution rather than the execution of the body's first command. */
3948 showing_function_line
= 1;
3949 save_current
= currently_executing_command
;
3950 result
= run_debug_trap ();
3951 #if defined (DEBUGGER)
3952 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3953 skip the command. */
3954 if (debugging_mode
== 0 || result
== EXECUTION_SUCCESS
)
3956 showing_function_line
= 0;
3957 currently_executing_command
= save_current
;
3958 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
3960 /* Run the RETURN trap in the function's context */
3961 save_current
= currently_executing_command
;
3963 currently_executing_command
= save_current
;
3966 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
3968 save_current
= currently_executing_command
;
3970 currently_executing_command
= save_current
;
3972 showing_function_line
= 0;
3975 /* Restore BASH_ARGC and BASH_ARGV */
3980 run_unwind_frame ("function_calling");
3983 #if defined (ARRAY_VARS)
3984 /* These two variables cannot be unset, and cannot be affected by the
3986 array_pop (bash_source_a
);
3987 array_pop (bash_lineno_a
);
3989 /* FUNCNAME can be unset, and so can potentially be changed by the
3991 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv
, funcname_a
);
3992 if (nfv
== funcname_v
)
3993 array_pop (funcname_a
);
3996 if (variable_context
== 0 || this_shell_function
== 0)
3997 make_funcname_visible (0);
4002 /* A convenience routine for use by other parts of the shell to execute
4003 a particular shell function. */
4005 execute_shell_function (var
, words
)
4010 struct fd_bitmap
*bitmap
;
4012 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
4013 begin_unwind_frame ("execute-shell-function");
4014 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
4016 ret
= execute_function (var
, words
, 0, bitmap
, 0, 0);
4018 dispose_fd_bitmap (bitmap
);
4019 discard_unwind_frame ("execute-shell-function");
4024 /* Execute a shell builtin or function in a subshell environment. This
4025 routine does not return; it only calls exit(). If BUILTIN is non-null,
4026 it points to a function to call to execute a shell builtin; otherwise
4027 VAR points at the body of a function to execute. WORDS is the arguments
4028 to the command, REDIRECTS specifies redirections to perform before the
4029 command is executed. */
4031 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
4032 pipe_in
, pipe_out
, async
, fds_to_close
,
4035 REDIRECT
*redirects
;
4036 sh_builtin_func_t
*builtin
;
4038 int pipe_in
, pipe_out
, async
;
4039 struct fd_bitmap
*fds_to_close
;
4042 int result
, r
, funcvalue
;
4043 #if defined (JOB_CONTROL)
4046 jobs_hack
= (builtin
== jobs_builtin
) &&
4047 ((subshell_environment
& SUBSHELL_ASYNC
) == 0 || pipe_out
!= NO_PIPE
);
4050 /* A subshell is neither a login shell nor interactive. */
4051 login_shell
= interactive
= 0;
4054 subshell_environment
|= SUBSHELL_ASYNC
;
4055 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4056 subshell_environment
|= SUBSHELL_PIPE
;
4058 maybe_make_export_env (); /* XXX - is this needed? */
4060 #if defined (JOB_CONTROL)
4061 /* Eradicate all traces of job control after we fork the subshell, so
4062 all jobs begun by this subshell are in the same process group as
4063 the shell itself. */
4065 /* Allow the output of `jobs' to be piped. */
4067 kill_current_pipeline ();
4069 without_job_control ();
4071 set_sigchld_handler ();
4072 #endif /* JOB_CONTROL */
4074 set_sigint_handler ();
4077 close_fd_bitmap (fds_to_close
);
4079 do_piping (pipe_in
, pipe_out
);
4081 if (do_redirections (redirects
, RX_ACTIVE
) != 0)
4082 exit (EXECUTION_FAILURE
);
4086 /* Give builtins a place to jump back to on failure,
4087 so we don't go back up to main(). */
4088 result
= setjmp (top_level
);
4090 /* Give the return builtin a place to jump to when executed in a subshell
4093 if (return_catch_flag
&& builtin
== return_builtin
)
4094 funcvalue
= setjmp (return_catch
);
4096 if (result
== EXITPROG
)
4097 exit (last_command_exit_value
);
4099 exit (EXECUTION_FAILURE
);
4101 exit (return_catch_value
);
4104 r
= execute_builtin (builtin
, words
, flags
, 1);
4113 r
= execute_function (var
, words
, flags
, fds_to_close
, async
, 1);
4119 /* Execute a builtin or function in the current shell context. If BUILTIN
4120 is non-null, it is the builtin command to execute, otherwise VAR points
4121 to the body of a function. WORDS are the command's arguments, REDIRECTS
4122 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4123 file descriptors to close.
4125 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4126 not undone before this function returns. */
4128 execute_builtin_or_function (words
, builtin
, var
, redirects
,
4129 fds_to_close
, flags
)
4131 sh_builtin_func_t
*builtin
;
4133 REDIRECT
*redirects
;
4134 struct fd_bitmap
*fds_to_close
;
4138 REDIRECT
*saved_undo_list
;
4139 sh_builtin_func_t
*saved_this_shell_builtin
;
4141 if (do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
4143 cleanup_redirects (redirection_undo_list
);
4144 redirection_undo_list
= (REDIRECT
*)NULL
;
4145 dispose_exec_redirects ();
4146 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
4149 saved_this_shell_builtin
= this_shell_builtin
;
4150 saved_undo_list
= redirection_undo_list
;
4152 /* Calling the "exec" builtin changes redirections forever. */
4153 if (builtin
== exec_builtin
)
4155 dispose_redirects (saved_undo_list
);
4156 saved_undo_list
= exec_redirection_undo_list
;
4157 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
4160 dispose_exec_redirects ();
4162 if (saved_undo_list
)
4164 begin_unwind_frame ("saved redirects");
4165 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
4168 redirection_undo_list
= (REDIRECT
*)NULL
;
4171 result
= execute_builtin (builtin
, words
, flags
, 0);
4173 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
4175 /* We do this before undoing the effects of any redirections. */
4178 if (ferror (stdout
))
4181 /* If we are executing the `command' builtin, but this_shell_builtin is
4182 set to `exec_builtin', we know that we have something like
4183 `command exec [redirection]', since otherwise `exec' would have
4184 overwritten the shell and we wouldn't get here. In this case, we
4185 want to behave as if the `command' builtin had not been specified
4186 and preserve the redirections. */
4187 if (builtin
== command_builtin
&& this_shell_builtin
== exec_builtin
)
4189 if (saved_undo_list
)
4190 dispose_redirects (saved_undo_list
);
4191 redirection_undo_list
= exec_redirection_undo_list
;
4192 saved_undo_list
= exec_redirection_undo_list
= (REDIRECT
*)NULL
;
4193 discard_unwind_frame ("saved_redirects");
4196 if (saved_undo_list
)
4198 redirection_undo_list
= saved_undo_list
;
4199 discard_unwind_frame ("saved redirects");
4202 if (redirection_undo_list
)
4204 cleanup_redirects (redirection_undo_list
);
4205 redirection_undo_list
= (REDIRECT
*)NULL
;
4212 setup_async_signals ()
4214 #if defined (__BEOS__)
4215 set_signal_handler (SIGHUP
, SIG_IGN
); /* they want csh-like behavior */
4218 #if defined (JOB_CONTROL)
4219 if (job_control
== 0)
4222 set_signal_handler (SIGINT
, SIG_IGN
);
4223 set_signal_ignored (SIGINT
);
4224 set_signal_handler (SIGQUIT
, SIG_IGN
);
4225 set_signal_ignored (SIGQUIT
);
4229 /* Execute a simple command that is hopefully defined in a disk file
4234 3) look up the command
4237 6) If the execve failed, see if the file has executable mode set.
4238 If so, and it isn't a directory, then execute its contents as
4241 Note that the filename hashing stuff has to take place up here,
4242 in the parent. This is probably why the Bourne style shells
4243 don't handle it, since that would require them to go through
4244 this gnarly hair, for no good reason.
4246 NOTE: callers expect this to fork or exit(). */
4248 /* Name of a shell function to call when a command name is not found. */
4249 #ifndef NOTFOUND_HOOK
4250 # define NOTFOUND_HOOK "command_not_found_handle"
4254 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
4255 async
, fds_to_close
, cmdflags
)
4257 REDIRECT
*redirects
;
4259 int pipe_in
, pipe_out
, async
;
4260 struct fd_bitmap
*fds_to_close
;
4263 char *pathname
, *command
, **args
;
4269 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
4270 pathname
= words
->word
->word
;
4272 #if defined (RESTRICTED_SHELL)
4273 command
= (char *)NULL
;
4274 if (restricted
&& xstrchr (pathname
, '/'))
4276 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4278 last_command_exit_value
= EXECUTION_FAILURE
;
4280 /* If we're not going to fork below, we must already be in a child
4281 process or a context in which it's safe to call exit(2). */
4282 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
4283 exit (last_command_exit_value
);
4287 #endif /* RESTRICTED_SHELL */
4289 command
= search_for_command (pathname
);
4293 maybe_make_export_env ();
4294 put_command_name_into_env (command
);
4297 /* We have to make the child before we check for the non-existence
4298 of COMMAND, since we want the error messages to be redirected. */
4299 /* If we can get away without forking and there are no pipes to deal with,
4300 don't bother to fork, just directly exec the command. */
4301 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
4304 pid
= make_child (savestring (command_line
), async
);
4308 int old_interactive
;
4311 /* This has been disabled for the time being. */
4312 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4313 if (posixly_correct
== 0)
4314 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags
);
4318 /* Cancel traps, in trap.c. */
4319 restore_original_signals ();
4321 /* restore_original_signals may have undone the work done
4322 by make_child to ensure that SIGINT and SIGQUIT are ignored
4323 in asynchronous children. */
4326 if ((cmdflags
& CMD_STDIN_REDIR
) &&
4327 pipe_in
== NO_PIPE
&&
4328 (stdin_redirects (redirects
) == 0))
4329 async_redirect_stdin ();
4330 setup_async_signals ();
4333 /* This functionality is now provided by close-on-exec of the
4334 file descriptors manipulated by redirection and piping.
4335 Some file descriptors still need to be closed in all children
4336 because of the way bash does pipes; fds_to_close is a
4337 bitmap of all such file descriptors. */
4339 close_fd_bitmap (fds_to_close
);
4341 do_piping (pipe_in
, pipe_out
);
4343 old_interactive
= interactive
;
4347 subshell_environment
= SUBSHELL_FORK
;
4349 if (redirects
&& (do_redirections (redirects
, RX_ACTIVE
) != 0))
4351 #if defined (PROCESS_SUBSTITUTION)
4352 /* Try to remove named pipes that may have been created as the
4353 result of redirections. */
4354 unlink_fifo_list ();
4355 #endif /* PROCESS_SUBSTITUTION */
4356 exit (EXECUTION_FAILURE
);
4360 interactive
= old_interactive
;
4364 hookf
= find_function (NOTFOUND_HOOK
);
4367 internal_error (_("%s: command not found"), pathname
);
4368 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
4371 wl
= make_word_list (make_word (NOTFOUND_HOOK
), words
);
4372 exit (execute_shell_function (hookf
, wl
));
4375 /* Execve expects the command name to be in args[0]. So we
4376 leave it there, in the same format that the user used to
4378 args
= strvec_from_word_list (words
, 0, 0, (int *)NULL
);
4379 exit (shell_execve (command
, args
, export_env
));
4384 /* Make sure that the pipes are closed in the parent. */
4385 close_pipes (pipe_in
, pipe_out
);
4386 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4387 unlink_fifo_list ();
4393 /* CPP defines to decide whether a particular index into the #! line
4394 corresponds to a valid interpreter name or argument character, or
4395 whitespace. The MSDOS define is to allow \r to be treated the same
4398 #if !defined (MSDOS)
4399 # define STRINGCHAR(ind) \
4400 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4401 # define WHITECHAR(ind) \
4402 (ind < sample_len && whitespace (sample[ind]))
4404 # define STRINGCHAR(ind) \
4405 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4406 # define WHITECHAR(ind) \
4407 (ind < sample_len && whitespace (sample[ind]))
4411 getinterp (sample
, sample_len
, endp
)
4413 int sample_len
, *endp
;
4419 /* Find the name of the interpreter to exec. */
4420 for (i
= 2; i
< sample_len
&& whitespace (sample
[i
]); i
++)
4423 for (start
= i
; STRINGCHAR(i
); i
++)
4426 execname
= substring (sample
, start
, i
);
4433 #if !defined (HAVE_HASH_BANG_EXEC)
4434 /* If the operating system on which we're running does not handle
4435 the #! executable format, then help out. SAMPLE is the text read
4436 from the file, SAMPLE_LEN characters. COMMAND is the name of
4437 the script; it and ARGS, the arguments given by the user, will
4438 become arguments to the specified interpreter. ENV is the environment
4439 to pass to the interpreter.
4441 The word immediately following the #! is the interpreter to execute.
4442 A single argument to the interpreter is allowed. */
4445 execute_shell_script (sample
, sample_len
, command
, args
, env
)
4451 char *execname
, *firstarg
;
4452 int i
, start
, size_increment
, larry
;
4454 /* Find the name of the interpreter to exec. */
4455 execname
= getinterp (sample
, sample_len
, &i
);
4458 /* Now the argument, if any. */
4459 for (firstarg
= (char *)NULL
, start
= i
; WHITECHAR(i
); i
++)
4462 /* If there is more text on the line, then it is an argument for the
4467 for (start
= i
; STRINGCHAR(i
); i
++)
4469 firstarg
= substring ((char *)sample
, start
, i
);
4473 larry
= strvec_len (args
) + size_increment
;
4474 args
= strvec_resize (args
, larry
+ 1);
4476 for (i
= larry
- 1; i
; i
--)
4477 args
[i
] = args
[i
- size_increment
];
4488 args
[larry
] = (char *)NULL
;
4490 return (shell_execve (execname
, args
, env
));
4495 #endif /* !HAVE_HASH_BANG_EXEC */
4498 initialize_subshell ()
4501 /* Forget about any aliases that we knew of. We are in a subshell. */
4502 delete_all_aliases ();
4505 #if defined (HISTORY)
4506 /* Forget about the history lines we have read. This is a non-interactive
4508 history_lines_this_session
= 0;
4511 #if defined (JOB_CONTROL)
4512 /* Forget about the way job control was working. We are in a subshell. */
4513 without_job_control ();
4514 set_sigchld_handler ();
4516 #endif /* JOB_CONTROL */
4518 /* Reset the values of the shell flags and options. */
4519 reset_shell_flags ();
4520 reset_shell_options ();
4521 reset_shopt_options ();
4523 /* Zero out builtin_env, since this could be a shell script run from a
4524 sourced file with a temporary environment supplied to the `source/.'
4525 builtin. Such variables are not supposed to be exported (empirical
4526 testing with sh and ksh). Just throw it away; don't worry about a
4528 if (vc_isbltnenv (shell_variables
))
4529 shell_variables
= shell_variables
->down
;
4531 clear_unwind_protect_list (0);
4532 /* XXX -- are there other things we should be resetting here? */
4533 parse_and_execute_level
= 0; /* nothing left to restore it */
4535 /* We're no longer inside a shell function. */
4536 variable_context
= return_catch_flag
= 0;
4538 executing_list
= 0; /* XXX */
4540 /* If we're not interactive, close the file descriptor from which we're
4541 reading the current shell script. */
4542 if (interactive_shell
== 0)
4543 unset_bash_input (0);
4546 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4547 # define SETOSTYPE(x) __setostype(x)
4549 # define SETOSTYPE(x)
4552 #define READ_SAMPLE_BUF(file, buf, len) \
4555 fd = open(file, O_RDONLY); \
4558 len = read (fd, buf, 80); \
4566 /* Call execve (), handling interpreting shell scripts, and handling
4569 shell_execve (command
, args
, env
)
4577 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
4578 execve (command
, args
, env
);
4579 i
= errno
; /* error from execve() */
4583 /* If we get to this point, then start checking out the file.
4584 Maybe it is something we can hack ourselves. */
4587 if (file_isdir (command
))
4588 internal_error (_("%s: is a directory"), command
);
4589 else if (executable_file (command
) == 0)
4592 file_error (command
);
4594 /* errors not involving the path argument to execve. */
4595 else if (i
== E2BIG
|| i
== ENOMEM
)
4598 file_error (command
);
4602 /* The file has the execute bits set, but the kernel refuses to
4603 run it for some reason. See why. */
4604 #if defined (HAVE_HASH_BANG_EXEC)
4605 READ_SAMPLE_BUF (command
, sample
, sample_len
);
4606 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
4611 interp
= getinterp (sample
, sample_len
, (int *)NULL
);
4612 ilen
= strlen (interp
);
4614 if (interp
[ilen
- 1] == '\r')
4616 interp
= xrealloc (interp
, ilen
+ 2);
4617 interp
[ilen
- 1] = '^';
4619 interp
[ilen
+ 1] = '\0';
4621 sys_error (_("%s: %s: bad interpreter"), command
, interp
? interp
: "");
4627 file_error (command
);
4629 return ((i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
); /* XXX Posix.2 says that exit status is 126 */
4632 /* This file is executable.
4633 If it begins with #!, then help out people with losing operating
4634 systems. Otherwise, check to see if it is a binary file by seeing
4635 if the contents of the first line (or up to 80 characters) are in the
4636 ASCII set. If it's a text file, execute the contents as shell commands,
4637 otherwise return 126 (EX_BINARY_FILE). */
4638 READ_SAMPLE_BUF (command
, sample
, sample_len
);
4640 if (sample_len
== 0)
4641 return (EXECUTION_SUCCESS
);
4643 /* Is this supposed to be an executable script?
4644 If so, the format of the line is "#! interpreter [argument]".
4645 A single argument is allowed. The BSD kernel restricts
4646 the length of the entire line to 32 characters (32 bytes
4647 being the size of the BSD exec header), but we allow 80
4651 #if !defined (HAVE_HASH_BANG_EXEC)
4652 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
4653 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
4656 if (check_binary_file (sample
, sample_len
))
4658 internal_error (_("%s: cannot execute binary file"), command
);
4659 return (EX_BINARY_FILE
);
4663 /* We have committed to attempting to execute the contents of this file
4664 as shell commands. */
4666 initialize_subshell ();
4668 set_sigint_handler ();
4670 /* Insert the name of this shell into the argument list. */
4671 larray
= strvec_len (args
) + 1;
4672 args
= strvec_resize (args
, larray
+ 1);
4674 for (i
= larray
- 1; i
; i
--)
4675 args
[i
] = args
[i
- 1];
4677 args
[0] = shell_name
;
4679 args
[larray
] = (char *)NULL
;
4681 if (args
[0][0] == '-')
4684 #if defined (RESTRICTED_SHELL)
4686 change_flag ('r', FLAG_OFF
);
4691 /* Can't free subshell_argv[0]; that is shell_name. */
4692 for (i
= 1; i
< subshell_argc
; i
++)
4693 free (subshell_argv
[i
]);
4694 free (subshell_argv
);
4697 dispose_command (currently_executing_command
); /* XXX */
4698 currently_executing_command
= (COMMAND
*)NULL
;
4700 subshell_argc
= larray
;
4701 subshell_argv
= args
;
4702 subshell_envp
= env
;
4704 unbind_args (); /* remove the positional parameters */
4706 longjmp (subshell_top_level
, 1);
4711 execute_intern_function (name
, function
)
4717 if (check_identifier (name
, posixly_correct
) == 0)
4719 if (posixly_correct
&& interactive_shell
== 0)
4721 last_command_exit_value
= EX_BADUSAGE
;
4722 jump_to_top_level (ERREXIT
);
4724 return (EXECUTION_FAILURE
);
4727 var
= find_function (name
->word
);
4728 if (var
&& (readonly_p (var
) || noassign_p (var
)))
4730 if (readonly_p (var
))
4731 internal_error (_("%s: readonly function"), var
->name
);
4732 return (EXECUTION_FAILURE
);
4735 bind_function (name
->word
, function
);
4736 return (EXECUTION_SUCCESS
);
4739 #if defined (INCLUDE_UNUSED)
4740 #if defined (PROCESS_SUBSTITUTION)
4744 register int i
, fd_table_size
;
4746 fd_table_size
= getdtablesize ();
4747 if (fd_table_size
> 256) /* clamp to a reasonable value */
4748 fd_table_size
= 256;
4750 for (i
= 3; i
< fd_table_size
; i
++)
4753 #endif /* PROCESS_SUBSTITUTION */
4757 close_pipes (in
, out
)
4767 dup_error (oldd
, newd
)
4770 sys_error (_("cannot duplicate fd %d to fd %d"), oldd
, newd
);
4773 /* Redirect input and output to be from and to the specified pipes.
4774 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4776 do_piping (pipe_in
, pipe_out
)
4777 int pipe_in
, pipe_out
;
4779 if (pipe_in
!= NO_PIPE
)
4781 if (dup2 (pipe_in
, 0) < 0)
4782 dup_error (pipe_in
, 0);
4786 if (pipe_out
!= NO_PIPE
)
4788 if (pipe_out
!= REDIRECT_BOTH
)
4790 if (dup2 (pipe_out
, 1) < 0)
4791 dup_error (pipe_out
, 1);
4792 if (pipe_out
== 0 || pipe_out
> 1)
4797 if (dup2 (1, 2) < 0)