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>
60 #define NEED_FPURGE_DECL
67 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
72 #include "execute_cmd.h"
79 #if defined (COND_COMMAND)
83 #include "builtins/common.h"
84 #include "builtins/builtext.h" /* list of builtins */
86 #include <glob/strmatch.h>
87 #include <tilde/tilde.h>
89 #if defined (BUFFERED_INPUT)
98 # include "bashhist.h"
101 extern int posixly_correct
;
102 extern int expand_aliases
;
104 extern int breaking
, continuing
, loop_level
;
105 extern int parse_and_execute_level
, running_trap
, sourcelevel
;
106 extern int command_string_index
, line_number
;
107 extern int dot_found_in_search
;
108 extern int already_making_children
;
109 extern int tempenv_assign_error
;
110 extern char *the_printed_command
, *shell_name
;
111 extern pid_t last_command_subst_pid
;
112 extern sh_builtin_func_t
*last_shell_builtin
, *this_shell_builtin
;
113 extern char **subshell_argv
, **subshell_envp
;
114 extern int subshell_argc
;
116 extern char *glob_argv_flags
;
119 extern int close
__P((int));
121 /* Static functions defined and used in this file. */
122 static void close_pipes
__P((int, int));
123 static void do_piping
__P((int, int));
124 static void bind_lastarg
__P((char *));
125 static int shell_control_structure
__P((enum command_type
));
126 static void cleanup_redirects
__P((REDIRECT
*));
128 #if defined (JOB_CONTROL)
129 static int restore_signal_mask
__P((sigset_t
*));
132 static void async_redirect_stdin
__P((void));
134 static int builtin_status
__P((int));
136 static int execute_for_command
__P((FOR_COM
*));
137 #if defined (SELECT_COMMAND)
138 static int print_index_and_element
__P((int, int, WORD_LIST
*));
139 static void indent
__P((int, int));
140 static void print_select_list
__P((WORD_LIST
*, int, int, int));
141 static char *select_query
__P((WORD_LIST
*, int, char *, int));
142 static int execute_select_command
__P((SELECT_COM
*));
144 #if defined (DPAREN_ARITHMETIC)
145 static int execute_arith_command
__P((ARITH_COM
*));
147 #if defined (COND_COMMAND)
148 static int execute_cond_node
__P((COND_COM
*));
149 static int execute_cond_command
__P((COND_COM
*));
151 #if defined (COMMAND_TIMING)
152 static int mkfmt
__P((char *, int, int, time_t, int));
153 static void print_formatted_time
__P((FILE *, char *,
154 time_t, int, time_t, int,
156 static int time_command
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
158 #if defined (ARITH_FOR_COMMAND)
159 static intmax_t eval_arith_for_expr
__P((WORD_LIST
*, int *));
160 static int execute_arith_for_command
__P((ARITH_FOR_COM
*));
162 static int execute_case_command
__P((CASE_COM
*));
163 static int execute_while_command
__P((WHILE_COM
*));
164 static int execute_until_command
__P((WHILE_COM
*));
165 static int execute_while_or_until
__P((WHILE_COM
*, int));
166 static int execute_if_command
__P((IF_COM
*));
167 static int execute_null_command
__P((REDIRECT
*, int, int, int));
168 static void fix_assignment_words
__P((WORD_LIST
*));
169 static int execute_simple_command
__P((SIMPLE_COM
*, int, int, int, struct fd_bitmap
*));
170 static int execute_builtin
__P((sh_builtin_func_t
*, WORD_LIST
*, int, int));
171 static int execute_function
__P((SHELL_VAR
*, WORD_LIST
*, int, struct fd_bitmap
*, int, int));
172 static int execute_builtin_or_function
__P((WORD_LIST
*, sh_builtin_func_t
*,
174 REDIRECT
*, struct fd_bitmap
*, int));
175 static void execute_subshell_builtin_or_function
__P((WORD_LIST
*, REDIRECT
*,
181 static void execute_disk_command
__P((WORD_LIST
*, REDIRECT
*, char *,
182 int, int, int, struct fd_bitmap
*, int));
184 static char *getinterp
__P((char *, int, int *));
185 static void initialize_subshell
__P((void));
186 static int execute_in_subshell
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
187 #if defined (COPROCESS_SUPPORT)
188 static int execute_coproc
__P((COMMAND
*, int, int, struct fd_bitmap
*));
191 static int execute_pipeline
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
193 static int execute_connection
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
195 static int execute_intern_function
__P((WORD_DESC
*, COMMAND
*));
197 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
198 so that reader_loop can set it to zero before executing a command. */
201 /* The name of the command that is currently being executed.
202 `test' needs this, for example. */
203 char *this_command_name
;
205 /* The printed representation of the currently-executing command (same as
206 the_printed_command), except when a trap is being executed. Useful for
207 a debugger to know where exactly the program is currently executing. */
208 char *the_printed_command_except_trap
;
210 /* For catching RETURN in a function. */
211 int return_catch_flag
;
212 int return_catch_value
;
213 procenv_t return_catch
;
215 /* The value returned by the last synchronous command. */
216 int last_command_exit_value
;
218 /* Whether or not the last command (corresponding to last_command_exit_value)
219 was terminated by a signal, and, if so, which one. */
220 int last_command_exit_signal
;
222 /* The list of redirections to perform which will undo the redirections
223 that I made in the shell. */
224 REDIRECT
*redirection_undo_list
= (REDIRECT
*)NULL
;
226 /* The list of redirections to perform which will undo the internal
227 redirections performed by the `exec' builtin. These are redirections
228 that must be undone even when exec discards redirection_undo_list. */
229 REDIRECT
*exec_redirection_undo_list
= (REDIRECT
*)NULL
;
231 /* When greater than zero, value is the `level' of builtins we are
232 currently executing (e.g. `eval echo a' would have it set to 2). */
233 int executing_builtin
= 0;
235 /* Non-zero if we are executing a command list (a;b;c, etc.) */
236 int executing_list
= 0;
238 /* Non-zero if failing commands in a command substitution should not exit the
239 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
240 commands run in command substitutions by parse_and_execute. */
241 int comsub_ignore_return
= 0;
243 /* Non-zero if we have just forked and are currently running in a subshell
245 int subshell_environment
;
247 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
248 int subshell_level
= 0;
250 /* Currently-executing shell function. */
251 SHELL_VAR
*this_shell_function
;
253 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
254 int match_ignore_case
= 0;
256 struct stat SB
; /* used for debugging */
258 static int special_builtin_failed
;
260 static COMMAND
*currently_executing_command
;
262 /* The line number that the currently executing function starts on. */
263 static int function_line_number
;
265 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
266 number containing the function name. Used by executing_line_number to
267 report the correct line number. Kind of a hack. */
268 static int showing_function_line
;
270 static int line_number_for_err_trap
;
272 /* A sort of function nesting level counter */
273 static int funcnest
= 0;
274 int funcnest_max
= 0; /* XXX - for bash-4.2 */
276 struct fd_bitmap
*current_fds_to_close
= (struct fd_bitmap
*)NULL
;
278 #define FD_BITMAP_DEFAULT_SIZE 32
280 /* Functions to allocate and deallocate the structures used to pass
281 information from the shell to its children about file descriptors
287 struct fd_bitmap
*ret
;
289 ret
= (struct fd_bitmap
*)xmalloc (sizeof (struct fd_bitmap
));
295 ret
->bitmap
= (char *)xmalloc (size
);
296 memset (ret
->bitmap
, '\0', size
);
299 ret
->bitmap
= (char *)NULL
;
304 dispose_fd_bitmap (fdbp
)
305 struct fd_bitmap
*fdbp
;
312 close_fd_bitmap (fdbp
)
313 struct fd_bitmap
*fdbp
;
319 for (i
= 0; i
< fdbp
->size
; i
++)
328 /* Return the line number of the currently executing command. */
330 executing_line_number ()
332 if (executing
&& showing_function_line
== 0 &&
333 (variable_context
== 0 || interactive_shell
== 0) &&
334 currently_executing_command
)
336 #if defined (COND_COMMAND)
337 if (currently_executing_command
->type
== cm_cond
)
338 return currently_executing_command
->value
.Cond
->line
;
340 #if defined (DPAREN_ARITHMETIC)
341 else if (currently_executing_command
->type
== cm_arith
)
342 return currently_executing_command
->value
.Arith
->line
;
344 #if defined (ARITH_FOR_COMMAND)
345 else if (currently_executing_command
->type
== cm_arith_for
)
346 return currently_executing_command
->value
.ArithFor
->line
;
355 /* Execute the command passed in COMMAND. COMMAND is exactly what
356 read_command () places into GLOBAL_COMMAND. See "command.h" for the
357 details of the command structure.
359 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
360 return values. Executing a command with nothing in it returns
361 EXECUTION_SUCCESS. */
363 execute_command (command
)
366 struct fd_bitmap
*bitmap
;
369 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
370 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
371 begin_unwind_frame ("execute-command");
372 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
374 /* Just do the command, but not asynchronously. */
375 result
= execute_command_internal (command
, 0, NO_PIPE
, NO_PIPE
, bitmap
);
377 dispose_fd_bitmap (bitmap
);
378 discard_unwind_frame ("execute-command");
380 #if defined (PROCESS_SUBSTITUTION)
381 /* don't unlink fifos if we're in a shell function; wait until the function
383 if (variable_context
== 0)
385 #endif /* PROCESS_SUBSTITUTION */
391 /* Return 1 if TYPE is a shell control structure type. */
393 shell_control_structure (type
)
394 enum command_type type
;
398 #if defined (ARITH_FOR_COMMAND)
401 #if defined (SELECT_COMMAND)
404 #if defined (DPAREN_ARITHMETIC)
407 #if defined (COND_COMMAND)
416 case cm_function_def
:
424 /* A function to use to unwind_protect the redirection undo list
427 cleanup_redirects (list
)
430 do_redirections (list
, RX_ACTIVE
);
431 dispose_redirects (list
);
435 /* Function to unwind_protect the redirections for functions and builtins. */
437 cleanup_func_redirects (list
)
440 do_redirections (list
, RX_ACTIVE
);
445 dispose_exec_redirects ()
447 if (exec_redirection_undo_list
)
449 dispose_redirects (exec_redirection_undo_list
);
450 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
454 #if defined (JOB_CONTROL)
455 /* A function to restore the signal mask to its proper value when the shell
456 is interrupted or errors occur while creating a pipeline. */
458 restore_signal_mask (set
)
461 return (sigprocmask (SIG_SETMASK
, set
, (sigset_t
*)NULL
));
463 #endif /* JOB_CONTROL */
466 /* A debugging function that can be called from gdb, for instance. */
471 int f
, fd_table_size
;
473 fd_table_size
= getdtablesize ();
475 fprintf (stderr
, "pid %ld open files:", (long)getpid ());
476 for (i
= 3; i
< fd_table_size
; i
++)
478 if ((f
= fcntl (i
, F_GETFD
, 0)) != -1)
479 fprintf (stderr
, " %d (%s)", i
, f
? "close" : "open");
481 fprintf (stderr
, "\n");
486 async_redirect_stdin ()
490 fd
= open ("/dev/null", O_RDONLY
);
497 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno
));
500 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
502 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
503 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
504 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
505 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
506 from and where it goes. They can have the value of NO_PIPE, which means
508 FDS_TO_CLOSE is a list of file descriptors to close once the child has
509 been forked. This list often contains the unusable sides of pipes, etc.
511 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
512 return values. Executing a command with nothing in it returns
513 EXECUTION_SUCCESS. */
515 execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
,
519 int pipe_in
, pipe_out
;
520 struct fd_bitmap
*fds_to_close
;
522 int exec_result
, user_subshell
, invert
, ignore_return
, was_error_trap
;
523 REDIRECT
*my_undo_list
, *exec_undo_list
;
524 volatile int last_pid
;
525 volatile int save_line_number
;
528 if (command
== 0 || breaking
|| continuing
|| read_but_dont_execute
)
529 return (EXECUTION_SUCCESS
);
531 if (breaking
|| continuing
)
532 return (last_command_exit_value
);
533 if (command
== 0 || read_but_dont_execute
)
534 return (EXECUTION_SUCCESS
);
538 run_pending_traps ();
541 if (running_trap
== 0)
543 currently_executing_command
= command
;
545 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
547 /* If we're inverting the return value and `set -e' has been executed,
548 we don't want a failing command to inadvertently cause the shell
550 if (exit_immediately_on_error
&& invert
) /* XXX */
551 command
->flags
|= CMD_IGNORE_RETURN
; /* XXX */
553 exec_result
= EXECUTION_SUCCESS
;
555 /* If a command was being explicitly run in a subshell, or if it is
556 a shell control-structure, and it has a pipe, then we do the command
558 if (command
->type
== cm_subshell
&& (command
->flags
& CMD_NO_FORK
))
559 return (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
561 #if defined (COPROCESS_SUPPORT)
562 if (command
->type
== cm_coproc
)
563 return (execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
));
566 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
568 if (command
->type
== cm_subshell
||
569 (command
->flags
& (CMD_WANT_SUBSHELL
|CMD_FORCE_SUBSHELL
)) ||
570 (shell_control_structure (command
->type
) &&
571 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
|| asynchronous
)))
575 /* Fork a subshell, turn off the subshell bit, turn off job
576 control and call execute_command () on the command again. */
577 line_number_for_err_trap
= line_number
;
578 paren_pid
= make_child (savestring (make_command_string (command
)),
581 exit (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
585 close_pipes (pipe_in
, pipe_out
);
587 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
590 /* If we are part of a pipeline, and not the end of the pipeline,
591 then we should simply return and let the last command in the
592 pipe be waited for. If we are not in a pipeline, or are the
593 last command in the pipeline, then we wait for the subshell
594 and return its exit status as usual. */
595 if (pipe_out
!= NO_PIPE
)
596 return (EXECUTION_SUCCESS
);
598 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
600 if (asynchronous
== 0)
602 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
603 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
604 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
606 last_command_exit_value
= wait_for (paren_pid
);
608 /* If we have to, invert the return value. */
610 exec_result
= ((last_command_exit_value
== EXECUTION_SUCCESS
)
612 : EXECUTION_SUCCESS
);
614 exec_result
= last_command_exit_value
;
616 if (user_subshell
&& was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
618 last_command_exit_value
= exec_result
;
619 save_line_number
= line_number
;
620 line_number
= line_number_for_err_trap
;
622 line_number
= save_line_number
;
625 if (user_subshell
&& ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
627 last_command_exit_value
= exec_result
;
628 run_pending_traps ();
629 jump_to_top_level (ERREXIT
);
632 return (last_command_exit_value
= exec_result
);
636 DESCRIBE_PID (paren_pid
);
638 run_pending_traps ();
640 return (EXECUTION_SUCCESS
);
645 #if defined (COMMAND_TIMING)
646 if (command
->flags
& CMD_TIME_PIPELINE
)
650 command
->flags
|= CMD_FORCE_SUBSHELL
;
651 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
655 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
657 if (running_trap
== 0)
659 currently_executing_command
= (COMMAND
*)NULL
;
661 return (exec_result
);
663 #endif /* COMMAND_TIMING */
665 if (shell_control_structure (command
->type
) && command
->redirects
)
666 stdin_redir
= stdin_redirects (command
->redirects
);
668 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
670 if (do_redirections (command
->redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
672 cleanup_redirects (redirection_undo_list
);
673 redirection_undo_list
= (REDIRECT
*)NULL
;
674 dispose_exec_redirects ();
675 return (last_command_exit_value
= EXECUTION_FAILURE
);
678 if (redirection_undo_list
)
680 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
681 dispose_redirects (redirection_undo_list
);
682 redirection_undo_list
= (REDIRECT
*)NULL
;
685 my_undo_list
= (REDIRECT
*)NULL
;
687 if (exec_redirection_undo_list
)
689 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
690 dispose_redirects (exec_redirection_undo_list
);
691 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
694 exec_undo_list
= (REDIRECT
*)NULL
;
696 if (my_undo_list
|| exec_undo_list
)
697 begin_unwind_frame ("loop_redirections");
700 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
703 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
705 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
709 switch (command
->type
)
713 save_line_number
= line_number
;
714 /* We can't rely on variables retaining their values across a
715 call to execute_simple_command if a longjmp occurs as the
716 result of a `return' builtin. This is true for sure with gcc. */
717 #if defined (RECYCLES_PIDS)
718 last_made_pid
= NO_PID
;
720 last_pid
= last_made_pid
;
721 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
723 if (ignore_return
&& command
->value
.Simple
)
724 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
725 if (command
->flags
& CMD_STDIN_REDIR
)
726 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
728 line_number_for_err_trap
= line_number
= command
->value
.Simple
->line
;
730 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
731 asynchronous
, fds_to_close
);
732 line_number
= save_line_number
;
734 /* The temporary environment should be used for only the simple
735 command immediately following its definition. */
736 dispose_used_env_vars ();
738 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
739 /* Reclaim memory allocated with alloca () on machines which
740 may be using the alloca emulation code. */
742 #endif /* (ultrix && mips) || C_ALLOCA */
744 /* If we forked to do the command, then we must wait_for ()
747 /* XXX - this is something to watch out for if there are problems
748 when the shell is compiled without job control. */
749 if (already_making_children
&& pipe_out
== NO_PIPE
&&
750 last_made_pid
!= last_pid
)
752 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
756 DESCRIBE_PID (last_made_pid
);
759 #if !defined (JOB_CONTROL)
760 /* Do not wait for asynchronous processes started from
762 if (last_made_pid
!= last_asynchronous_pid
)
764 /* When executing a shell function that executes other
765 commands, this causes the last simple command in
766 the function to be waited for twice. This also causes
767 subshells forked to execute builtin commands (e.g., in
768 pipelines) to be waited for twice. */
769 exec_result
= wait_for (last_made_pid
);
773 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
774 only the failure of a simple command. */
775 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)
777 last_command_exit_value
= exec_result
;
778 line_number
= line_number_for_err_trap
;
780 line_number
= save_line_number
;
783 if (ignore_return
== 0 && invert
== 0 &&
784 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
785 (exit_immediately_on_error
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&& exec_result
!= EXECUTION_SUCCESS
)))
787 last_command_exit_value
= exec_result
;
788 run_pending_traps ();
789 jump_to_top_level (ERREXIT
);
796 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
797 exec_result
= execute_for_command (command
->value
.For
);
800 #if defined (ARITH_FOR_COMMAND)
803 command
->value
.ArithFor
->flags
|= CMD_IGNORE_RETURN
;
804 exec_result
= execute_arith_for_command (command
->value
.ArithFor
);
808 #if defined (SELECT_COMMAND)
811 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
812 exec_result
= execute_select_command (command
->value
.Select
);
818 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
819 exec_result
= execute_case_command (command
->value
.Case
);
824 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
825 exec_result
= execute_while_command (command
->value
.While
);
830 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
831 exec_result
= execute_until_command (command
->value
.While
);
836 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
837 exec_result
= execute_if_command (command
->value
.If
);
842 /* This code can be executed from either of two paths: an explicit
843 '{}' command, or via a function call. If we are executed via a
844 function call, we have already taken care of the function being
845 executed in the background (down there in execute_simple_command ()),
846 and this command should *not* be marked as asynchronous. If we
847 are executing a regular '{}' group command, and asynchronous == 1,
848 we must want to execute the whole command in the background, so we
849 need a subshell, and we want the stuff executed in that subshell
850 (this group command) to be executed in the foreground of that
851 subshell (i.e. there will not be *another* subshell forked).
853 What we do is to force a subshell if asynchronous, and then call
854 execute_command_internal again with asynchronous still set to 1,
855 but with the original group command, so the printed command will
858 The code above that handles forking off subshells will note that
859 both subshell and async are on, and turn off async in the child
860 after forking the subshell (but leave async set in the parent, so
861 the normal call to describe_pid is made). This turning off
862 async is *crucial*; if it is not done, this will fall into an
863 infinite loop of executions through this spot in subshell after
864 subshell until the process limit is exhausted. */
868 command
->flags
|= CMD_FORCE_SUBSHELL
;
870 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
875 if (ignore_return
&& command
->value
.Group
->command
)
876 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
878 execute_command_internal (command
->value
.Group
->command
,
879 asynchronous
, pipe_in
, pipe_out
,
885 exec_result
= execute_connection (command
, asynchronous
,
886 pipe_in
, pipe_out
, fds_to_close
);
889 #if defined (DPAREN_ARITHMETIC)
891 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
893 command
->value
.Arith
->flags
|= CMD_IGNORE_RETURN
;
894 line_number_for_err_trap
= save_line_number
= line_number
;
895 exec_result
= execute_arith_command (command
->value
.Arith
);
896 line_number
= save_line_number
;
898 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
900 last_command_exit_value
= exec_result
;
901 save_line_number
= line_number
;
902 line_number
= line_number_for_err_trap
;
904 line_number
= save_line_number
;
907 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
909 last_command_exit_value
= exec_result
;
910 run_pending_traps ();
911 jump_to_top_level (ERREXIT
);
917 #if defined (COND_COMMAND)
919 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
921 command
->value
.Cond
->flags
|= CMD_IGNORE_RETURN
;
923 line_number_for_err_trap
= save_line_number
= line_number
;
924 exec_result
= execute_cond_command (command
->value
.Cond
);
925 line_number
= save_line_number
;
927 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
929 last_command_exit_value
= exec_result
;
930 save_line_number
= line_number
;
931 line_number
= line_number_for_err_trap
;
933 line_number
= save_line_number
;
936 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
938 last_command_exit_value
= exec_result
;
939 run_pending_traps ();
940 jump_to_top_level (ERREXIT
);
946 case cm_function_def
:
947 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
948 command
->value
.Function_def
->command
);
952 command_error ("execute_command", CMDERR_BADTYPE
, command
->type
, 0);
957 do_redirections (my_undo_list
, RX_ACTIVE
);
958 dispose_redirects (my_undo_list
);
962 dispose_redirects (exec_undo_list
);
964 if (my_undo_list
|| exec_undo_list
)
965 discard_unwind_frame ("loop_redirections");
967 /* Invert the return value if we have to */
969 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
973 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
974 /* This is where we set PIPESTATUS from the exit status of the appropriate
975 compound commands (the ones that look enough like simple commands to
976 cause confusion). We might be able to optimize by not doing this if
977 subshell_environment != 0. */
978 switch (command
->type
)
980 # if defined (DPAREN_ARITHMETIC)
983 # if defined (COND_COMMAND)
986 set_pipestatus_from_exit (exec_result
);
991 last_command_exit_value
= exec_result
;
992 run_pending_traps ();
994 if (running_trap
== 0)
996 currently_executing_command
= (COMMAND
*)NULL
;
997 return (last_command_exit_value
);
1000 #if defined (COMMAND_TIMING)
1002 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1003 extern struct timeval
*difftimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1004 extern struct timeval
*addtimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1005 extern int timeval_to_cpu
__P((struct timeval
*, struct timeval
*, struct timeval
*));
1008 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1009 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1011 static const int precs
[] = { 0, 100, 10, 1 };
1013 /* Expand one `%'-prefixed escape sequence from a time format string. */
1015 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
1022 char abuf
[INT_STRLEN_BOUND(time_t) + 1];
1026 abuf
[sizeof(abuf
) - 1] = '\0';
1028 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1033 aind
= sizeof(abuf
) - 2;
1035 abuf
[aind
--] = (min
% 10) + '0';
1039 buf
[ind
++] = abuf
[aind
++];
1043 /* Now add the seconds. */
1044 aind
= sizeof (abuf
) - 2;
1046 abuf
[aind
--] = (sec
% 10) + '0';
1050 buf
[ind
++] = abuf
[aind
++];
1052 /* We want to add a decimal point and PREC places after it if PREC is
1053 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1058 for (aind
= 1; aind
<= prec
; aind
++)
1060 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
1061 sec_fraction
%= precs
[aind
];
1072 /* Interpret the format string FORMAT, interpolating the following escape
1076 where the optional `prec' is a precision, meaning the number of
1077 characters after the decimal point, the optional `l' means to format
1078 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1079 and the last character is one of
1081 R number of seconds of `real' time
1082 U number of seconds of `user' time
1083 S number of seconds of `system' time
1085 An occurrence of `%%' in the format string is translated to a `%'. The
1086 result is printed to FP, a pointer to a FILE. The other variables are
1087 the seconds and thousandths of a second of real, user, and system time,
1090 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1101 char *str
, *s
, ts
[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1106 len
= strlen (format
);
1107 ssize
= (len
+ 64) - (len
% 64);
1108 str
= (char *)xmalloc (ssize
);
1111 for (s
= format
; *s
; s
++)
1113 if (*s
!= '%' || s
[1] == '\0')
1115 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1118 else if (s
[1] == '%')
1121 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1124 else if (s
[1] == 'P')
1128 /* clamp CPU usage at 100% */
1133 sum_frac
= (cpu
% 100) * 10;
1134 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1135 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1136 strcpy (str
+ sindex
, ts
);
1141 prec
= 3; /* default is three places past the decimal point. */
1142 lng
= 0; /* default is to not use minutes or append `s' */
1144 if (DIGIT (*s
)) /* `precision' */
1147 if (prec
> 3) prec
= 3;
1149 if (*s
== 'l') /* `length extender' */
1154 if (*s
== 'R' || *s
== 'E')
1155 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1157 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1159 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1162 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s
);
1166 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1167 strcpy (str
+ sindex
, ts
);
1173 fprintf (fp
, "%s\n", str
);
1180 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1182 int asynchronous
, pipe_in
, pipe_out
;
1183 struct fd_bitmap
*fds_to_close
;
1185 int rv
, posix_time
, old_flags
;
1191 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1192 struct timeval real
, user
, sys
;
1193 struct timeval before
, after
;
1194 # if defined (HAVE_STRUCT_TIMEZONE)
1195 struct timezone dtz
; /* posix doesn't define this */
1197 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1199 # if defined (HAVE_TIMES)
1200 clock_t tbefore
, tafter
, real
, user
, sys
;
1201 struct tms before
, after
;
1205 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1206 # if defined (HAVE_STRUCT_TIMEZONE)
1207 gettimeofday (&before
, &dtz
);
1209 gettimeofday (&before
, (void *)NULL
);
1210 # endif /* !HAVE_STRUCT_TIMEZONE */
1211 getrusage (RUSAGE_SELF
, &selfb
);
1212 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1214 # if defined (HAVE_TIMES)
1215 tbefore
= times (&before
);
1219 posix_time
= (command
->flags
& CMD_TIME_POSIX
);
1221 old_flags
= command
->flags
;
1222 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1223 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1224 command
->flags
= old_flags
;
1227 rsf
= usf
= ssf
= cpu
= 0;
1229 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1230 # if defined (HAVE_STRUCT_TIMEZONE)
1231 gettimeofday (&after
, &dtz
);
1233 gettimeofday (&after
, (void *)NULL
);
1234 # endif /* !HAVE_STRUCT_TIMEZONE */
1235 getrusage (RUSAGE_SELF
, &selfa
);
1236 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1238 difftimeval (&real
, &before
, &after
);
1239 timeval_to_secs (&real
, &rs
, &rsf
);
1241 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1242 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1243 timeval_to_secs (&user
, &us
, &usf
);
1245 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1246 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1247 timeval_to_secs (&sys
, &ss
, &ssf
);
1249 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1251 # if defined (HAVE_TIMES)
1252 tafter
= times (&after
);
1254 real
= tafter
- tbefore
;
1255 clock_t_to_secs (real
, &rs
, &rsf
);
1257 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1258 clock_t_to_secs (user
, &us
, &usf
);
1260 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1261 clock_t_to_secs (sys
, &ss
, &ssf
);
1263 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1267 rsf
= usf
= ssf
= cpu
= 0;
1272 time_format
= POSIX_TIMEFORMAT
;
1273 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1274 time_format
= BASH_TIMEFORMAT
;
1276 if (time_format
&& *time_format
)
1277 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1281 #endif /* COMMAND_TIMING */
1283 /* Execute a command that's supposed to be in a subshell. This must be
1284 called after make_child and we must be running in the child process.
1285 The caller will return or exit() immediately with the value this returns. */
1287 execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1290 int pipe_in
, pipe_out
;
1291 struct fd_bitmap
*fds_to_close
;
1293 int user_subshell
, return_code
, function_value
, should_redir_stdin
, invert
;
1294 int ois
, user_coproc
;
1298 USE_VAR(user_subshell
);
1299 USE_VAR(user_coproc
);
1302 USE_VAR(asynchronous
);
1305 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
1306 pipe_in
== NO_PIPE
&&
1307 stdin_redirects (command
->redirects
) == 0);
1309 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
1310 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
1311 user_coproc
= command
->type
== cm_coproc
;
1313 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
1315 /* If a command is asynchronous in a subshell (like ( foo ) & or
1316 the special case of an asynchronous GROUP command where the
1317 the subshell bit is turned on down in case cm_group: below),
1318 turn off `asynchronous', so that two subshells aren't spawned.
1319 XXX - asynchronous used to be set to 0 in this block, but that
1320 means that setup_async_signals was never run. Now it's set to
1321 0 after subshell_environment is set appropriately and setup_async_signals
1324 This seems semantically correct to me. For example,
1325 ( foo ) & seems to say ``do the command `foo' in a subshell
1326 environment, but don't wait for that subshell to finish'',
1327 and "{ foo ; bar ; } &" seems to me to be like functions or
1328 builtins in the background, which executed in a subshell
1329 environment. I just don't see the need to fork two subshells. */
1331 /* Don't fork again, we are already in a subshell. A `doubly
1332 async' shell is not interactive, however. */
1335 #if defined (JOB_CONTROL)
1336 /* If a construct like ( exec xxx yyy ) & is given while job
1337 control is active, we want to prevent exec from putting the
1338 subshell back into the original process group, carefully
1339 undoing all the work we just did in make_child. */
1341 #endif /* JOB_CONTROL */
1342 ois
= interactive_shell
;
1343 interactive_shell
= 0;
1344 /* This test is to prevent alias expansion by interactive shells that
1345 run `(command) &' but to allow scripts that have enabled alias
1346 expansion with `shopt -s expand_alias' to continue to expand
1348 if (ois
!= interactive_shell
)
1352 /* Subshells are neither login nor interactive. */
1353 login_shell
= interactive
= 0;
1356 subshell_environment
= SUBSHELL_PAREN
;
1359 subshell_environment
= 0; /* XXX */
1361 subshell_environment
|= SUBSHELL_ASYNC
;
1362 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
1363 subshell_environment
|= SUBSHELL_PIPE
;
1365 subshell_environment
|= SUBSHELL_COPROC
;
1368 reset_terminating_signals (); /* in sig.c */
1369 /* Cancel traps, in trap.c. */
1370 restore_original_signals ();
1372 /* Make sure restore_original_signals doesn't undo the work done by
1373 make_child to ensure that asynchronous children are immune to SIGINT
1374 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1378 setup_async_signals ();
1382 #if defined (JOB_CONTROL)
1383 set_sigchld_handler ();
1384 #endif /* JOB_CONTROL */
1386 set_sigint_handler ();
1388 #if defined (JOB_CONTROL)
1389 /* Delete all traces that there were any jobs running. This is
1390 only for subshells. */
1391 without_job_control ();
1392 #endif /* JOB_CONTROL */
1395 close_fd_bitmap (fds_to_close
);
1397 do_piping (pipe_in
, pipe_out
);
1399 #if defined (COPROCESS_SUPPORT)
1403 /* If this is a user subshell, set a flag if stdin was redirected.
1404 This is used later to decide whether to redirect fd 0 to
1405 /dev/null for async commands in the subshell. This adds more
1406 sh compatibility, but I'm not sure it's the right thing to do. */
1409 stdin_redir
= stdin_redirects (command
->redirects
);
1410 restore_default_signal (0);
1413 /* If this is an asynchronous command (command &), we want to
1414 redirect the standard input from /dev/null in the absence of
1415 any specific redirection involving stdin. */
1416 if (should_redir_stdin
&& stdin_redir
== 0)
1417 async_redirect_stdin ();
1419 /* Do redirections, then dispose of them before recursive call. */
1420 if (command
->redirects
)
1422 if (do_redirections (command
->redirects
, RX_ACTIVE
) != 0)
1423 exit (invert
? EXECUTION_SUCCESS
: EXECUTION_FAILURE
);
1425 dispose_redirects (command
->redirects
);
1426 command
->redirects
= (REDIRECT
*)NULL
;
1429 if (command
->type
== cm_subshell
)
1430 tcom
= command
->value
.Subshell
->command
;
1431 else if (user_coproc
)
1432 tcom
= command
->value
.Coproc
->command
;
1436 if (command
->flags
& CMD_TIME_PIPELINE
)
1437 tcom
->flags
|= CMD_TIME_PIPELINE
;
1438 if (command
->flags
& CMD_TIME_POSIX
)
1439 tcom
->flags
|= CMD_TIME_POSIX
;
1441 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1442 if ((command
->flags
& CMD_IGNORE_RETURN
) && tcom
!= command
)
1443 tcom
->flags
|= CMD_IGNORE_RETURN
;
1445 /* If this is a simple command, tell execute_disk_command that it
1446 might be able to get away without forking and simply exec.
1447 This means things like ( sleep 10 ) will only cause one fork.
1448 If we're timing the command or inverting its return value, however,
1449 we cannot do this optimization. */
1450 if ((user_subshell
|| user_coproc
) && (tcom
->type
== cm_simple
|| tcom
->type
== cm_subshell
) &&
1451 ((tcom
->flags
& CMD_TIME_PIPELINE
) == 0) &&
1452 ((tcom
->flags
& CMD_INVERT_RETURN
) == 0))
1454 tcom
->flags
|= CMD_NO_FORK
;
1455 if (tcom
->type
== cm_simple
)
1456 tcom
->value
.Simple
->flags
|= CMD_NO_FORK
;
1459 invert
= (tcom
->flags
& CMD_INVERT_RETURN
) != 0;
1460 tcom
->flags
&= ~CMD_INVERT_RETURN
;
1462 result
= setjmp (top_level
);
1464 /* If we're inside a function while executing this subshell, we
1465 need to handle a possible `return'. */
1467 if (return_catch_flag
)
1468 function_value
= setjmp (return_catch
);
1470 /* If we're going to exit the shell, we don't want to invert the return
1472 if (result
== EXITPROG
)
1473 invert
= 0, return_code
= last_command_exit_value
;
1475 return_code
= EXECUTION_FAILURE
;
1476 else if (function_value
)
1477 return_code
= return_catch_value
;
1479 return_code
= execute_command_internal (tcom
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
1481 /* If we are asked to, invert the return value. */
1483 return_code
= (return_code
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
1484 : EXECUTION_SUCCESS
;
1486 /* If we were explicitly placed in a subshell with (), we need
1487 to do the `shell cleanup' things, such as running traps[0]. */
1488 if (user_subshell
&& signal_is_trapped (0))
1490 last_command_exit_value
= return_code
;
1491 return_code
= run_exit_trap ();
1495 return (return_code
);
1499 #if defined (COPROCESS_SUPPORT)
1500 #define COPROC_MAX 16
1502 typedef struct cpelement
1504 struct cpelement
*next
;
1505 struct coproc
*coproc
;
1509 typedef struct cplist
1511 struct cpelement
*head
;
1512 struct cpelement
*tail
;
1517 static struct cpelement
*cpe_alloc
__P((struct coproc
*));
1518 static void cpe_dispose
__P((struct cpelement
*));
1519 static struct cpelement
*cpl_add
__P((struct coproc
*));
1520 static struct cpelement
*cpl_delete
__P((pid_t
));
1521 static void cpl_reap
__P((void));
1522 static void cpl_flush
__P((void));
1523 static struct cpelement
*cpl_search
__P((pid_t
));
1524 static struct cpelement
*cpl_searchbyname
__P((char *));
1525 static void cpl_prune
__P((void));
1527 Coproc sh_coproc
= { 0, NO_PID
, -1, -1, 0, 0 };
1529 cplist_t coproc_list
= {0, 0, 0};
1531 /* Functions to manage the list of coprocs */
1533 static struct cpelement
*
1537 struct cpelement
*cpe
;
1539 cpe
= (struct cpelement
*)xmalloc (sizeof (struct cpelement
));
1541 cpe
->next
= (struct cpelement
*)0;
1547 struct cpelement
*cpe
;
1552 static struct cpelement
*
1556 struct cpelement
*cpe
;
1558 cpe
= cpe_alloc (cp
);
1560 if (coproc_list
.head
== 0)
1562 coproc_list
.head
= coproc_list
.tail
= cpe
;
1563 coproc_list
.ncoproc
= 0; /* just to make sure */
1567 coproc_list
.tail
->next
= cpe
;
1568 coproc_list
.tail
= cpe
;
1570 coproc_list
.ncoproc
++;
1575 static struct cpelement
*
1579 struct cpelement
*prev
, *p
;
1581 for (prev
= p
= coproc_list
.head
; p
; prev
= p
, p
= p
->next
)
1582 if (p
->coproc
->c_pid
== pid
)
1584 prev
->next
= p
->next
; /* remove from list */
1589 return 0; /* not found */
1592 itrace("cpl_delete: deleting %d", pid
);
1595 /* Housekeeping in the border cases. */
1596 if (p
== coproc_list
.head
)
1597 coproc_list
.head
= coproc_list
.head
->next
;
1598 else if (p
== coproc_list
.tail
)
1599 coproc_list
.tail
= prev
;
1601 coproc_list
.ncoproc
--;
1602 if (coproc_list
.ncoproc
== 0)
1603 coproc_list
.head
= coproc_list
.tail
= 0;
1604 else if (coproc_list
.ncoproc
== 1)
1605 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1613 struct cpelement
*prev
, *p
;
1615 for (prev
= p
= coproc_list
.head
; p
; prev
= p
, p
= p
->next
)
1616 if (p
->coproc
->c_flags
& COPROC_DEAD
)
1618 prev
->next
= p
->next
; /* remove from list */
1620 /* Housekeeping in the border cases. */
1621 if (p
== coproc_list
.head
)
1622 coproc_list
.head
= coproc_list
.head
->next
;
1623 else if (p
== coproc_list
.tail
)
1624 coproc_list
.tail
= prev
;
1626 coproc_list
.ncoproc
--;
1627 if (coproc_list
.ncoproc
== 0)
1628 coproc_list
.head
= coproc_list
.tail
= 0;
1629 else if (coproc_list
.ncoproc
== 1)
1630 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1633 itrace("cpl_reap: deleting %d", p
->coproc
->c_pid
);
1636 coproc_dispose (p
->coproc
);
1641 /* Clear out the list of saved statuses */
1645 struct cpelement
*cpe
, *p
;
1647 for (cpe
= coproc_list
.head
; cpe
; )
1652 coproc_dispose (p
->coproc
);
1656 coproc_list
.head
= coproc_list
.tail
= 0;
1657 coproc_list
.ncoproc
= 0;
1660 /* Search for PID in the list of coprocs; return the cpelement struct if
1661 found. If not found, return NULL. */
1662 static struct cpelement
*
1666 struct cpelement
*cp
;
1668 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1669 if (cp
->coproc
->c_pid
== pid
)
1671 return (struct cpelement
*)NULL
;
1674 /* Search for the coproc named NAME in the list of coprocs; return the
1675 cpelement struct if found. If not found, return NULL. */
1676 static struct cpelement
*
1677 cpl_searchbyname (name
)
1680 struct cpelement
*cp
;
1682 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1683 if (STREQ (cp
->coproc
->c_name
, name
))
1685 return (struct cpelement
*)NULL
;
1692 struct cpelement
*cp
;
1694 while (coproc_list
.head
&& coproc_list
.ncoproc
> COPROC_MAX
)
1696 cp
= coproc_list
.head
;
1697 coproc_list
.head
= coproc_list
.head
->next
;
1698 coproc_dispose (cp
->coproc
);
1700 coproc_list
.ncoproc
--;
1705 /* These currently use a single global "shell coproc" but are written in a
1706 way to not preclude additional coprocs later (using the list management
1710 getcoprocbypid (pid
)
1713 return (pid
== sh_coproc
.c_pid
? &sh_coproc
: 0);
1717 getcoprocbyname (name
)
1720 return ((sh_coproc
.c_name
&& STREQ (sh_coproc
.c_name
, name
)) ? &sh_coproc
: 0);
1729 cp
->c_rfd
= cp
->c_wfd
= -1;
1730 cp
->c_rsave
= cp
->c_wsave
= -1;
1731 cp
->c_flags
= cp
->c_status
= 0;
1735 coproc_alloc (name
, pid
)
1741 cp
= &sh_coproc
; /* XXX */
1744 cp
->c_name
= savestring (name
);
1757 coproc_unsetvars (cp
);
1763 /* Placeholder for now. */
1767 coproc_dispose (&sh_coproc
);
1784 cp
->c_rsave
= cp
->c_wsave
= -1;
1790 coproc_close (&sh_coproc
);
1799 if (cp
&& (cp
->c_flags
& COPROC_DEAD
))
1800 coproc_dispose (cp
);
1804 coproc_rclose (cp
, fd
)
1808 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
1816 coproc_wclose (cp
, fd
)
1820 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
1828 coproc_checkfd (cp
, fd
)
1835 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
1836 update
= cp
->c_rfd
= -1;
1837 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
1838 update
= cp
->c_wfd
= -1;
1840 coproc_setvars (cp
);
1847 coproc_checkfd (&sh_coproc
, fd
);
1851 coproc_fdclose (cp
, fd
)
1855 coproc_rclose (cp
, fd
);
1856 coproc_wclose (cp
, fd
);
1857 coproc_setvars (cp
);
1864 cp
->c_rsave
= cp
->c_rfd
;
1865 cp
->c_wsave
= cp
->c_wfd
;
1869 coproc_fdrestore (cp
)
1872 cp
->c_rfd
= cp
->c_rsave
;
1873 cp
->c_wfd
= cp
->c_wsave
;
1877 coproc_pidchk (pid
, status
)
1882 cp
= getcoprocbypid (pid
);
1885 itrace("coproc_pidchk: pid %d has died", pid
);
1889 cp
->c_status
= status
;
1890 cp
->c_flags
|= COPROC_DEAD
;
1891 cp
->c_flags
&= ~COPROC_RUNNING
;
1893 coproc_dispose (cp
);
1905 #if defined (ARRAY_VARS)
1909 if (cp
->c_name
== 0)
1912 l
= strlen (cp
->c_name
);
1913 namevar
= xmalloc (l
+ 16);
1915 #if defined (ARRAY_VARS)
1916 v
= find_variable (cp
->c_name
);
1918 v
= make_new_array_variable (cp
->c_name
);
1919 if (array_p (v
) == 0)
1920 v
= convert_var_to_array (v
);
1922 t
= itos (cp
->c_rfd
);
1924 v
= bind_array_variable (cp
->c_name
, ind
, t
, 0);
1927 t
= itos (cp
->c_wfd
);
1929 bind_array_variable (cp
->c_name
, ind
, t
, 0);
1932 sprintf (namevar
, "%s_READ", cp
->c_name
);
1933 t
= itos (cp
->c_rfd
);
1934 bind_variable (namevar
, t
, 0);
1936 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
1937 t
= itos (cp
->c_wfd
);
1938 bind_variable (namevar
, t
, 0);
1942 sprintf (namevar
, "%s_PID", cp
->c_name
);
1943 t
= itos (cp
->c_pid
);
1944 bind_variable (namevar
, t
, 0);
1951 coproc_unsetvars (cp
)
1957 if (cp
->c_name
== 0)
1960 l
= strlen (cp
->c_name
);
1961 namevar
= xmalloc (l
+ 16);
1963 sprintf (namevar
, "%s_PID", cp
->c_name
);
1964 unbind_variable (namevar
);
1966 #if defined (ARRAY_VARS)
1967 unbind_variable (cp
->c_name
);
1969 sprintf (namevar
, "%s_READ", cp
->c_name
);
1970 unbind_variable (namevar
);
1971 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
1972 unbind_variable (namevar
);
1979 execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
)
1981 int pipe_in
, pipe_out
;
1982 struct fd_bitmap
*fds_to_close
;
1984 int rpipe
[2], wpipe
[2], estat
;
1989 /* XXX -- will require changes to handle multiple coprocs */
1990 if (sh_coproc
.c_pid
!= NO_PID
)
1993 internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc
.c_pid
, sh_coproc
.c_name
);
1994 return (last_command_exit_value
= EXECUTION_FAILURE
);
1996 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc
.c_pid
, sh_coproc
.c_name
);
1999 coproc_init (&sh_coproc
);
2001 command_string_index
= 0;
2002 tcmd
= make_command_string (command
);
2004 sh_openpipe ((int *)&rpipe
); /* 0 = parent read, 1 = child write */
2005 sh_openpipe ((int *)&wpipe
); /* 0 = child read, 1 = parent write */
2007 coproc_pid
= make_child (savestring (tcmd
), 1);
2008 if (coproc_pid
== 0)
2013 estat
= execute_in_subshell (command
, 1, wpipe
[0], rpipe
[1], fds_to_close
);
2024 cp
= coproc_alloc (command
->value
.Coproc
->name
, coproc_pid
);
2025 cp
->c_rfd
= rpipe
[0];
2026 cp
->c_wfd
= wpipe
[1];
2028 SET_CLOSE_ON_EXEC (cp
->c_rfd
);
2029 SET_CLOSE_ON_EXEC (cp
->c_wfd
);
2031 coproc_setvars (cp
);
2034 itrace ("execute_coproc: [%d] %s", coproc_pid
, the_printed_command
);
2037 close_pipes (pipe_in
, pipe_out
);
2038 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2039 unlink_fifo_list ();
2041 stop_pipeline (1, (COMMAND
*)NULL
);
2042 DESCRIBE_PID (coproc_pid
);
2043 run_pending_traps ();
2045 return (EXECUTION_SUCCESS
);
2050 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2052 int asynchronous
, pipe_in
, pipe_out
;
2053 struct fd_bitmap
*fds_to_close
;
2055 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
2057 struct fd_bitmap
*fd_bitmap
;
2059 #if defined (JOB_CONTROL)
2061 BLOCK_CHILD (set
, oset
);
2062 #endif /* JOB_CONTROL */
2064 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2069 while (cmd
&& cmd
->type
== cm_connection
&&
2070 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
2072 /* Make a pipeline between the two commands. */
2073 if (pipe (fildes
) < 0)
2075 sys_error (_("pipe error"));
2076 #if defined (JOB_CONTROL)
2077 terminate_current_pipeline ();
2078 kill_current_pipeline ();
2079 UNBLOCK_CHILD (oset
);
2080 #endif /* JOB_CONTROL */
2081 last_command_exit_value
= EXECUTION_FAILURE
;
2082 /* The unwind-protects installed below will take care
2083 of closing all of the open file descriptors. */
2084 throw_to_top_level ();
2085 return (EXECUTION_FAILURE
); /* XXX */
2088 /* Here is a problem: with the new file close-on-exec
2089 code, the read end of the pipe (fildes[0]) stays open
2090 in the first process, so that process will never get a
2091 SIGPIPE. There is no way to signal the first process
2092 that it should close fildes[0] after forking, so it
2093 remains open. No SIGPIPE is ever sent because there
2094 is still a file descriptor open for reading connected
2095 to the pipe. We take care of that here. This passes
2096 around a bitmap of file descriptors that must be
2097 closed after making a child process in execute_simple_command. */
2099 /* We need fd_bitmap to be at least as big as fildes[0].
2100 If fildes[0] is less than fds_to_close->size, then
2101 use fds_to_close->size. */
2102 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
2103 ? fds_to_close
->size
2106 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
2108 /* Now copy the old information into the new bitmap. */
2109 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
2111 /* And mark the pipe file descriptors to be closed. */
2112 fd_bitmap
->bitmap
[fildes
[0]] = 1;
2114 /* In case there are pipe or out-of-processes errors, we
2115 want all these file descriptors to be closed when
2116 unwind-protects are run, and the storage used for the
2117 bitmaps freed up. */
2118 begin_unwind_frame ("pipe-file-descriptors");
2119 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
2120 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
2122 add_unwind_protect (close
, prev
);
2123 dummyfd
= fildes
[1];
2124 add_unwind_protect (close
, dummyfd
);
2126 #if defined (JOB_CONTROL)
2127 add_unwind_protect (restore_signal_mask
, &oset
);
2128 #endif /* JOB_CONTROL */
2130 if (ignore_return
&& cmd
->value
.Connection
->first
)
2131 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2132 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
2133 prev
, fildes
[1], fd_bitmap
);
2141 dispose_fd_bitmap (fd_bitmap
);
2142 discard_unwind_frame ("pipe-file-descriptors");
2144 cmd
= cmd
->value
.Connection
->second
;
2147 /* Now execute the rightmost command in the pipeline. */
2148 if (ignore_return
&& cmd
)
2149 cmd
->flags
|= CMD_IGNORE_RETURN
;
2150 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
2155 #if defined (JOB_CONTROL)
2156 UNBLOCK_CHILD (oset
);
2160 return (exec_result
);
2164 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2166 int asynchronous
, pipe_in
, pipe_out
;
2167 struct fd_bitmap
*fds_to_close
;
2170 COMMAND
*tc
, *second
;
2171 int ignore_return
, exec_result
, was_error_trap
, invert
;
2172 volatile int save_line_number
;
2174 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2176 switch (command
->value
.Connection
->connector
)
2178 /* Do the first command asynchronously. */
2180 tc
= command
->value
.Connection
->first
;
2182 return (EXECUTION_SUCCESS
);
2187 tc
->flags
|= CMD_IGNORE_RETURN
;
2188 tc
->flags
|= CMD_AMPERSAND
;
2190 /* If this shell was compiled without job control support,
2191 if we are currently in a subshell via `( xxx )', or if job
2192 control is not active then the standard input for an
2193 asynchronous command is forced to /dev/null. */
2194 #if defined (JOB_CONTROL)
2195 if ((subshell_environment
|| !job_control
) && !stdin_redir
)
2198 #endif /* JOB_CONTROL */
2199 tc
->flags
|= CMD_STDIN_REDIR
;
2201 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
2204 if (tc
->flags
& CMD_STDIN_REDIR
)
2205 tc
->flags
&= ~CMD_STDIN_REDIR
;
2207 second
= command
->value
.Connection
->second
;
2211 second
->flags
|= CMD_IGNORE_RETURN
;
2213 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2218 /* Just call execute command on both sides. */
2222 if (command
->value
.Connection
->first
)
2223 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2224 if (command
->value
.Connection
->second
)
2225 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2229 execute_command (command
->value
.Connection
->first
);
2231 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
2232 asynchronous
, pipe_in
, pipe_out
,
2238 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
2239 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
2240 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2242 line_number_for_err_trap
= line_number
;
2243 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2245 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
2247 last_command_exit_value
= exec_result
;
2248 save_line_number
= line_number
;
2249 line_number
= line_number_for_err_trap
;
2251 line_number
= save_line_number
;
2254 if (ignore_return
== 0 && invert
== 0 && exit_immediately_on_error
&& exec_result
!= EXECUTION_SUCCESS
)
2256 last_command_exit_value
= exec_result
;
2257 run_pending_traps ();
2258 jump_to_top_level (ERREXIT
);
2267 /* If we have something like `a && b &' or `a || b &', run the
2268 && or || stuff in a subshell. Force a subshell and just call
2269 execute_command_internal again. Leave asynchronous on
2270 so that we get a report from the parent shell about the
2272 command
->flags
|= CMD_FORCE_SUBSHELL
;
2273 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
2277 /* Execute the first command. If the result of that is successful
2278 and the connector is AND_AND, or the result is not successful
2279 and the connector is OR_OR, then execute the second command,
2280 otherwise return. */
2283 if (command
->value
.Connection
->first
)
2284 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2286 exec_result
= execute_command (command
->value
.Connection
->first
);
2288 if (((command
->value
.Connection
->connector
== AND_AND
) &&
2289 (exec_result
== EXECUTION_SUCCESS
)) ||
2290 ((command
->value
.Connection
->connector
== OR_OR
) &&
2291 (exec_result
!= EXECUTION_SUCCESS
)))
2293 if (ignore_return
&& command
->value
.Connection
->second
)
2294 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2296 exec_result
= execute_command (command
->value
.Connection
->second
);
2302 command_error ("execute_connection", CMDERR_BADCONN
, command
->value
.Connection
->connector
, 0);
2303 jump_to_top_level (DISCARD
);
2304 exec_result
= EXECUTION_FAILURE
;
2313 if (!interactive_shell) \
2314 reap_dead_jobs (); \
2318 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2321 execute_for_command (for_command
)
2322 FOR_COM
*for_command
;
2324 register WORD_LIST
*releaser
, *list
;
2327 int retval
, save_line_number
;
2329 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
2332 save_line_number
= line_number
;
2333 if (check_identifier (for_command
->name
, 1) == 0)
2335 if (posixly_correct
&& interactive_shell
== 0)
2337 last_command_exit_value
= EX_BADUSAGE
;
2338 jump_to_top_level (ERREXIT
);
2340 return (EXECUTION_FAILURE
);
2344 identifier
= for_command
->name
->word
;
2346 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
2348 begin_unwind_frame ("for");
2349 add_unwind_protect (dispose_words
, releaser
);
2352 if (lexical_scoping
)
2354 old_value
= copy_variable (find_variable (identifier
));
2356 add_unwind_protect (dispose_variable
, old_value
);
2360 if (for_command
->flags
& CMD_IGNORE_RETURN
)
2361 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2363 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
2367 line_number
= for_command
->line
;
2369 /* Remember what this command looks like, for debugger. */
2370 command_string_index
= 0;
2371 print_for_command_head (for_command
);
2373 if (echo_command_at_execute
)
2374 xtrace_print_for_command_head (for_command
);
2376 /* Save this command unless it's a trap command and we're not running
2379 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2381 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2384 FREE (the_printed_command_except_trap
);
2385 the_printed_command_except_trap
= savestring (the_printed_command
);
2388 retval
= run_debug_trap ();
2389 #if defined (DEBUGGER)
2390 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2391 skip the command. */
2392 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2396 this_command_name
= (char *)NULL
;
2397 v
= bind_variable (identifier
, list
->word
->word
, 0);
2398 if (readonly_p (v
) || noassign_p (v
))
2400 line_number
= save_line_number
;
2401 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2403 last_command_exit_value
= EXECUTION_FAILURE
;
2404 jump_to_top_level (FORCE_EOF
);
2408 dispose_words (releaser
);
2409 discard_unwind_frame ("for");
2411 return (EXECUTION_FAILURE
);
2414 retval
= execute_command (for_command
->action
);
2433 line_number
= save_line_number
;
2436 if (lexical_scoping
)
2439 unbind_variable (identifier
);
2442 SHELL_VAR
*new_value
;
2444 new_value
= bind_variable (identifier
, value_cell(old_value
), 0);
2445 new_value
->attributes
= old_value
->attributes
;
2446 dispose_variable (old_value
);
2451 dispose_words (releaser
);
2452 discard_unwind_frame ("for");
2456 #if defined (ARITH_FOR_COMMAND)
2457 /* Execute an arithmetic for command. The syntax is
2459 for (( init ; step ; test ))
2464 The execution should be exactly equivalent to
2467 while eval \(\( test \)\) ; do
2473 eval_arith_for_expr (l
, okp
)
2481 new = expand_words_no_vars (l
);
2484 if (echo_command_at_execute
)
2485 xtrace_print_arith_cmd (new);
2486 this_command_name
= "(("; /* )) for expression error messages */
2488 command_string_index
= 0;
2489 print_arith_command (new);
2490 if (signal_in_progress (DEBUG_TRAP
) == 0)
2492 FREE (the_printed_command_except_trap
);
2493 the_printed_command_except_trap
= savestring (the_printed_command
);
2496 r
= run_debug_trap ();
2497 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2498 skip the command. */
2499 #if defined (DEBUGGER)
2500 if (debugging_mode
== 0 || r
== EXECUTION_SUCCESS
)
2501 expresult
= evalexp (new->word
->word
, okp
);
2509 expresult
= evalexp (new->word
->word
, okp
);
2511 dispose_words (new);
2523 execute_arith_for_command (arith_for_command
)
2524 ARITH_FOR_COM
*arith_for_command
;
2527 int expok
, body_status
, arith_lineno
, save_lineno
;
2529 body_status
= EXECUTION_SUCCESS
;
2531 save_lineno
= line_number
;
2533 if (arith_for_command
->flags
& CMD_IGNORE_RETURN
)
2534 arith_for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2536 this_command_name
= "(("; /* )) for expression error messages */
2538 /* save the starting line number of the command so we can reset
2539 line_number before executing each expression -- for $LINENO
2540 and the DEBUG trap. */
2541 line_number
= arith_lineno
= arith_for_command
->line
;
2542 if (variable_context
&& interactive_shell
)
2543 line_number
-= function_line_number
;
2545 /* Evaluate the initialization expression. */
2546 expresult
= eval_arith_for_expr (arith_for_command
->init
, &expok
);
2549 line_number
= save_lineno
;
2550 return (EXECUTION_FAILURE
);
2555 /* Evaluate the test expression. */
2556 line_number
= arith_lineno
;
2557 expresult
= eval_arith_for_expr (arith_for_command
->test
, &expok
);
2558 line_number
= save_lineno
;
2562 body_status
= EXECUTION_FAILURE
;
2569 /* Execute the body of the arithmetic for command. */
2571 body_status
= execute_command (arith_for_command
->action
);
2574 /* Handle any `break' or `continue' commands executed by the body. */
2588 /* Evaluate the step expression. */
2589 line_number
= arith_lineno
;
2590 expresult
= eval_arith_for_expr (arith_for_command
->step
, &expok
);
2591 line_number
= save_lineno
;
2595 body_status
= EXECUTION_FAILURE
;
2601 line_number
= save_lineno
;
2603 return (body_status
);
2607 #if defined (SELECT_COMMAND)
2608 static int LINES
, COLS
, tabsize
;
2610 #define RP_SPACE ") "
2611 #define RP_SPACE_LEN 2
2613 /* XXX - does not handle numbers > 1000000 at all. */
2614 #define NUMBER_LEN(s) \
2618 : ((s < 10000) ? 4 \
2619 : ((s < 100000) ? 5 \
2623 print_index_and_element (len
, ind
, list
)
2627 register WORD_LIST
*l
;
2632 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
2634 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
2635 return (STRLEN (l
->word
->word
));
2644 if ((to
/ tabsize
) > (from
/ tabsize
))
2646 putc ('\t', stderr
);
2647 from
+= tabsize
- from
% tabsize
;
2658 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
2660 int list_len
, max_elem_len
, indices_len
;
2662 int ind
, row
, elem_len
, pos
, cols
, rows
;
2663 int first_column_indices_len
, other_indices_len
;
2667 putc ('\n', stderr
);
2671 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
2674 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
2675 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
2683 first_column_indices_len
= NUMBER_LEN (rows
);
2684 other_indices_len
= indices_len
;
2686 for (row
= 0; row
< rows
; row
++)
2692 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
2693 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
2694 elem_len
+= indices_len
+ RP_SPACE_LEN
;
2696 if (ind
>= list_len
)
2698 indent (pos
+ elem_len
, pos
+ max_elem_len
);
2699 pos
+= max_elem_len
;
2701 putc ('\n', stderr
);
2705 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2706 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2707 If the number is between 1 and LIST_LEN, return that selection. If EOF
2708 is read, return a null string. If a blank line is entered, or an invalid
2709 number is entered, the loop is executed again. */
2711 select_query (list
, list_len
, prompt
, print_menu
)
2717 int max_elem_len
, indices_len
, len
;
2720 char *repl_string
, *t
;
2722 t
= get_string_value ("LINES");
2723 LINES
= (t
&& *t
) ? atoi (t
) : 24;
2724 t
= get_string_value ("COLUMNS");
2725 COLS
= (t
&& *t
) ? atoi (t
) : 80;
2728 t
= get_string_value ("TABSIZE");
2729 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
2737 for (l
= list
; l
; l
= l
->next
)
2739 len
= STRLEN (l
->word
->word
);
2740 if (len
> max_elem_len
)
2743 indices_len
= NUMBER_LEN (list_len
);
2744 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
2749 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
2750 fprintf (stderr
, "%s", prompt
);
2754 if (read_builtin ((WORD_LIST
*)NULL
) == EXECUTION_FAILURE
)
2757 return ((char *)NULL
);
2759 repl_string
= get_string_value ("REPLY");
2760 if (*repl_string
== 0)
2765 if (legal_number (repl_string
, &reply
) == 0)
2767 if (reply
< 1 || reply
> list_len
)
2770 for (l
= list
; l
&& --reply
; l
= l
->next
)
2772 return (l
->word
->word
);
2776 /* Execute a SELECT command. The syntax is:
2777 SELECT word IN list DO command_list DONE
2778 Only `break' or `return' in command_list will terminate
2781 execute_select_command (select_command
)
2782 SELECT_COM
*select_command
;
2784 WORD_LIST
*releaser
, *list
;
2786 char *identifier
, *ps3_prompt
, *selection
;
2787 int retval
, list_len
, show_menu
, save_line_number
;
2789 if (check_identifier (select_command
->name
, 1) == 0)
2790 return (EXECUTION_FAILURE
);
2792 save_line_number
= line_number
;
2793 line_number
= select_command
->line
;
2795 command_string_index
= 0;
2796 print_select_command_head (select_command
);
2798 if (echo_command_at_execute
)
2799 xtrace_print_select_command_head (select_command
);
2802 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2804 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2807 FREE (the_printed_command_except_trap
);
2808 the_printed_command_except_trap
= savestring (the_printed_command
);
2811 retval
= run_debug_trap ();
2812 #if defined (DEBUGGER)
2813 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2814 skip the command. */
2815 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2816 return (EXECUTION_SUCCESS
);
2820 identifier
= select_command
->name
->word
;
2822 /* command and arithmetic substitution, parameter and variable expansion,
2823 word splitting, pathname expansion, and quote removal. */
2824 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
2825 list_len
= list_length (list
);
2826 if (list
== 0 || list_len
== 0)
2829 dispose_words (list
);
2830 line_number
= save_line_number
;
2831 return (EXECUTION_SUCCESS
);
2834 begin_unwind_frame ("select");
2835 add_unwind_protect (dispose_words
, releaser
);
2837 if (select_command
->flags
& CMD_IGNORE_RETURN
)
2838 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2840 retval
= EXECUTION_SUCCESS
;
2845 line_number
= select_command
->line
;
2846 ps3_prompt
= get_string_value ("PS3");
2847 if (ps3_prompt
== 0)
2851 selection
= select_query (list
, list_len
, ps3_prompt
, show_menu
);
2855 /* select_query returns EXECUTION_FAILURE if the read builtin
2856 fails, so we want to return failure in this case. */
2857 retval
= EXECUTION_FAILURE
;
2861 v
= bind_variable (identifier
, selection
, 0);
2862 if (readonly_p (v
) || noassign_p (v
))
2864 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2866 last_command_exit_value
= EXECUTION_FAILURE
;
2867 jump_to_top_level (FORCE_EOF
);
2871 dispose_words (releaser
);
2872 discard_unwind_frame ("select");
2874 line_number
= save_line_number
;
2875 return (EXECUTION_FAILURE
);
2879 retval
= execute_command (select_command
->action
);
2897 #if defined (KSH_COMPATIBLE_SELECT)
2899 selection
= get_string_value ("REPLY");
2900 if (selection
&& *selection
== '\0')
2906 line_number
= save_line_number
;
2908 dispose_words (releaser
);
2909 discard_unwind_frame ("select");
2912 #endif /* SELECT_COMMAND */
2914 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2915 The pattern_list is a linked list of pattern clauses; each clause contains
2916 some patterns to compare word_desc against, and an associated command to
2919 execute_case_command (case_command
)
2920 CASE_COM
*case_command
;
2922 register WORD_LIST
*list
;
2923 WORD_LIST
*wlist
, *es
;
2924 PATTERN_LIST
*clauses
;
2925 char *word
, *pattern
;
2926 int retval
, match
, ignore_return
, save_line_number
;
2928 save_line_number
= line_number
;
2929 line_number
= case_command
->line
;
2931 command_string_index
= 0;
2932 print_case_command_head (case_command
);
2934 if (echo_command_at_execute
)
2935 xtrace_print_case_command_head (case_command
);
2938 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2940 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2943 FREE (the_printed_command_except_trap
);
2944 the_printed_command_except_trap
= savestring (the_printed_command
);
2947 retval
= run_debug_trap();
2948 #if defined (DEBUGGER)
2949 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2950 skip the command. */
2951 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2953 line_number
= save_line_number
;
2954 return (EXECUTION_SUCCESS
);
2958 wlist
= expand_word_unsplit (case_command
->word
, 0);
2959 word
= wlist
? string_list (wlist
) : savestring ("");
2960 dispose_words (wlist
);
2962 retval
= EXECUTION_SUCCESS
;
2963 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
2965 begin_unwind_frame ("case");
2966 add_unwind_protect ((Function
*)xfree
, word
);
2968 #define EXIT_CASE() goto exit_case_command
2970 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
2973 for (list
= clauses
->patterns
; list
; list
= list
->next
)
2975 es
= expand_word_leave_quoted (list
->word
, 0);
2977 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
2978 pattern
= quote_string_for_globbing (es
->word
->word
, QGLOB_CVTNULL
);
2981 pattern
= (char *)xmalloc (1);
2985 /* Since the pattern does not undergo quote removal (as per
2986 Posix.2, section 3.9.4.3), the strmatch () call must be able
2987 to recognize backslashes as escape characters. */
2988 match
= strmatch (pattern
, word
, FNMATCH_EXTFLAG
|FNMATCH_IGNCASE
) != FNM_NOMATCH
;
2997 if (clauses
->action
&& ignore_return
)
2998 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
2999 retval
= execute_command (clauses
->action
);
3001 while ((clauses
->flags
& CASEPAT_FALLTHROUGH
) && (clauses
= clauses
->next
));
3002 if (clauses
== 0 || (clauses
->flags
& CASEPAT_TESTNEXT
) == 0)
3014 discard_unwind_frame ("case");
3015 line_number
= save_line_number
;
3022 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3023 Repeatedly execute action while executing test produces
3024 EXECUTION_SUCCESS. */
3026 execute_while_command (while_command
)
3027 WHILE_COM
*while_command
;
3029 return (execute_while_or_until (while_command
, CMD_WHILE
));
3032 /* UNTIL is just like WHILE except that the test result is negated. */
3034 execute_until_command (while_command
)
3035 WHILE_COM
*while_command
;
3037 return (execute_while_or_until (while_command
, CMD_UNTIL
));
3040 /* The body for both while and until. The only difference between the
3041 two is that the test value is treated differently. TYPE is
3042 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3043 be EXECUTION_SUCCESS if no commands in the body are executed, and
3044 the status of the last command executed in the body otherwise. */
3046 execute_while_or_until (while_command
, type
)
3047 WHILE_COM
*while_command
;
3050 int return_value
, body_status
;
3052 body_status
= EXECUTION_SUCCESS
;
3055 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
3056 if (while_command
->flags
& CMD_IGNORE_RETURN
)
3057 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
3061 return_value
= execute_command (while_command
->test
);
3064 /* Need to handle `break' in the test when we would break out of the
3065 loop. The job control code will set `breaking' to loop_level
3066 when a job in a loop is stopped with SIGTSTP. If the stopped job
3067 is in the loop test, `breaking' will not be reset unless we do
3068 this, and the shell will cease to execute commands. */
3069 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
3075 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
3083 body_status
= execute_command (while_command
->action
);
3101 return (body_status
);
3104 /* IF test THEN command [ELSE command].
3105 IF also allows ELIF in the place of ELSE IF, but
3106 the parser makes *that* stupidity transparent. */
3108 execute_if_command (if_command
)
3111 int return_value
, save_line_number
;
3113 save_line_number
= line_number
;
3114 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
3115 return_value
= execute_command (if_command
->test
);
3116 line_number
= save_line_number
;
3118 if (return_value
== EXECUTION_SUCCESS
)
3122 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
3123 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
3125 return (execute_command (if_command
->true_case
));
3131 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
3132 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
3134 return (execute_command (if_command
->false_case
));
3138 #if defined (DPAREN_ARITHMETIC)
3140 execute_arith_command (arith_command
)
3141 ARITH_COM
*arith_command
;
3143 int expok
, save_line_number
, retval
;
3150 save_line_number
= line_number
;
3151 this_command_name
= "(("; /* )) */
3152 line_number
= arith_command
->line
;
3153 /* If we're in a function, update the line number information. */
3154 if (variable_context
&& interactive_shell
)
3155 line_number
-= function_line_number
;
3157 command_string_index
= 0;
3158 print_arith_command (arith_command
->exp
);
3160 if (signal_in_progress (DEBUG_TRAP
) == 0)
3162 FREE (the_printed_command_except_trap
);
3163 the_printed_command_except_trap
= savestring (the_printed_command
);
3166 /* Run the debug trap before each arithmetic command, but do it after we
3167 update the line number information and before we expand the various
3168 words in the expression. */
3169 retval
= run_debug_trap ();
3170 #if defined (DEBUGGER)
3171 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3172 skip the command. */
3173 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3175 line_number
= save_line_number
;
3176 return (EXECUTION_SUCCESS
);
3180 new = expand_words_no_vars (arith_command
->exp
);
3182 /* If we're tracing, make a new word list with `((' at the front and `))'
3183 at the back and print it. */
3184 if (echo_command_at_execute
)
3185 xtrace_print_arith_cmd (new);
3189 exp
= new->next
? string_list (new) : new->word
->word
;
3190 expresult
= evalexp (exp
, &expok
);
3191 line_number
= save_line_number
;
3192 if (exp
!= new->word
->word
)
3194 dispose_words (new);
3203 return (EXECUTION_FAILURE
);
3205 return (expresult
== 0 ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
3207 #endif /* DPAREN_ARITHMETIC */
3209 #if defined (COND_COMMAND)
3211 static char * const nullstr
= "";
3214 execute_cond_node (cond
)
3217 int result
, invert
, patmatch
, rmatch
, mflags
, ignore
;
3220 invert
= (cond
->flags
& CMD_INVERT_RETURN
);
3221 ignore
= (cond
->flags
& CMD_IGNORE_RETURN
);
3225 cond
->left
->flags
|= CMD_IGNORE_RETURN
;
3227 cond
->right
->flags
|= CMD_IGNORE_RETURN
;
3230 if (cond
->type
== COND_EXPR
)
3231 result
= execute_cond_node (cond
->left
);
3232 else if (cond
->type
== COND_OR
)
3234 result
= execute_cond_node (cond
->left
);
3235 if (result
!= EXECUTION_SUCCESS
)
3236 result
= execute_cond_node (cond
->right
);
3238 else if (cond
->type
== COND_AND
)
3240 result
= execute_cond_node (cond
->left
);
3241 if (result
== EXECUTION_SUCCESS
)
3242 result
= execute_cond_node (cond
->right
);
3244 else if (cond
->type
== COND_UNARY
)
3247 comsub_ignore_return
++;
3248 arg1
= cond_expand_word (cond
->left
->op
, 0);
3250 comsub_ignore_return
--;
3253 if (echo_command_at_execute
)
3254 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, (char *)NULL
);
3255 result
= unary_test (cond
->op
->word
, arg1
) ? EXECUTION_SUCCESS
: EXECUTION_FAILURE
;
3256 if (arg1
!= nullstr
)
3259 else if (cond
->type
== COND_BINARY
)
3262 patmatch
= ((cond
->op
->word
[1] == '=') && (cond
->op
->word
[2] == '\0') &&
3263 (cond
->op
->word
[0] == '!' || cond
->op
->word
[0] == '=') ||
3264 (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '\0'));
3265 #if defined (COND_REGEXP)
3266 rmatch
= (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '~' &&
3267 cond
->op
->word
[2] == '\0');
3271 comsub_ignore_return
++;
3272 arg1
= cond_expand_word (cond
->left
->op
, 0);
3274 comsub_ignore_return
--;
3278 comsub_ignore_return
++;
3279 arg2
= cond_expand_word (cond
->right
->op
,
3280 (rmatch
&& shell_compatibility_level
> 31) ? 2 : (patmatch
? 1 : 0));
3282 comsub_ignore_return
--;
3286 if (echo_command_at_execute
)
3287 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, arg2
);
3289 #if defined (COND_REGEXP)
3292 mflags
= SHMAT_PWARN
;
3293 #if defined (ARRAY_VARS)
3294 mflags
|= SHMAT_SUBEXP
;
3297 result
= sh_regmatch (arg1
, arg2
, mflags
);
3300 #endif /* COND_REGEXP */
3305 result
= binary_test (cond
->op
->word
, arg1
, arg2
, TEST_PATMATCH
|TEST_ARITHEXP
|TEST_LOCALE
)
3307 : EXECUTION_FAILURE
;
3310 if (arg1
!= nullstr
)
3312 if (arg2
!= nullstr
)
3317 command_error ("execute_cond_node", CMDERR_BADTYPE
, cond
->type
, 0);
3318 jump_to_top_level (DISCARD
);
3319 result
= EXECUTION_FAILURE
;
3323 result
= (result
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
;
3329 execute_cond_command (cond_command
)
3330 COND_COM
*cond_command
;
3332 int retval
, save_line_number
;
3334 retval
= EXECUTION_SUCCESS
;
3335 save_line_number
= line_number
;
3337 this_command_name
= "[[";
3338 line_number
= cond_command
->line
;
3339 /* If we're in a function, update the line number information. */
3340 if (variable_context
&& interactive_shell
)
3341 line_number
-= function_line_number
;
3342 command_string_index
= 0;
3343 print_cond_command (cond_command
);
3345 if (signal_in_progress (DEBUG_TRAP
) == 0)
3347 FREE (the_printed_command_except_trap
);
3348 the_printed_command_except_trap
= savestring (the_printed_command
);
3351 /* Run the debug trap before each conditional command, but do it after we
3352 update the line number information. */
3353 retval
= run_debug_trap ();
3354 #if defined (DEBUGGER)
3355 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3356 skip the command. */
3357 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3359 line_number
= save_line_number
;
3360 return (EXECUTION_SUCCESS
);
3365 debug_print_cond_command (cond_command
);
3368 last_command_exit_value
= retval
= execute_cond_node (cond_command
);
3369 line_number
= save_line_number
;
3372 #endif /* COND_COMMAND */
3382 var
= bind_variable ("_", arg
, 0);
3383 VUNSETATTR (var
, att_exported
);
3386 /* Execute a null command. Fork a subshell if the command uses pipes or is
3387 to be run asynchronously. This handles all the side effects that are
3388 supposed to take place. */
3390 execute_null_command (redirects
, pipe_in
, pipe_out
, async
)
3391 REDIRECT
*redirects
;
3392 int pipe_in
, pipe_out
, async
;
3398 for (forcefork
= 0, rd
= redirects
; rd
; rd
= rd
->next
)
3399 forcefork
+= rd
->rflags
& REDIR_VARASSIGN
;
3401 if (forcefork
|| pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
3403 /* We have a null command, but we really want a subshell to take
3404 care of it. Just fork, do piping and redirections, and exit. */
3405 if (make_child ((char *)NULL
, async
) == 0)
3407 /* Cancel traps, in trap.c. */
3408 restore_original_signals (); /* XXX */
3410 do_piping (pipe_in
, pipe_out
);
3412 #if defined (COPROCESS_SUPPORT)
3416 subshell_environment
= 0;
3418 subshell_environment
|= SUBSHELL_ASYNC
;
3419 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3420 subshell_environment
|= SUBSHELL_PIPE
;
3422 if (do_redirections (redirects
, RX_ACTIVE
) == 0)
3423 exit (EXECUTION_SUCCESS
);
3425 exit (EXECUTION_FAILURE
);
3429 close_pipes (pipe_in
, pipe_out
);
3430 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3431 unlink_fifo_list ();
3433 return (EXECUTION_SUCCESS
);
3438 /* Even if there aren't any command names, pretend to do the
3439 redirections that are specified. The user expects the side
3440 effects to take place. If the redirections fail, then return
3441 failure. Otherwise, if a command substitution took place while
3442 expanding the command or a redirection, return the value of that
3443 substitution. Otherwise, return EXECUTION_SUCCESS. */
3445 r
= do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
);
3446 cleanup_redirects (redirection_undo_list
);
3447 redirection_undo_list
= (REDIRECT
*)NULL
;
3450 return (EXECUTION_FAILURE
);
3451 else if (last_command_subst_pid
!= NO_PID
)
3452 return (last_command_exit_value
);
3454 return (EXECUTION_SUCCESS
);
3458 /* This is a hack to suppress word splitting for assignment statements
3459 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3461 fix_assignment_words (words
)
3474 for (w
= words
; w
; w
= w
->next
)
3475 if (w
->word
->flags
& W_ASSIGNMENT
)
3479 b
= builtin_address_internal (words
->word
->word
, 0);
3480 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3482 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3483 words
->word
->flags
|= W_ASSNBLTIN
;
3485 w
->word
->flags
|= (W_NOSPLIT
|W_NOGLOB
|W_TILDEEXP
|W_ASSIGNARG
);
3486 #if defined (ARRAY_VARS)
3488 w
->word
->flags
|= W_ASSIGNASSOC
;
3491 #if defined (ARRAY_VARS)
3492 /* Note that we saw an associative array option to a builtin that takes
3493 assignment statements. This is a bit of a kludge. */
3494 else if (w
->word
->word
[0] == '-' && strchr (w
->word
->word
, 'A'))
3498 b
= builtin_address_internal (words
->word
->word
, 0);
3499 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3501 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3502 words
->word
->flags
|= W_ASSNBLTIN
;
3504 if (words
->word
->flags
& W_ASSNBLTIN
)
3510 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3511 to PATHNAME, is a directory. Used by the autocd code below. */
3513 is_dirname (pathname
)
3517 temp
= search_for_command (pathname
);
3518 return (temp
? file_isdir (temp
) : file_isdir (pathname
));
3521 /* The meaty part of all the executions. We have to start hacking the
3522 real execution of commands here. Fork a process, set things up,
3523 execute the command. */
3525 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
3526 SIMPLE_COM
*simple_command
;
3527 int pipe_in
, pipe_out
, async
;
3528 struct fd_bitmap
*fds_to_close
;
3530 WORD_LIST
*words
, *lastword
;
3531 char *command_line
, *lastarg
, *temp
;
3532 int first_word_quoted
, result
, builtin_is_special
, already_forked
, dofork
;
3533 pid_t old_last_async_pid
;
3534 sh_builtin_func_t
*builtin
;
3537 result
= EXECUTION_SUCCESS
;
3538 special_builtin_failed
= builtin_is_special
= 0;
3539 command_line
= (char *)0;
3541 /* If we're in a function, update the line number information. */
3542 if (variable_context
&& interactive_shell
&& sourcelevel
== 0)
3543 line_number
-= function_line_number
;
3545 /* Remember what this command line looks like at invocation. */
3546 command_string_index
= 0;
3547 print_simple_command (simple_command
);
3550 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3552 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3555 FREE (the_printed_command_except_trap
);
3556 the_printed_command_except_trap
= the_printed_command
? savestring (the_printed_command
) : (char *)0;
3559 /* Run the debug trap before each simple command, but do it after we
3560 update the line number information. */
3561 result
= run_debug_trap ();
3562 #if defined (DEBUGGER)
3563 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3564 skip the command. */
3565 if (debugging_mode
&& result
!= EXECUTION_SUCCESS
)
3566 return (EXECUTION_SUCCESS
);
3570 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
) : 0;
3572 last_command_subst_pid
= NO_PID
;
3573 old_last_async_pid
= last_asynchronous_pid
;
3575 already_forked
= dofork
= 0;
3577 /* If we're in a pipeline or run in the background, set DOFORK so we
3578 make the child early, before word expansion. This keeps assignment
3579 statements from affecting the parent shell's environment when they
3581 dofork
= pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
;
3583 /* Something like `%2 &' should restart job 2 in the background, not cause
3584 the shell to fork here. */
3585 if (dofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&&
3586 simple_command
->words
&& simple_command
->words
->word
&&
3587 simple_command
->words
->word
->word
&&
3588 (simple_command
->words
->word
->word
[0] == '%'))
3593 /* Do this now, because execute_disk_command will do it anyway in the
3594 vast majority of cases. */
3595 maybe_make_export_env ();
3597 /* Don't let a DEBUG trap overwrite the command string to be saved with
3598 the process/job associated with this child. */
3599 if (make_child (savestring (the_printed_command_except_trap
), async
) == 0)
3602 simple_command
->flags
|= CMD_NO_FORK
;
3604 subshell_environment
= SUBSHELL_FORK
;
3605 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3606 subshell_environment
|= SUBSHELL_PIPE
;
3608 subshell_environment
|= SUBSHELL_ASYNC
;
3610 /* We need to do this before piping to handle some really
3611 pathological cases where one of the pipe file descriptors
3614 close_fd_bitmap (fds_to_close
);
3616 do_piping (pipe_in
, pipe_out
);
3617 pipe_in
= pipe_out
= NO_PIPE
;
3618 #if defined (COPROCESS_SUPPORT)
3622 last_asynchronous_pid
= old_last_async_pid
;
3626 close_pipes (pipe_in
, pipe_out
);
3627 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3628 unlink_fifo_list ();
3630 command_line
= (char *)NULL
; /* don't free this. */
3631 bind_lastarg ((char *)NULL
);
3636 /* If we are re-running this as the result of executing the `command'
3637 builtin, do not expand the command words a second time. */
3638 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
3640 current_fds_to_close
= fds_to_close
;
3641 fix_assignment_words (simple_command
->words
);
3642 /* Pass the ignore return flag down to command substitutions */
3643 if (simple_command
->flags
& CMD_IGNORE_RETURN
) /* XXX */
3644 comsub_ignore_return
++;
3645 words
= expand_words (simple_command
->words
);
3646 if (simple_command
->flags
& CMD_IGNORE_RETURN
)
3647 comsub_ignore_return
--;
3648 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
3651 words
= copy_word_list (simple_command
->words
);
3653 /* It is possible for WORDS not to have anything left in it.
3654 Perhaps all the words consisted of `$foo', and there was
3655 no variable `$foo'. */
3658 this_command_name
= 0;
3659 result
= execute_null_command (simple_command
->redirects
,
3661 already_forked
? 0 : async
);
3666 bind_lastarg ((char *)NULL
);
3667 set_pipestatus_from_exit (result
);
3672 lastarg
= (char *)NULL
;
3674 begin_unwind_frame ("simple-command");
3676 if (echo_command_at_execute
)
3677 xtrace_print_word_list (words
, 1);
3679 builtin
= (sh_builtin_func_t
*)NULL
;
3680 func
= (SHELL_VAR
*)NULL
;
3681 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
3683 /* Posix.2 says special builtins are found before functions. We
3684 don't set builtin_is_special anywhere other than here, because
3685 this path is followed only when the `command' builtin is *not*
3686 being used, and we don't want to exit the shell if a special
3687 builtin executed with `command builtin' fails. `command' is not
3688 a special builtin. */
3689 if (posixly_correct
)
3691 builtin
= find_special_builtin (words
->word
->word
);
3693 builtin_is_special
= 1;
3696 func
= find_function (words
->word
->word
);
3699 /* In POSIX mode, assignment errors in the temporary environment cause a
3700 non-interactive shell to exit. */
3701 if (builtin_is_special
&& interactive_shell
== 0 && tempenv_assign_error
)
3703 last_command_exit_value
= EXECUTION_FAILURE
;
3704 jump_to_top_level (ERREXIT
);
3707 add_unwind_protect (dispose_words
, words
);
3710 /* Bind the last word in this command to "$_" after execution. */
3711 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
3713 lastarg
= lastword
->word
->word
;
3715 #if defined (JOB_CONTROL)
3716 /* Is this command a job control related thing? */
3717 if (words
->word
->word
[0] == '%' && already_forked
== 0)
3719 this_command_name
= async
? "bg" : "fg";
3720 last_shell_builtin
= this_shell_builtin
;
3721 this_shell_builtin
= builtin_address (this_command_name
);
3722 result
= (*this_shell_builtin
) (words
);
3726 /* One other possiblilty. The user may want to resume an existing job.
3727 If they do, find out whether this word is a candidate for a running
3729 if (job_control
&& already_forked
== 0 && async
== 0 &&
3730 !first_word_quoted
&&
3732 words
->word
->word
[0] &&
3733 !simple_command
->redirects
&&
3734 pipe_in
== NO_PIPE
&&
3735 pipe_out
== NO_PIPE
&&
3736 (temp
= get_string_value ("auto_resume")))
3738 int job
, jflags
, started_status
;
3740 jflags
= JM_STOPPED
|JM_FIRSTMATCH
;
3741 if (STREQ (temp
, "exact"))
3743 else if (STREQ (temp
, "substring"))
3744 jflags
|= JM_SUBSTRING
;
3746 jflags
|= JM_PREFIX
;
3747 job
= get_job_by_name (words
->word
->word
, jflags
);
3750 run_unwind_frame ("simple-command");
3751 this_command_name
= "fg";
3752 last_shell_builtin
= this_shell_builtin
;
3753 this_shell_builtin
= builtin_address ("fg");
3755 started_status
= start_job (job
, 1);
3756 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
3759 #endif /* JOB_CONTROL */
3762 /* Remember the name of this command globally. */
3763 this_command_name
= words
->word
->word
;
3767 /* This command could be a shell builtin or a user-defined function.
3768 We have already found special builtins by this time, so we do not
3769 set builtin_is_special. If this is a function or builtin, and we
3770 have pipes, then fork a subshell in here. Otherwise, just execute
3771 the command directly. */
3772 if (func
== 0 && builtin
== 0)
3773 builtin
= find_shell_builtin (this_command_name
);
3775 last_shell_builtin
= this_shell_builtin
;
3776 this_shell_builtin
= builtin
;
3778 if (builtin
|| func
)
3781 unwind_protect_int (executing_builtin
); /* modified in execute_builtin */
3784 /* reset_terminating_signals (); */ /* XXX */
3785 /* Cancel traps, in trap.c. */
3786 restore_original_signals ();
3790 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
3791 pipe_in
== NO_PIPE
&&
3792 (stdin_redirects (simple_command
->redirects
) == 0))
3793 async_redirect_stdin ();
3794 setup_async_signals ();
3798 execute_subshell_builtin_or_function
3799 (words
, simple_command
->redirects
, builtin
, func
,
3800 pipe_in
, pipe_out
, async
, fds_to_close
,
3801 simple_command
->flags
);
3806 result
= execute_builtin_or_function
3807 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
3808 simple_command
->flags
);
3811 if (result
> EX_SHERRBASE
)
3813 result
= builtin_status (result
);
3814 if (builtin_is_special
)
3815 special_builtin_failed
= 1;
3817 /* In POSIX mode, if there are assignment statements preceding
3818 a special builtin, they persist after the builtin
3820 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
3821 merge_temporary_env ();
3825 if (result
== EX_USAGE
)
3826 result
= EX_BADUSAGE
;
3827 else if (result
> EX_SHERRBASE
)
3828 result
= EXECUTION_FAILURE
;
3831 set_pipestatus_from_exit (result
);
3837 if (autocd
&& interactive
&& words
->word
&& is_dirname (words
->word
->word
))
3839 words
= make_word_list (make_word ("cd"), words
);
3840 xtrace_print_word_list (words
, 0);
3844 if (command_line
== 0)
3845 command_line
= savestring (the_printed_command_except_trap
);
3847 #if defined (PROCESS_SUBSTITUTION)
3848 if ((subshell_environment
& SUBSHELL_COMSUB
) && (simple_command
->flags
& CMD_NO_FORK
) && fifos_pending() > 0)
3849 simple_command
->flags
&= ~CMD_NO_FORK
;
3852 execute_disk_command (words
, simple_command
->redirects
, command_line
,
3853 pipe_in
, pipe_out
, async
, fds_to_close
,
3854 simple_command
->flags
);
3857 bind_lastarg (lastarg
);
3858 FREE (command_line
);
3859 dispose_words (words
);
3860 discard_unwind_frame ("simple-command");
3861 this_command_name
= (char *)NULL
; /* points to freed memory now */
3865 /* Translate the special builtin exit statuses. We don't really need a
3866 function for this; it's a placeholder for future work. */
3868 builtin_status (result
)
3882 r
= EXECUTION_FAILURE
;
3885 r
= EXECUTION_SUCCESS
;
3892 execute_builtin (builtin
, words
, flags
, subshell
)
3893 sh_builtin_func_t
*builtin
;
3895 int flags
, subshell
;
3897 int old_e_flag
, result
, eval_unwind
;
3902 /* XXX -- added 12/11 */
3903 terminate_immediately
++;
3907 old_e_flag
= exit_immediately_on_error
;
3908 /* The eval builtin calls parse_and_execute, which does not know about
3909 the setting of flags, and always calls the execution functions with
3910 flags that will exit the shell on an error if -e is set. If the
3911 eval builtin is being called, and we're supposed to ignore the exit
3912 value of the command, we turn the -e flag off ourselves and disable
3913 the ERR trap, then restore them when the command completes. This is
3914 also a problem (as below) for the command and source/. builtins. */
3915 if (subshell
== 0 && (flags
& CMD_IGNORE_RETURN
) &&
3916 (builtin
== eval_builtin
|| builtin
== command_builtin
|| builtin
== source_builtin
))
3918 begin_unwind_frame ("eval_builtin");
3919 unwind_protect_int (exit_immediately_on_error
);
3920 error_trap
= TRAP_STRING (ERROR_TRAP
);
3923 error_trap
= savestring (error_trap
);
3924 add_unwind_protect (xfree
, error_trap
);
3925 add_unwind_protect (set_error_trap
, error_trap
);
3926 restore_default_signal (ERROR_TRAP
);
3928 exit_immediately_on_error
= 0;
3934 /* The temporary environment for a builtin is supposed to apply to
3935 all commands executed by that builtin. Currently, this is a
3936 problem only with the `unset', `source' and `eval' builtins. */
3938 isbltinenv
= (builtin
== source_builtin
|| builtin
== eval_builtin
|| builtin
== unset_builtin
);
3943 begin_unwind_frame ("builtin_env");
3947 push_scope (VC_BLTNENV
, temporary_env
);
3949 add_unwind_protect (pop_scope
, (flags
& CMD_COMMAND_BUILTIN
) ? 0 : "1");
3950 temporary_env
= (HASH_TABLE
*)NULL
;
3954 /* `return' does a longjmp() back to a saved environment in execute_function.
3955 If a variable assignment list preceded the command, and the shell is
3956 running in POSIX mode, we need to merge that into the shell_variables
3957 table, since `return' is a POSIX special builtin. */
3958 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3960 begin_unwind_frame ("return_temp_env");
3961 add_unwind_protect (merge_temporary_env
, (char *)NULL
);
3964 executing_builtin
++;
3965 result
= ((*builtin
) (words
->next
));
3967 /* This shouldn't happen, but in case `return' comes back instead of
3968 longjmp'ing, we need to unwind. */
3969 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3970 discard_unwind_frame ("return_temp_env");
3972 if (subshell
== 0 && isbltinenv
)
3973 run_unwind_frame ("builtin_env");
3977 exit_immediately_on_error
+= old_e_flag
;
3980 set_error_trap (error_trap
);
3983 discard_unwind_frame ("eval_builtin");
3987 /* XXX -- added 12/11 */
3988 terminate_immediately
--;
3995 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
3999 struct fd_bitmap
*fds_to_close
;
4000 int async
, subshell
;
4002 int return_val
, result
;
4003 COMMAND
*tc
, *fc
, *save_current
;
4004 char *debug_trap
, *error_trap
, *return_trap
;
4005 #if defined (ARRAY_VARS)
4006 SHELL_VAR
*funcname_v
, *nfv
, *bash_source_v
, *bash_lineno_v
;
4007 ARRAY
*funcname_a
, *bash_source_a
, *bash_lineno_a
;
4009 FUNCTION_DEF
*shell_fn
;
4014 #if 0 /* for bash-4.2 */
4015 if (funcnest_max
> 0 && funcnest
>= funcnest_max
)
4017 internal_error ("%s: maximum function nesting level exceeded (%d)", var
->name
, funcnest
);
4018 jump_to_top_level (DISCARD
);
4022 #if defined (ARRAY_VARS)
4023 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v
, funcname_a
);
4024 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v
, bash_source_a
);
4025 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v
, bash_lineno_a
);
4028 tc
= (COMMAND
*)copy_command (function_cell (var
));
4029 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
4030 tc
->flags
|= CMD_IGNORE_RETURN
;
4034 begin_unwind_frame ("function_calling");
4035 push_context (var
->name
, subshell
, temporary_env
);
4036 add_unwind_protect (pop_context
, (char *)NULL
);
4037 unwind_protect_int (line_number
);
4038 unwind_protect_int (return_catch_flag
);
4039 unwind_protect_jmp_buf (return_catch
);
4040 add_unwind_protect (dispose_command
, (char *)tc
);
4041 unwind_protect_pointer (this_shell_function
);
4042 unwind_protect_int (loop_level
);
4043 unwind_protect_int (funcnest
);
4046 push_context (var
->name
, subshell
, temporary_env
); /* don't unwind-protect for subshells */
4048 temporary_env
= (HASH_TABLE
*)NULL
;
4050 this_shell_function
= var
;
4051 make_funcname_visible (1);
4053 debug_trap
= TRAP_STRING(DEBUG_TRAP
);
4054 error_trap
= TRAP_STRING(ERROR_TRAP
);
4055 return_trap
= TRAP_STRING(RETURN_TRAP
);
4057 /* The order of the unwind protects for debug_trap, error_trap and
4058 return_trap is important here! unwind-protect commands are run
4059 in reverse order of registration. If this causes problems, take
4060 out the xfree unwind-protect calls and live with the small memory leak. */
4062 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4063 if the function has the trace attribute set, it inherits the DEBUG trap */
4064 if (debug_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
4068 debug_trap
= savestring (debug_trap
);
4069 add_unwind_protect (xfree
, debug_trap
);
4070 add_unwind_protect (set_debug_trap
, debug_trap
);
4072 restore_default_signal (DEBUG_TRAP
);
4075 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4076 if (error_trap
&& error_trace_mode
== 0)
4080 error_trap
= savestring (error_trap
);
4081 add_unwind_protect (xfree
, error_trap
);
4082 add_unwind_protect (set_error_trap
, error_trap
);
4084 restore_default_signal (ERROR_TRAP
);
4087 /* Shell functions inherit the RETURN trap if function tracing is on
4088 globally or on individually for this function. */
4090 if (return_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
4092 if (return_trap
&& (signal_in_progress (DEBUG_TRAP
) || ((trace_p (var
) == 0) && function_trace_mode
== 0)))
4097 return_trap
= savestring (return_trap
);
4098 add_unwind_protect (xfree
, return_trap
);
4099 add_unwind_protect (set_return_trap
, return_trap
);
4101 restore_default_signal (RETURN_TRAP
);
4105 #if defined (ARRAY_VARS)
4106 /* This is quite similar to the code in shell.c and elsewhere. */
4107 shell_fn
= find_function_def (this_shell_function
->name
);
4108 sfile
= shell_fn
? shell_fn
->source_file
: "";
4109 array_push (funcname_a
, this_shell_function
->name
);
4111 array_push (bash_source_a
, sfile
);
4112 t
= itos (executing_line_number ());
4113 array_push (bash_lineno_a
, t
);
4117 /* The temporary environment for a function is supposed to apply to
4118 all commands executed within the function body. */
4120 remember_args (words
->next
, 1);
4122 /* Update BASH_ARGV and BASH_ARGC */
4124 push_args (words
->next
);
4126 /* Number of the line on which the function body starts. */
4127 line_number
= function_line_number
= tc
->line
;
4129 #if defined (JOB_CONTROL)
4131 stop_pipeline (async
, (COMMAND
*)NULL
);
4136 return_catch_flag
++;
4137 return_val
= setjmp (return_catch
);
4141 result
= return_catch_value
;
4142 /* Run the RETURN trap in the function's context. */
4143 save_current
= currently_executing_command
;
4145 currently_executing_command
= save_current
;
4149 /* Run the debug trap here so we can trap at the start of a function's
4150 execution rather than the execution of the body's first command. */
4151 showing_function_line
= 1;
4152 save_current
= currently_executing_command
;
4153 result
= run_debug_trap ();
4154 #if defined (DEBUGGER)
4155 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4156 skip the command. */
4157 if (debugging_mode
== 0 || result
== EXECUTION_SUCCESS
)
4159 showing_function_line
= 0;
4160 currently_executing_command
= save_current
;
4161 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
4163 /* Run the RETURN trap in the function's context */
4164 save_current
= currently_executing_command
;
4166 currently_executing_command
= save_current
;
4169 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
4171 save_current
= currently_executing_command
;
4173 currently_executing_command
= save_current
;
4175 showing_function_line
= 0;
4178 /* Restore BASH_ARGC and BASH_ARGV */
4183 run_unwind_frame ("function_calling");
4185 #if defined (ARRAY_VARS)
4186 /* These two variables cannot be unset, and cannot be affected by the
4188 array_pop (bash_source_a
);
4189 array_pop (bash_lineno_a
);
4191 /* FUNCNAME can be unset, and so can potentially be changed by the
4193 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv
, funcname_a
);
4194 if (nfv
== funcname_v
)
4195 array_pop (funcname_a
);
4198 if (variable_context
== 0 || this_shell_function
== 0)
4200 make_funcname_visible (0);
4201 #if defined (PROCESS_SUBSTITUTION)
4202 unlink_fifo_list ();
4209 /* A convenience routine for use by other parts of the shell to execute
4210 a particular shell function. */
4212 execute_shell_function (var
, words
)
4217 struct fd_bitmap
*bitmap
;
4219 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
4220 begin_unwind_frame ("execute-shell-function");
4221 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
4223 ret
= execute_function (var
, words
, 0, bitmap
, 0, 0);
4225 dispose_fd_bitmap (bitmap
);
4226 discard_unwind_frame ("execute-shell-function");
4231 /* Execute a shell builtin or function in a subshell environment. This
4232 routine does not return; it only calls exit(). If BUILTIN is non-null,
4233 it points to a function to call to execute a shell builtin; otherwise
4234 VAR points at the body of a function to execute. WORDS is the arguments
4235 to the command, REDIRECTS specifies redirections to perform before the
4236 command is executed. */
4238 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
4239 pipe_in
, pipe_out
, async
, fds_to_close
,
4242 REDIRECT
*redirects
;
4243 sh_builtin_func_t
*builtin
;
4245 int pipe_in
, pipe_out
, async
;
4246 struct fd_bitmap
*fds_to_close
;
4249 int result
, r
, funcvalue
;
4250 #if defined (JOB_CONTROL)
4253 jobs_hack
= (builtin
== jobs_builtin
) &&
4254 ((subshell_environment
& SUBSHELL_ASYNC
) == 0 || pipe_out
!= NO_PIPE
);
4257 /* A subshell is neither a login shell nor interactive. */
4258 login_shell
= interactive
= 0;
4261 subshell_environment
|= SUBSHELL_ASYNC
;
4262 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4263 subshell_environment
|= SUBSHELL_PIPE
;
4265 maybe_make_export_env (); /* XXX - is this needed? */
4267 #if defined (JOB_CONTROL)
4268 /* Eradicate all traces of job control after we fork the subshell, so
4269 all jobs begun by this subshell are in the same process group as
4270 the shell itself. */
4272 /* Allow the output of `jobs' to be piped. */
4274 kill_current_pipeline ();
4276 without_job_control ();
4278 set_sigchld_handler ();
4279 #endif /* JOB_CONTROL */
4281 set_sigint_handler ();
4284 close_fd_bitmap (fds_to_close
);
4286 do_piping (pipe_in
, pipe_out
);
4288 if (do_redirections (redirects
, RX_ACTIVE
) != 0)
4289 exit (EXECUTION_FAILURE
);
4293 /* Give builtins a place to jump back to on failure,
4294 so we don't go back up to main(). */
4295 result
= setjmp (top_level
);
4297 /* Give the return builtin a place to jump to when executed in a subshell
4300 if (return_catch_flag
&& builtin
== return_builtin
)
4301 funcvalue
= setjmp (return_catch
);
4303 if (result
== EXITPROG
)
4304 exit (last_command_exit_value
);
4306 exit (EXECUTION_FAILURE
);
4308 exit (return_catch_value
);
4311 r
= execute_builtin (builtin
, words
, flags
, 1);
4320 r
= execute_function (var
, words
, flags
, fds_to_close
, async
, 1);
4326 /* Execute a builtin or function in the current shell context. If BUILTIN
4327 is non-null, it is the builtin command to execute, otherwise VAR points
4328 to the body of a function. WORDS are the command's arguments, REDIRECTS
4329 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4330 file descriptors to close.
4332 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4333 not undone before this function returns. */
4335 execute_builtin_or_function (words
, builtin
, var
, redirects
,
4336 fds_to_close
, flags
)
4338 sh_builtin_func_t
*builtin
;
4340 REDIRECT
*redirects
;
4341 struct fd_bitmap
*fds_to_close
;
4345 REDIRECT
*saved_undo_list
;
4346 sh_builtin_func_t
*saved_this_shell_builtin
;
4348 if (do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
4350 cleanup_redirects (redirection_undo_list
);
4351 redirection_undo_list
= (REDIRECT
*)NULL
;
4352 dispose_exec_redirects ();
4353 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
4356 saved_this_shell_builtin
= this_shell_builtin
;
4357 saved_undo_list
= redirection_undo_list
;
4359 /* Calling the "exec" builtin changes redirections forever. */
4360 if (builtin
== exec_builtin
)
4362 dispose_redirects (saved_undo_list
);
4363 saved_undo_list
= exec_redirection_undo_list
;
4364 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
4367 dispose_exec_redirects ();
4369 if (saved_undo_list
)
4371 begin_unwind_frame ("saved redirects");
4372 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
4375 redirection_undo_list
= (REDIRECT
*)NULL
;
4378 result
= execute_builtin (builtin
, words
, flags
, 0);
4380 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
4382 /* We do this before undoing the effects of any redirections. */
4385 if (ferror (stdout
))
4388 /* If we are executing the `command' builtin, but this_shell_builtin is
4389 set to `exec_builtin', we know that we have something like
4390 `command exec [redirection]', since otherwise `exec' would have
4391 overwritten the shell and we wouldn't get here. In this case, we
4392 want to behave as if the `command' builtin had not been specified
4393 and preserve the redirections. */
4394 if (builtin
== command_builtin
&& this_shell_builtin
== exec_builtin
)
4396 if (saved_undo_list
)
4397 dispose_redirects (saved_undo_list
);
4398 redirection_undo_list
= exec_redirection_undo_list
;
4399 saved_undo_list
= exec_redirection_undo_list
= (REDIRECT
*)NULL
;
4400 discard_unwind_frame ("saved_redirects");
4403 if (saved_undo_list
)
4405 redirection_undo_list
= saved_undo_list
;
4406 discard_unwind_frame ("saved redirects");
4409 if (redirection_undo_list
)
4411 cleanup_redirects (redirection_undo_list
);
4412 redirection_undo_list
= (REDIRECT
*)NULL
;
4419 setup_async_signals ()
4421 #if defined (__BEOS__)
4422 set_signal_handler (SIGHUP
, SIG_IGN
); /* they want csh-like behavior */
4425 #if defined (JOB_CONTROL)
4426 if (job_control
== 0)
4429 set_signal_handler (SIGINT
, SIG_IGN
);
4430 set_signal_ignored (SIGINT
);
4431 set_signal_handler (SIGQUIT
, SIG_IGN
);
4432 set_signal_ignored (SIGQUIT
);
4436 /* Execute a simple command that is hopefully defined in a disk file
4441 3) look up the command
4444 6) If the execve failed, see if the file has executable mode set.
4445 If so, and it isn't a directory, then execute its contents as
4448 Note that the filename hashing stuff has to take place up here,
4449 in the parent. This is probably why the Bourne style shells
4450 don't handle it, since that would require them to go through
4451 this gnarly hair, for no good reason.
4453 NOTE: callers expect this to fork or exit(). */
4455 /* Name of a shell function to call when a command name is not found. */
4456 #ifndef NOTFOUND_HOOK
4457 # define NOTFOUND_HOOK "command_not_found_handle"
4461 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
4462 async
, fds_to_close
, cmdflags
)
4464 REDIRECT
*redirects
;
4466 int pipe_in
, pipe_out
, async
;
4467 struct fd_bitmap
*fds_to_close
;
4470 char *pathname
, *command
, **args
;
4476 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
4477 pathname
= words
->word
->word
;
4479 #if defined (RESTRICTED_SHELL)
4480 command
= (char *)NULL
;
4481 if (restricted
&& mbschr (pathname
, '/'))
4483 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4485 last_command_exit_value
= EXECUTION_FAILURE
;
4487 /* If we're not going to fork below, we must already be in a child
4488 process or a context in which it's safe to call exit(2). */
4489 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
4490 exit (last_command_exit_value
);
4494 #endif /* RESTRICTED_SHELL */
4496 command
= search_for_command (pathname
);
4500 maybe_make_export_env ();
4501 put_command_name_into_env (command
);
4504 /* We have to make the child before we check for the non-existence
4505 of COMMAND, since we want the error messages to be redirected. */
4506 /* If we can get away without forking and there are no pipes to deal with,
4507 don't bother to fork, just directly exec the command. */
4508 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
4511 pid
= make_child (savestring (command_line
), async
);
4515 int old_interactive
;
4518 /* This has been disabled for the time being. */
4519 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4520 if (posixly_correct
== 0)
4521 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags
);
4525 /* Cancel traps, in trap.c. */
4526 restore_original_signals ();
4528 /* restore_original_signals may have undone the work done
4529 by make_child to ensure that SIGINT and SIGQUIT are ignored
4530 in asynchronous children. */
4533 if ((cmdflags
& CMD_STDIN_REDIR
) &&
4534 pipe_in
== NO_PIPE
&&
4535 (stdin_redirects (redirects
) == 0))
4536 async_redirect_stdin ();
4537 setup_async_signals ();
4540 /* This functionality is now provided by close-on-exec of the
4541 file descriptors manipulated by redirection and piping.
4542 Some file descriptors still need to be closed in all children
4543 because of the way bash does pipes; fds_to_close is a
4544 bitmap of all such file descriptors. */
4546 close_fd_bitmap (fds_to_close
);
4548 do_piping (pipe_in
, pipe_out
);
4550 old_interactive
= interactive
;
4554 subshell_environment
= SUBSHELL_FORK
;
4556 if (redirects
&& (do_redirections (redirects
, RX_ACTIVE
) != 0))
4558 #if defined (PROCESS_SUBSTITUTION)
4559 /* Try to remove named pipes that may have been created as the
4560 result of redirections. */
4561 unlink_fifo_list ();
4562 #endif /* PROCESS_SUBSTITUTION */
4563 exit (EXECUTION_FAILURE
);
4567 interactive
= old_interactive
;
4571 hookf
= find_function (NOTFOUND_HOOK
);
4574 internal_error (_("%s: command not found"), pathname
);
4575 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
4578 wl
= make_word_list (make_word (NOTFOUND_HOOK
), words
);
4579 exit (execute_shell_function (hookf
, wl
));
4582 /* Execve expects the command name to be in args[0]. So we
4583 leave it there, in the same format that the user used to
4585 args
= strvec_from_word_list (words
, 0, 0, (int *)NULL
);
4586 exit (shell_execve (command
, args
, export_env
));
4591 /* Make sure that the pipes are closed in the parent. */
4592 close_pipes (pipe_in
, pipe_out
);
4593 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4594 if (variable_context
== 0)
4595 unlink_fifo_list ();
4601 /* CPP defines to decide whether a particular index into the #! line
4602 corresponds to a valid interpreter name or argument character, or
4603 whitespace. The MSDOS define is to allow \r to be treated the same
4606 #if !defined (MSDOS)
4607 # define STRINGCHAR(ind) \
4608 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4609 # define WHITECHAR(ind) \
4610 (ind < sample_len && whitespace (sample[ind]))
4612 # define STRINGCHAR(ind) \
4613 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4614 # define WHITECHAR(ind) \
4615 (ind < sample_len && whitespace (sample[ind]))
4619 getinterp (sample
, sample_len
, endp
)
4621 int sample_len
, *endp
;
4627 /* Find the name of the interpreter to exec. */
4628 for (i
= 2; i
< sample_len
&& whitespace (sample
[i
]); i
++)
4631 for (start
= i
; STRINGCHAR(i
); i
++)
4634 execname
= substring (sample
, start
, i
);
4641 #if !defined (HAVE_HASH_BANG_EXEC)
4642 /* If the operating system on which we're running does not handle
4643 the #! executable format, then help out. SAMPLE is the text read
4644 from the file, SAMPLE_LEN characters. COMMAND is the name of
4645 the script; it and ARGS, the arguments given by the user, will
4646 become arguments to the specified interpreter. ENV is the environment
4647 to pass to the interpreter.
4649 The word immediately following the #! is the interpreter to execute.
4650 A single argument to the interpreter is allowed. */
4653 execute_shell_script (sample
, sample_len
, command
, args
, env
)
4659 char *execname
, *firstarg
;
4660 int i
, start
, size_increment
, larry
;
4662 /* Find the name of the interpreter to exec. */
4663 execname
= getinterp (sample
, sample_len
, &i
);
4666 /* Now the argument, if any. */
4667 for (firstarg
= (char *)NULL
, start
= i
; WHITECHAR(i
); i
++)
4670 /* If there is more text on the line, then it is an argument for the
4675 for (start
= i
; STRINGCHAR(i
); i
++)
4677 firstarg
= substring ((char *)sample
, start
, i
);
4681 larry
= strvec_len (args
) + size_increment
;
4682 args
= strvec_resize (args
, larry
+ 1);
4684 for (i
= larry
- 1; i
; i
--)
4685 args
[i
] = args
[i
- size_increment
];
4696 args
[larry
] = (char *)NULL
;
4698 return (shell_execve (execname
, args
, env
));
4703 #endif /* !HAVE_HASH_BANG_EXEC */
4706 initialize_subshell ()
4709 /* Forget about any aliases that we knew of. We are in a subshell. */
4710 delete_all_aliases ();
4713 #if defined (HISTORY)
4714 /* Forget about the history lines we have read. This is a non-interactive
4716 history_lines_this_session
= 0;
4719 #if defined (JOB_CONTROL)
4720 /* Forget about the way job control was working. We are in a subshell. */
4721 without_job_control ();
4722 set_sigchld_handler ();
4724 #endif /* JOB_CONTROL */
4726 /* Reset the values of the shell flags and options. */
4727 reset_shell_flags ();
4728 reset_shell_options ();
4729 reset_shopt_options ();
4731 /* Zero out builtin_env, since this could be a shell script run from a
4732 sourced file with a temporary environment supplied to the `source/.'
4733 builtin. Such variables are not supposed to be exported (empirical
4734 testing with sh and ksh). Just throw it away; don't worry about a
4736 if (vc_isbltnenv (shell_variables
))
4737 shell_variables
= shell_variables
->down
;
4739 clear_unwind_protect_list (0);
4740 /* XXX -- are there other things we should be resetting here? */
4741 parse_and_execute_level
= 0; /* nothing left to restore it */
4743 /* We're no longer inside a shell function. */
4744 variable_context
= return_catch_flag
= funcnest
= 0;
4746 executing_list
= 0; /* XXX */
4748 /* If we're not interactive, close the file descriptor from which we're
4749 reading the current shell script. */
4750 if (interactive_shell
== 0)
4751 unset_bash_input (0);
4754 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4755 # define SETOSTYPE(x) __setostype(x)
4757 # define SETOSTYPE(x)
4760 #define READ_SAMPLE_BUF(file, buf, len) \
4763 fd = open(file, O_RDONLY); \
4766 len = read (fd, buf, 80); \
4774 /* Call execve (), handling interpreting shell scripts, and handling
4777 shell_execve (command
, args
, env
)
4785 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
4786 execve (command
, args
, env
);
4787 i
= errno
; /* error from execve() */
4791 /* If we get to this point, then start checking out the file.
4792 Maybe it is something we can hack ourselves. */
4795 if (file_isdir (command
))
4796 internal_error (_("%s: is a directory"), command
);
4797 else if (executable_file (command
) == 0)
4800 file_error (command
);
4802 /* errors not involving the path argument to execve. */
4803 else if (i
== E2BIG
|| i
== ENOMEM
)
4806 file_error (command
);
4810 /* The file has the execute bits set, but the kernel refuses to
4811 run it for some reason. See why. */
4812 #if defined (HAVE_HASH_BANG_EXEC)
4813 READ_SAMPLE_BUF (command
, sample
, sample_len
);
4814 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
4819 interp
= getinterp (sample
, sample_len
, (int *)NULL
);
4820 ilen
= strlen (interp
);
4822 if (interp
[ilen
- 1] == '\r')
4824 interp
= xrealloc (interp
, ilen
+ 2);
4825 interp
[ilen
- 1] = '^';
4827 interp
[ilen
+ 1] = '\0';
4829 sys_error (_("%s: %s: bad interpreter"), command
, interp
? interp
: "");
4835 file_error (command
);
4837 return ((i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
); /* XXX Posix.2 says that exit status is 126 */
4840 /* This file is executable.
4841 If it begins with #!, then help out people with losing operating
4842 systems. Otherwise, check to see if it is a binary file by seeing
4843 if the contents of the first line (or up to 80 characters) are in the
4844 ASCII set. If it's a text file, execute the contents as shell commands,
4845 otherwise return 126 (EX_BINARY_FILE). */
4846 READ_SAMPLE_BUF (command
, sample
, sample_len
);
4848 if (sample_len
== 0)
4849 return (EXECUTION_SUCCESS
);
4851 /* Is this supposed to be an executable script?
4852 If so, the format of the line is "#! interpreter [argument]".
4853 A single argument is allowed. The BSD kernel restricts
4854 the length of the entire line to 32 characters (32 bytes
4855 being the size of the BSD exec header), but we allow 80
4859 #if !defined (HAVE_HASH_BANG_EXEC)
4860 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
4861 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
4864 if (check_binary_file (sample
, sample_len
))
4866 internal_error (_("%s: cannot execute binary file"), command
);
4867 return (EX_BINARY_FILE
);
4871 /* We have committed to attempting to execute the contents of this file
4872 as shell commands. */
4874 initialize_subshell ();
4876 set_sigint_handler ();
4878 /* Insert the name of this shell into the argument list. */
4879 larray
= strvec_len (args
) + 1;
4880 args
= strvec_resize (args
, larray
+ 1);
4882 for (i
= larray
- 1; i
; i
--)
4883 args
[i
] = args
[i
- 1];
4885 args
[0] = shell_name
;
4887 args
[larray
] = (char *)NULL
;
4889 if (args
[0][0] == '-')
4892 #if defined (RESTRICTED_SHELL)
4894 change_flag ('r', FLAG_OFF
);
4899 /* Can't free subshell_argv[0]; that is shell_name. */
4900 for (i
= 1; i
< subshell_argc
; i
++)
4901 free (subshell_argv
[i
]);
4902 free (subshell_argv
);
4905 dispose_command (currently_executing_command
); /* XXX */
4906 currently_executing_command
= (COMMAND
*)NULL
;
4908 subshell_argc
= larray
;
4909 subshell_argv
= args
;
4910 subshell_envp
= env
;
4912 unbind_args (); /* remove the positional parameters */
4914 longjmp (subshell_top_level
, 1);
4919 execute_intern_function (name
, function
)
4925 if (check_identifier (name
, posixly_correct
) == 0)
4927 if (posixly_correct
&& interactive_shell
== 0)
4929 last_command_exit_value
= EX_BADUSAGE
;
4930 jump_to_top_level (ERREXIT
);
4932 return (EXECUTION_FAILURE
);
4935 var
= find_function (name
->word
);
4936 if (var
&& (readonly_p (var
) || noassign_p (var
)))
4938 if (readonly_p (var
))
4939 internal_error (_("%s: readonly function"), var
->name
);
4940 return (EXECUTION_FAILURE
);
4943 bind_function (name
->word
, function
);
4944 return (EXECUTION_SUCCESS
);
4947 #if defined (INCLUDE_UNUSED)
4948 #if defined (PROCESS_SUBSTITUTION)
4952 register int i
, fd_table_size
;
4954 fd_table_size
= getdtablesize ();
4955 if (fd_table_size
> 256) /* clamp to a reasonable value */
4956 fd_table_size
= 256;
4958 for (i
= 3; i
< fd_table_size
; i
++)
4961 #endif /* PROCESS_SUBSTITUTION */
4965 close_pipes (in
, out
)
4975 dup_error (oldd
, newd
)
4978 sys_error (_("cannot duplicate fd %d to fd %d"), oldd
, newd
);
4981 /* Redirect input and output to be from and to the specified pipes.
4982 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4984 do_piping (pipe_in
, pipe_out
)
4985 int pipe_in
, pipe_out
;
4987 if (pipe_in
!= NO_PIPE
)
4989 if (dup2 (pipe_in
, 0) < 0)
4990 dup_error (pipe_in
, 0);
4994 if (pipe_out
!= NO_PIPE
)
4996 if (pipe_out
!= REDIRECT_BOTH
)
4998 if (dup2 (pipe_out
, 1) < 0)
4999 dup_error (pipe_out
, 1);
5000 if (pipe_out
== 0 || pipe_out
> 1)
5005 if (dup2 (1, 2) < 0)