1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2008 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
34 #include "posixstat.h"
37 # include <sys/param.h>
40 #if defined (HAVE_UNISTD_H)
44 #include "posixtime.h"
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 # include <sys/resource.h>
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 # include <sys/times.h>
65 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
70 #include "execute_cmd.h"
77 #if defined (COND_COMMAND)
81 #include "builtins/common.h"
82 #include "builtins/builtext.h" /* list of builtins */
84 #include <glob/strmatch.h>
85 #include <tilde/tilde.h>
87 #if defined (BUFFERED_INPUT)
96 # include "bashhist.h"
99 extern int posixly_correct
;
100 extern int expand_aliases
;
102 extern int breaking
, continuing
, loop_level
;
103 extern int parse_and_execute_level
, running_trap
;
104 extern int command_string_index
, line_number
;
105 extern int dot_found_in_search
;
106 extern int already_making_children
;
107 extern int tempenv_assign_error
;
108 extern char *the_printed_command
, *shell_name
;
109 extern pid_t last_command_subst_pid
;
110 extern sh_builtin_func_t
*last_shell_builtin
, *this_shell_builtin
;
111 extern char **subshell_argv
, **subshell_envp
;
112 extern int subshell_argc
;
114 extern char *glob_argv_flags
;
117 extern int close
__P((int));
119 /* Static functions defined and used in this file. */
120 static void close_pipes
__P((int, int));
121 static void do_piping
__P((int, int));
122 static void bind_lastarg
__P((char *));
123 static int shell_control_structure
__P((enum command_type
));
124 static void cleanup_redirects
__P((REDIRECT
*));
126 #if defined (JOB_CONTROL)
127 static int restore_signal_mask
__P((sigset_t
*));
130 static void async_redirect_stdin
__P((void));
132 static int builtin_status
__P((int));
134 static int execute_for_command
__P((FOR_COM
*));
135 #if defined (SELECT_COMMAND)
136 static int print_index_and_element
__P((int, int, WORD_LIST
*));
137 static void indent
__P((int, int));
138 static void print_select_list
__P((WORD_LIST
*, int, int, int));
139 static char *select_query
__P((WORD_LIST
*, int, char *, int));
140 static int execute_select_command
__P((SELECT_COM
*));
142 #if defined (DPAREN_ARITHMETIC)
143 static int execute_arith_command
__P((ARITH_COM
*));
145 #if defined (COND_COMMAND)
146 static int execute_cond_node
__P((COND_COM
*));
147 static int execute_cond_command
__P((COND_COM
*));
149 #if defined (COMMAND_TIMING)
150 static int mkfmt
__P((char *, int, int, time_t, int));
151 static void print_formatted_time
__P((FILE *, char *,
152 time_t, int, time_t, int,
154 static int time_command
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
156 #if defined (ARITH_FOR_COMMAND)
157 static intmax_t eval_arith_for_expr
__P((WORD_LIST
*, int *));
158 static int execute_arith_for_command
__P((ARITH_FOR_COM
*));
160 static int execute_case_command
__P((CASE_COM
*));
161 static int execute_while_command
__P((WHILE_COM
*));
162 static int execute_until_command
__P((WHILE_COM
*));
163 static int execute_while_or_until
__P((WHILE_COM
*, int));
164 static int execute_if_command
__P((IF_COM
*));
165 static int execute_null_command
__P((REDIRECT
*, int, int, int));
166 static void fix_assignment_words
__P((WORD_LIST
*));
167 static int execute_simple_command
__P((SIMPLE_COM
*, int, int, int, struct fd_bitmap
*));
168 static int execute_builtin
__P((sh_builtin_func_t
*, WORD_LIST
*, int, int));
169 static int execute_function
__P((SHELL_VAR
*, WORD_LIST
*, int, struct fd_bitmap
*, int, int));
170 static int execute_builtin_or_function
__P((WORD_LIST
*, sh_builtin_func_t
*,
172 REDIRECT
*, struct fd_bitmap
*, int));
173 static void execute_subshell_builtin_or_function
__P((WORD_LIST
*, REDIRECT
*,
179 static void execute_disk_command
__P((WORD_LIST
*, REDIRECT
*, char *,
180 int, int, int, struct fd_bitmap
*, int));
182 static char *getinterp
__P((char *, int, int *));
183 static void initialize_subshell
__P((void));
184 static int execute_in_subshell
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
185 #if defined (COPROCESS_SUPPORT)
186 static int execute_coproc
__P((COMMAND
*, int, int, struct fd_bitmap
*));
189 static int execute_pipeline
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
191 static int execute_connection
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
193 static int execute_intern_function
__P((WORD_DESC
*, COMMAND
*));
195 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
196 so that reader_loop can set it to zero before executing a command. */
199 /* The name of the command that is currently being executed.
200 `test' needs this, for example. */
201 char *this_command_name
;
203 /* The printed representation of the currently-executing command (same as
204 the_printed_command), except when a trap is being executed. Useful for
205 a debugger to know where exactly the program is currently executing. */
206 char *the_printed_command_except_trap
;
208 /* For catching RETURN in a function. */
209 int return_catch_flag
;
210 int return_catch_value
;
211 procenv_t return_catch
;
213 /* The value returned by the last synchronous command. */
214 int last_command_exit_value
;
216 /* Whether or not the last command (corresponding to last_command_exit_value)
217 was terminated by a signal, and, if so, which one. */
218 int last_command_exit_signal
;
220 /* The list of redirections to perform which will undo the redirections
221 that I made in the shell. */
222 REDIRECT
*redirection_undo_list
= (REDIRECT
*)NULL
;
224 /* The list of redirections to perform which will undo the internal
225 redirections performed by the `exec' builtin. These are redirections
226 that must be undone even when exec discards redirection_undo_list. */
227 REDIRECT
*exec_redirection_undo_list
= (REDIRECT
*)NULL
;
229 /* When greater than zero, value is the `level' of builtins we are
230 currently executing (e.g. `eval echo a' would have it set to 2). */
231 int executing_builtin
= 0;
233 /* Non-zero if we have just forked and are currently running in a subshell
235 int subshell_environment
;
237 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
238 int subshell_level
= 0;
240 /* Currently-executing shell function. */
241 SHELL_VAR
*this_shell_function
;
243 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
244 int match_ignore_case
= 0;
246 struct stat SB
; /* used for debugging */
248 static int special_builtin_failed
;
250 static COMMAND
*currently_executing_command
;
252 /* The line number that the currently executing function starts on. */
253 static int function_line_number
;
255 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
256 number containing the function name. Used by executing_line_number to
257 report the correct line number. Kind of a hack. */
258 static int showing_function_line
;
260 static int line_number_for_err_trap
;
262 struct fd_bitmap
*current_fds_to_close
= (struct fd_bitmap
*)NULL
;
264 #define FD_BITMAP_DEFAULT_SIZE 32
266 /* Functions to allocate and deallocate the structures used to pass
267 information from the shell to its children about file descriptors
273 struct fd_bitmap
*ret
;
275 ret
= (struct fd_bitmap
*)xmalloc (sizeof (struct fd_bitmap
));
281 ret
->bitmap
= (char *)xmalloc (size
);
282 memset (ret
->bitmap
, '\0', size
);
285 ret
->bitmap
= (char *)NULL
;
290 dispose_fd_bitmap (fdbp
)
291 struct fd_bitmap
*fdbp
;
298 close_fd_bitmap (fdbp
)
299 struct fd_bitmap
*fdbp
;
305 for (i
= 0; i
< fdbp
->size
; i
++)
314 /* Return the line number of the currently executing command. */
316 executing_line_number ()
318 if (executing
&& showing_function_line
== 0 &&
319 (variable_context
== 0 || interactive_shell
== 0) &&
320 currently_executing_command
)
322 #if defined (COND_COMMAND)
323 if (currently_executing_command
->type
== cm_cond
)
324 return currently_executing_command
->value
.Cond
->line
;
326 #if defined (DPAREN_ARITHMETIC)
327 else if (currently_executing_command
->type
== cm_arith
)
328 return currently_executing_command
->value
.Arith
->line
;
330 #if defined (ARITH_FOR_COMMAND)
331 else if (currently_executing_command
->type
== cm_arith_for
)
332 return currently_executing_command
->value
.ArithFor
->line
;
341 /* Execute the command passed in COMMAND. COMMAND is exactly what
342 read_command () places into GLOBAL_COMMAND. See "command.h" for the
343 details of the command structure.
345 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
346 return values. Executing a command with nothing in it returns
347 EXECUTION_SUCCESS. */
349 execute_command (command
)
352 struct fd_bitmap
*bitmap
;
355 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
356 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
357 begin_unwind_frame ("execute-command");
358 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
360 /* Just do the command, but not asynchronously. */
361 result
= execute_command_internal (command
, 0, NO_PIPE
, NO_PIPE
, bitmap
);
363 dispose_fd_bitmap (bitmap
);
364 discard_unwind_frame ("execute-command");
366 #if defined (PROCESS_SUBSTITUTION)
367 /* don't unlink fifos if we're in a shell function; wait until the function
369 if (variable_context
== 0)
371 #endif /* PROCESS_SUBSTITUTION */
377 /* Return 1 if TYPE is a shell control structure type. */
379 shell_control_structure (type
)
380 enum command_type type
;
384 #if defined (ARITH_FOR_COMMAND)
387 #if defined (SELECT_COMMAND)
390 #if defined (DPAREN_ARITHMETIC)
393 #if defined (COND_COMMAND)
402 case cm_function_def
:
410 /* A function to use to unwind_protect the redirection undo list
413 cleanup_redirects (list
)
416 do_redirections (list
, RX_ACTIVE
);
417 dispose_redirects (list
);
421 /* Function to unwind_protect the redirections for functions and builtins. */
423 cleanup_func_redirects (list
)
426 do_redirections (list
, RX_ACTIVE
);
431 dispose_exec_redirects ()
433 if (exec_redirection_undo_list
)
435 dispose_redirects (exec_redirection_undo_list
);
436 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
440 #if defined (JOB_CONTROL)
441 /* A function to restore the signal mask to its proper value when the shell
442 is interrupted or errors occur while creating a pipeline. */
444 restore_signal_mask (set
)
447 return (sigprocmask (SIG_SETMASK
, set
, (sigset_t
*)NULL
));
449 #endif /* JOB_CONTROL */
452 /* A debugging function that can be called from gdb, for instance. */
457 int f
, fd_table_size
;
459 fd_table_size
= getdtablesize ();
461 fprintf (stderr
, "pid %ld open files:", (long)getpid ());
462 for (i
= 3; i
< fd_table_size
; i
++)
464 if ((f
= fcntl (i
, F_GETFD
, 0)) != -1)
465 fprintf (stderr
, " %d (%s)", i
, f
? "close" : "open");
467 fprintf (stderr
, "\n");
472 async_redirect_stdin ()
476 fd
= open ("/dev/null", O_RDONLY
);
483 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno
));
486 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
488 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
489 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
490 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
491 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
492 from and where it goes. They can have the value of NO_PIPE, which means
494 FDS_TO_CLOSE is a list of file descriptors to close once the child has
495 been forked. This list often contains the unusable sides of pipes, etc.
497 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
498 return values. Executing a command with nothing in it returns
499 EXECUTION_SUCCESS. */
501 execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
,
505 int pipe_in
, pipe_out
;
506 struct fd_bitmap
*fds_to_close
;
508 int exec_result
, invert
, ignore_return
, was_error_trap
;
509 REDIRECT
*my_undo_list
, *exec_undo_list
;
510 volatile int last_pid
;
511 volatile int save_line_number
;
514 if (command
== 0 || breaking
|| continuing
|| read_but_dont_execute
)
515 return (EXECUTION_SUCCESS
);
517 if (breaking
|| continuing
)
518 return (last_command_exit_value
);
519 if (command
== 0 || read_but_dont_execute
)
520 return (EXECUTION_SUCCESS
);
524 run_pending_traps ();
527 if (running_trap
== 0)
529 currently_executing_command
= command
;
531 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
533 /* If we're inverting the return value and `set -e' has been executed,
534 we don't want a failing command to inadvertently cause the shell
536 if (exit_immediately_on_error
&& invert
) /* XXX */
537 command
->flags
|= CMD_IGNORE_RETURN
; /* XXX */
539 exec_result
= EXECUTION_SUCCESS
;
541 /* If a command was being explicitly run in a subshell, or if it is
542 a shell control-structure, and it has a pipe, then we do the command
544 if (command
->type
== cm_subshell
&& (command
->flags
& CMD_NO_FORK
))
545 return (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
547 #if defined (COPROCESS_SUPPORT)
548 if (command
->type
== cm_coproc
)
549 return (execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
));
552 if (command
->type
== cm_subshell
||
553 (command
->flags
& (CMD_WANT_SUBSHELL
|CMD_FORCE_SUBSHELL
)) ||
554 (shell_control_structure (command
->type
) &&
555 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
|| asynchronous
)))
559 /* Fork a subshell, turn off the subshell bit, turn off job
560 control and call execute_command () on the command again. */
561 paren_pid
= make_child (savestring (make_command_string (command
)),
564 exit (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
568 close_pipes (pipe_in
, pipe_out
);
570 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
573 /* If we are part of a pipeline, and not the end of the pipeline,
574 then we should simply return and let the last command in the
575 pipe be waited for. If we are not in a pipeline, or are the
576 last command in the pipeline, then we wait for the subshell
577 and return its exit status as usual. */
578 if (pipe_out
!= NO_PIPE
)
579 return (EXECUTION_SUCCESS
);
581 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
583 if (asynchronous
== 0)
585 last_command_exit_value
= wait_for (paren_pid
);
587 /* If we have to, invert the return value. */
589 exec_result
= ((last_command_exit_value
== EXECUTION_SUCCESS
)
591 : EXECUTION_SUCCESS
);
593 exec_result
= last_command_exit_value
;
595 return (last_command_exit_value
= exec_result
);
599 DESCRIBE_PID (paren_pid
);
601 run_pending_traps ();
603 return (EXECUTION_SUCCESS
);
608 #if defined (COMMAND_TIMING)
609 if (command
->flags
& CMD_TIME_PIPELINE
)
613 command
->flags
|= CMD_FORCE_SUBSHELL
;
614 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
618 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
620 if (running_trap
== 0)
622 currently_executing_command
= (COMMAND
*)NULL
;
624 return (exec_result
);
626 #endif /* COMMAND_TIMING */
628 if (shell_control_structure (command
->type
) && command
->redirects
)
629 stdin_redir
= stdin_redirects (command
->redirects
);
631 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
633 if (do_redirections (command
->redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
635 cleanup_redirects (redirection_undo_list
);
636 redirection_undo_list
= (REDIRECT
*)NULL
;
637 dispose_exec_redirects ();
638 return (last_command_exit_value
= EXECUTION_FAILURE
);
641 if (redirection_undo_list
)
643 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
644 dispose_redirects (redirection_undo_list
);
645 redirection_undo_list
= (REDIRECT
*)NULL
;
648 my_undo_list
= (REDIRECT
*)NULL
;
650 if (exec_redirection_undo_list
)
652 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
653 dispose_redirects (exec_redirection_undo_list
);
654 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
657 exec_undo_list
= (REDIRECT
*)NULL
;
659 if (my_undo_list
|| exec_undo_list
)
660 begin_unwind_frame ("loop_redirections");
663 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
666 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
668 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
672 switch (command
->type
)
676 save_line_number
= line_number
;
677 /* We can't rely on variables retaining their values across a
678 call to execute_simple_command if a longjmp occurs as the
679 result of a `return' builtin. This is true for sure with gcc. */
680 #if defined (RECYCLES_PIDS)
681 last_made_pid
= NO_PID
;
683 last_pid
= last_made_pid
;
684 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
686 if (ignore_return
&& command
->value
.Simple
)
687 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
688 if (command
->flags
& CMD_STDIN_REDIR
)
689 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
691 line_number_for_err_trap
= line_number
= command
->value
.Simple
->line
;
693 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
694 asynchronous
, fds_to_close
);
695 line_number
= save_line_number
;
697 /* The temporary environment should be used for only the simple
698 command immediately following its definition. */
699 dispose_used_env_vars ();
701 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
702 /* Reclaim memory allocated with alloca () on machines which
703 may be using the alloca emulation code. */
705 #endif /* (ultrix && mips) || C_ALLOCA */
707 /* If we forked to do the command, then we must wait_for ()
710 /* XXX - this is something to watch out for if there are problems
711 when the shell is compiled without job control. */
712 if (already_making_children
&& pipe_out
== NO_PIPE
&&
713 last_made_pid
!= last_pid
)
715 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
719 DESCRIBE_PID (last_made_pid
);
722 #if !defined (JOB_CONTROL)
723 /* Do not wait for asynchronous processes started from
725 if (last_made_pid
!= last_asynchronous_pid
)
727 /* When executing a shell function that executes other
728 commands, this causes the last simple command in
729 the function to be waited for twice. This also causes
730 subshells forked to execute builtin commands (e.g., in
731 pipelines) to be waited for twice. */
732 exec_result
= wait_for (last_made_pid
);
736 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
738 last_command_exit_value
= exec_result
;
742 if (ignore_return
== 0 && invert
== 0 &&
743 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
744 (exit_immediately_on_error
&& (exec_result
!= EXECUTION_SUCCESS
))))
746 last_command_exit_value
= exec_result
;
747 run_pending_traps ();
748 jump_to_top_level (ERREXIT
);
755 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
756 exec_result
= execute_for_command (command
->value
.For
);
759 #if defined (ARITH_FOR_COMMAND)
762 command
->value
.ArithFor
->flags
|= CMD_IGNORE_RETURN
;
763 exec_result
= execute_arith_for_command (command
->value
.ArithFor
);
767 #if defined (SELECT_COMMAND)
770 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
771 exec_result
= execute_select_command (command
->value
.Select
);
777 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
778 exec_result
= execute_case_command (command
->value
.Case
);
783 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
784 exec_result
= execute_while_command (command
->value
.While
);
789 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
790 exec_result
= execute_until_command (command
->value
.While
);
795 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
796 exec_result
= execute_if_command (command
->value
.If
);
801 /* This code can be executed from either of two paths: an explicit
802 '{}' command, or via a function call. If we are executed via a
803 function call, we have already taken care of the function being
804 executed in the background (down there in execute_simple_command ()),
805 and this command should *not* be marked as asynchronous. If we
806 are executing a regular '{}' group command, and asynchronous == 1,
807 we must want to execute the whole command in the background, so we
808 need a subshell, and we want the stuff executed in that subshell
809 (this group command) to be executed in the foreground of that
810 subshell (i.e. there will not be *another* subshell forked).
812 What we do is to force a subshell if asynchronous, and then call
813 execute_command_internal again with asynchronous still set to 1,
814 but with the original group command, so the printed command will
817 The code above that handles forking off subshells will note that
818 both subshell and async are on, and turn off async in the child
819 after forking the subshell (but leave async set in the parent, so
820 the normal call to describe_pid is made). This turning off
821 async is *crucial*; if it is not done, this will fall into an
822 infinite loop of executions through this spot in subshell after
823 subshell until the process limit is exhausted. */
827 command
->flags
|= CMD_FORCE_SUBSHELL
;
829 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
834 if (ignore_return
&& command
->value
.Group
->command
)
835 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
837 execute_command_internal (command
->value
.Group
->command
,
838 asynchronous
, pipe_in
, pipe_out
,
844 exec_result
= execute_connection (command
, asynchronous
,
845 pipe_in
, pipe_out
, fds_to_close
);
848 #if defined (DPAREN_ARITHMETIC)
851 command
->value
.Arith
->flags
|= CMD_IGNORE_RETURN
;
852 exec_result
= execute_arith_command (command
->value
.Arith
);
856 #if defined (COND_COMMAND)
859 command
->value
.Cond
->flags
|= CMD_IGNORE_RETURN
;
860 save_line_number
= line_number
;
861 exec_result
= execute_cond_command (command
->value
.Cond
);
862 line_number
= save_line_number
;
866 case cm_function_def
:
867 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
868 command
->value
.Function_def
->command
);
872 command_error ("execute_command", CMDERR_BADTYPE
, command
->type
, 0);
877 do_redirections (my_undo_list
, RX_ACTIVE
);
878 dispose_redirects (my_undo_list
);
882 dispose_redirects (exec_undo_list
);
884 if (my_undo_list
|| exec_undo_list
)
885 discard_unwind_frame ("loop_redirections");
887 /* Invert the return value if we have to */
889 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
893 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
894 /* This is where we set PIPESTATUS from the exit status of the appropriate
895 compound commands (the ones that look enough like simple commands to
896 cause confusion). We might be able to optimize by not doing this if
897 subshell_environment != 0. */
898 switch (command
->type
)
900 # if defined (DPAREN_ARITHMETIC)
903 # if defined (COND_COMMAND)
906 set_pipestatus_from_exit (exec_result
);
911 last_command_exit_value
= exec_result
;
912 run_pending_traps ();
914 if (running_trap
== 0)
916 currently_executing_command
= (COMMAND
*)NULL
;
917 return (last_command_exit_value
);
920 #if defined (COMMAND_TIMING)
922 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
923 extern struct timeval
*difftimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
924 extern struct timeval
*addtimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
925 extern int timeval_to_cpu
__P((struct timeval
*, struct timeval
*, struct timeval
*));
928 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
929 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
931 static const int precs
[] = { 0, 100, 10, 1 };
933 /* Expand one `%'-prefixed escape sequence from a time format string. */
935 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
942 char abuf
[INT_STRLEN_BOUND(time_t) + 1];
946 abuf
[sizeof(abuf
) - 1] = '\0';
948 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
953 aind
= sizeof(abuf
) - 2;
955 abuf
[aind
--] = (min
% 10) + '0';
959 buf
[ind
++] = abuf
[aind
++];
963 /* Now add the seconds. */
964 aind
= sizeof (abuf
) - 2;
966 abuf
[aind
--] = (sec
% 10) + '0';
970 buf
[ind
++] = abuf
[aind
++];
972 /* We want to add a decimal point and PREC places after it if PREC is
973 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
978 for (aind
= 1; aind
<= prec
; aind
++)
980 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
981 sec_fraction
%= precs
[aind
];
992 /* Interpret the format string FORMAT, interpolating the following escape
996 where the optional `prec' is a precision, meaning the number of
997 characters after the decimal point, the optional `l' means to format
998 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
999 and the last character is one of
1001 R number of seconds of `real' time
1002 U number of seconds of `user' time
1003 S number of seconds of `system' time
1005 An occurrence of `%%' in the format string is translated to a `%'. The
1006 result is printed to FP, a pointer to a FILE. The other variables are
1007 the seconds and thousandths of a second of real, user, and system time,
1010 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1021 char *str
, *s
, ts
[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1026 len
= strlen (format
);
1027 ssize
= (len
+ 64) - (len
% 64);
1028 str
= (char *)xmalloc (ssize
);
1031 for (s
= format
; *s
; s
++)
1033 if (*s
!= '%' || s
[1] == '\0')
1035 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1038 else if (s
[1] == '%')
1041 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1044 else if (s
[1] == 'P')
1050 sum_frac
= (cpu
% 100) * 10;
1051 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1052 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1053 strcpy (str
+ sindex
, ts
);
1058 prec
= 3; /* default is three places past the decimal point. */
1059 lng
= 0; /* default is to not use minutes or append `s' */
1061 if (DIGIT (*s
)) /* `precision' */
1064 if (prec
> 3) prec
= 3;
1066 if (*s
== 'l') /* `length extender' */
1071 if (*s
== 'R' || *s
== 'E')
1072 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1074 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1076 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1079 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s
);
1083 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1084 strcpy (str
+ sindex
, ts
);
1090 fprintf (fp
, "%s\n", str
);
1097 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1099 int asynchronous
, pipe_in
, pipe_out
;
1100 struct fd_bitmap
*fds_to_close
;
1102 int rv
, posix_time
, old_flags
;
1108 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1109 struct timeval real
, user
, sys
;
1110 struct timeval before
, after
;
1111 # if defined (HAVE_STRUCT_TIMEZONE)
1112 struct timezone dtz
; /* posix doesn't define this */
1114 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1116 # if defined (HAVE_TIMES)
1117 clock_t tbefore
, tafter
, real
, user
, sys
;
1118 struct tms before
, after
;
1122 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1123 # if defined (HAVE_STRUCT_TIMEZONE)
1124 gettimeofday (&before
, &dtz
);
1126 gettimeofday (&before
, (void *)NULL
);
1127 # endif /* !HAVE_STRUCT_TIMEZONE */
1128 getrusage (RUSAGE_SELF
, &selfb
);
1129 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1131 # if defined (HAVE_TIMES)
1132 tbefore
= times (&before
);
1136 posix_time
= (command
->flags
& CMD_TIME_POSIX
);
1138 old_flags
= command
->flags
;
1139 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1140 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1141 command
->flags
= old_flags
;
1144 rsf
= usf
= ssf
= cpu
= 0;
1146 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1147 # if defined (HAVE_STRUCT_TIMEZONE)
1148 gettimeofday (&after
, &dtz
);
1150 gettimeofday (&after
, (void *)NULL
);
1151 # endif /* !HAVE_STRUCT_TIMEZONE */
1152 getrusage (RUSAGE_SELF
, &selfa
);
1153 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1155 difftimeval (&real
, &before
, &after
);
1156 timeval_to_secs (&real
, &rs
, &rsf
);
1158 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1159 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1160 timeval_to_secs (&user
, &us
, &usf
);
1162 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1163 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1164 timeval_to_secs (&sys
, &ss
, &ssf
);
1166 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1168 # if defined (HAVE_TIMES)
1169 tafter
= times (&after
);
1171 real
= tafter
- tbefore
;
1172 clock_t_to_secs (real
, &rs
, &rsf
);
1174 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1175 clock_t_to_secs (user
, &us
, &usf
);
1177 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1178 clock_t_to_secs (sys
, &ss
, &ssf
);
1180 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1184 rsf
= usf
= ssf
= cpu
= 0;
1189 time_format
= POSIX_TIMEFORMAT
;
1190 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1191 time_format
= BASH_TIMEFORMAT
;
1193 if (time_format
&& *time_format
)
1194 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1198 #endif /* COMMAND_TIMING */
1200 /* Execute a command that's supposed to be in a subshell. This must be
1201 called after make_child and we must be running in the child process.
1202 The caller will return or exit() immediately with the value this returns. */
1204 execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1207 int pipe_in
, pipe_out
;
1208 struct fd_bitmap
*fds_to_close
;
1210 int user_subshell
, return_code
, function_value
, should_redir_stdin
, invert
;
1211 int ois
, user_coproc
;
1214 USE_VAR(user_subshell
);
1215 USE_VAR(user_coproc
);
1218 USE_VAR(asynchronous
);
1221 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
1222 pipe_in
== NO_PIPE
&&
1223 stdin_redirects (command
->redirects
) == 0);
1225 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
1226 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
1227 user_coproc
= command
->type
== cm_coproc
;
1229 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
1231 /* If a command is asynchronous in a subshell (like ( foo ) & or
1232 the special case of an asynchronous GROUP command where the
1233 the subshell bit is turned on down in case cm_group: below),
1234 turn off `asynchronous', so that two subshells aren't spawned.
1235 XXX - asynchronous used to be set to 0 in this block, but that
1236 means that setup_async_signals was never run. Now it's set to
1237 0 after subshell_environment is set appropriately and setup_async_signals
1240 This seems semantically correct to me. For example,
1241 ( foo ) & seems to say ``do the command `foo' in a subshell
1242 environment, but don't wait for that subshell to finish'',
1243 and "{ foo ; bar ; } &" seems to me to be like functions or
1244 builtins in the background, which executed in a subshell
1245 environment. I just don't see the need to fork two subshells. */
1247 /* Don't fork again, we are already in a subshell. A `doubly
1248 async' shell is not interactive, however. */
1251 #if defined (JOB_CONTROL)
1252 /* If a construct like ( exec xxx yyy ) & is given while job
1253 control is active, we want to prevent exec from putting the
1254 subshell back into the original process group, carefully
1255 undoing all the work we just did in make_child. */
1257 #endif /* JOB_CONTROL */
1258 ois
= interactive_shell
;
1259 interactive_shell
= 0;
1260 /* This test is to prevent alias expansion by interactive shells that
1261 run `(command) &' but to allow scripts that have enabled alias
1262 expansion with `shopt -s expand_alias' to continue to expand
1264 if (ois
!= interactive_shell
)
1268 /* Subshells are neither login nor interactive. */
1269 login_shell
= interactive
= 0;
1272 subshell_environment
= SUBSHELL_PAREN
;
1275 subshell_environment
= 0; /* XXX */
1277 subshell_environment
|= SUBSHELL_ASYNC
;
1278 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
1279 subshell_environment
|= SUBSHELL_PIPE
;
1281 subshell_environment
|= SUBSHELL_COPROC
;
1284 reset_terminating_signals (); /* in sig.c */
1285 /* Cancel traps, in trap.c. */
1286 restore_original_signals ();
1288 /* Make sure restore_original_signals doesn't undo the work done by
1289 make_child to ensure that asynchronous children are immune to SIGINT
1290 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1294 setup_async_signals ();
1298 #if defined (JOB_CONTROL)
1299 set_sigchld_handler ();
1300 #endif /* JOB_CONTROL */
1302 set_sigint_handler ();
1304 #if defined (JOB_CONTROL)
1305 /* Delete all traces that there were any jobs running. This is
1306 only for subshells. */
1307 without_job_control ();
1308 #endif /* JOB_CONTROL */
1311 close_fd_bitmap (fds_to_close
);
1313 do_piping (pipe_in
, pipe_out
);
1315 #if defined (COPROCESS_SUPPORT)
1319 /* If this is a user subshell, set a flag if stdin was redirected.
1320 This is used later to decide whether to redirect fd 0 to
1321 /dev/null for async commands in the subshell. This adds more
1322 sh compatibility, but I'm not sure it's the right thing to do. */
1325 stdin_redir
= stdin_redirects (command
->redirects
);
1326 restore_default_signal (0);
1329 /* If this is an asynchronous command (command &), we want to
1330 redirect the standard input from /dev/null in the absence of
1331 any specific redirection involving stdin. */
1332 if (should_redir_stdin
&& stdin_redir
== 0)
1333 async_redirect_stdin ();
1335 /* Do redirections, then dispose of them before recursive call. */
1336 if (command
->redirects
)
1338 if (do_redirections (command
->redirects
, RX_ACTIVE
) != 0)
1339 exit (invert
? EXECUTION_SUCCESS
: EXECUTION_FAILURE
);
1341 dispose_redirects (command
->redirects
);
1342 command
->redirects
= (REDIRECT
*)NULL
;
1345 if (command
->type
== cm_subshell
)
1346 tcom
= command
->value
.Subshell
->command
;
1347 else if (user_coproc
)
1348 tcom
= command
->value
.Coproc
->command
;
1352 if (command
->flags
& CMD_TIME_PIPELINE
)
1353 tcom
->flags
|= CMD_TIME_PIPELINE
;
1354 if (command
->flags
& CMD_TIME_POSIX
)
1355 tcom
->flags
|= CMD_TIME_POSIX
;
1357 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1358 if ((command
->flags
& CMD_IGNORE_RETURN
) && tcom
!= command
)
1359 tcom
->flags
|= CMD_IGNORE_RETURN
;
1361 /* If this is a simple command, tell execute_disk_command that it
1362 might be able to get away without forking and simply exec.
1363 This means things like ( sleep 10 ) will only cause one fork.
1364 If we're timing the command or inverting its return value, however,
1365 we cannot do this optimization. */
1366 if ((user_subshell
|| user_coproc
) && (tcom
->type
== cm_simple
|| tcom
->type
== cm_subshell
) &&
1367 ((tcom
->flags
& CMD_TIME_PIPELINE
) == 0) &&
1368 ((tcom
->flags
& CMD_INVERT_RETURN
) == 0))
1370 tcom
->flags
|= CMD_NO_FORK
;
1371 if (tcom
->type
== cm_simple
)
1372 tcom
->value
.Simple
->flags
|= CMD_NO_FORK
;
1375 invert
= (tcom
->flags
& CMD_INVERT_RETURN
) != 0;
1376 tcom
->flags
&= ~CMD_INVERT_RETURN
;
1378 /* If we're inside a function while executing this subshell, we
1379 need to handle a possible `return'. */
1381 if (return_catch_flag
)
1382 function_value
= setjmp (return_catch
);
1385 return_code
= return_catch_value
;
1387 return_code
= execute_command_internal (tcom
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
1389 /* If we are asked to, invert the return value. */
1391 return_code
= (return_code
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
1392 : EXECUTION_SUCCESS
;
1394 /* If we were explicitly placed in a subshell with (), we need
1395 to do the `shell cleanup' things, such as running traps[0]. */
1396 if (user_subshell
&& signal_is_trapped (0))
1398 last_command_exit_value
= return_code
;
1399 return_code
= run_exit_trap ();
1403 return (return_code
);
1407 #if defined (COPROCESS_SUPPORT)
1408 #define COPROC_MAX 16
1410 typedef struct cpelement
1412 struct cpelement
*next
;
1413 struct coproc
*coproc
;
1417 typedef struct cplist
1419 struct cpelement
*head
;
1420 struct cpelement
*tail
;
1425 static struct cpelement
*cpe_alloc
__P((struct coproc
*));
1426 static void cpe_dispose
__P((struct cpelement
*));
1427 static struct cpelement
*cpl_add
__P((struct coproc
*));
1428 static struct cpelement
*cpl_delete
__P((pid_t
));
1429 static void cpl_flush
__P((void));
1430 static struct cpelement
*cpl_search
__P((pid_t
));
1431 static struct cpelement
*cpl_searchbyname
__P((char *));
1432 static void cpl_prune
__P((void));
1434 Coproc sh_coproc
= { 0, NO_PID
, -1, -1, 0, 0 };
1436 cplist_t coproc_list
= {0, 0, 0};
1438 /* Functions to manage the list of exited background pids whose status has
1441 static struct cpelement
*
1445 struct cpelement
*cpe
;
1447 cpe
= (struct cpelement
*)xmalloc (sizeof (struct cpelement
));
1449 cpe
->next
= (struct cpelement
*)0;
1455 struct cpelement
*cpe
;
1460 static struct cpelement
*
1464 struct cpelement
*cpe
;
1466 cpe
= cpe_alloc (cp
);
1468 if (coproc_list
.head
== 0)
1470 coproc_list
.head
= coproc_list
.tail
= cpe
;
1471 coproc_list
.ncoproc
= 0; /* just to make sure */
1475 coproc_list
.tail
->next
= cpe
;
1476 coproc_list
.tail
= cpe
;
1478 coproc_list
.ncoproc
++;
1483 static struct cpelement
*
1487 struct cpelement
*prev
, *p
;
1489 for (prev
= p
= coproc_list
.head
; p
; prev
= p
, p
= p
->next
)
1490 if (p
->coproc
->c_pid
== pid
)
1492 prev
->next
= p
->next
; /* remove from list */
1497 return 0; /* not found */
1500 itrace("cpl_delete: deleting %d", pid
);
1503 /* Housekeeping in the border cases. */
1504 if (p
== coproc_list
.head
)
1505 coproc_list
.head
= coproc_list
.head
->next
;
1506 else if (p
== coproc_list
.tail
)
1507 coproc_list
.tail
= prev
;
1509 coproc_list
.ncoproc
--;
1510 if (coproc_list
.ncoproc
== 0)
1511 coproc_list
.head
= coproc_list
.tail
= 0;
1512 else if (coproc_list
.ncoproc
== 1)
1513 coproc_list
.tail
= coproc_list
.head
; /* just to make sure */
1518 /* Clear out the list of saved statuses */
1522 struct cpelement
*cpe
, *p
;
1524 for (cpe
= coproc_list
.head
; cpe
; )
1529 coproc_dispose (p
->coproc
);
1533 coproc_list
.head
= coproc_list
.tail
= 0;
1534 coproc_list
.ncoproc
= 0;
1537 /* Search for PID in the list of coprocs; return the cpelement struct if
1538 found. If not found, return NULL. */
1539 static struct cpelement
*
1543 struct cpelement
*cp
;
1545 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1546 if (cp
->coproc
->c_pid
== pid
)
1548 return (struct cpelement
*)NULL
;
1551 /* Search for the coproc named NAME in the list of coprocs; return the
1552 cpelement struct if found. If not found, return NULL. */
1553 static struct cpelement
*
1554 cpl_searchbyname (name
)
1557 struct cpelement
*cp
;
1559 for (cp
= coproc_list
.head
; cp
; cp
= cp
->next
)
1560 if (STREQ (cp
->coproc
->c_name
, name
))
1562 return (struct cpelement
*)NULL
;
1569 struct cpelement
*cp
;
1571 while (coproc_list
.head
&& coproc_list
.ncoproc
> COPROC_MAX
)
1573 cp
= coproc_list
.head
;
1574 coproc_list
.head
= coproc_list
.head
->next
;
1575 coproc_dispose (cp
->coproc
);
1577 coproc_list
.ncoproc
--;
1582 /* These currently use a single global "shell coproc" but are written in a
1583 way to not preclude additional coprocs later (using the list management
1587 getcoprocbypid (pid
)
1590 return (pid
== sh_coproc
.c_pid
? &sh_coproc
: 0);
1594 getcoprocbyname (name
)
1597 return ((sh_coproc
.c_name
&& STREQ (sh_coproc
.c_name
, name
)) ? &sh_coproc
: 0);
1606 cp
->c_rfd
= cp
->c_wfd
= -1;
1607 cp
->c_rsave
= cp
->c_wsave
= -1;
1608 cp
->c_flags
= cp
->c_status
= 0;
1612 coproc_alloc (name
, pid
)
1618 cp
= &sh_coproc
; /* XXX */
1621 cp
->c_name
= savestring (name
);
1634 coproc_unsetvars (cp
);
1640 /* Placeholder for now. */
1644 coproc_dispose (&sh_coproc
);
1661 cp
->c_rsave
= cp
->c_wsave
= -1;
1667 coproc_close (&sh_coproc
);
1671 coproc_rclose (cp
, fd
)
1675 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
1683 coproc_wclose (cp
, fd
)
1687 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
1695 coproc_checkfd (cp
, fd
)
1702 if (cp
->c_rfd
>= 0 && cp
->c_rfd
== fd
)
1703 update
= cp
->c_rfd
= -1;
1704 if (cp
->c_wfd
>= 0 && cp
->c_wfd
== fd
)
1705 update
= cp
->c_wfd
= -1;
1707 coproc_setvars (cp
);
1714 coproc_checkfd (&sh_coproc
, fd
);
1718 coproc_fdclose (cp
, fd
)
1722 coproc_rclose (cp
, fd
);
1723 coproc_wclose (cp
, fd
);
1724 coproc_setvars (cp
);
1731 cp
->c_rsave
= cp
->c_rfd
;
1732 cp
->c_wsave
= cp
->c_wfd
;
1736 coproc_fdrestore (cp
)
1739 cp
->c_rfd
= cp
->c_rsave
;
1740 cp
->c_wfd
= cp
->c_wsave
;
1749 cp
= getcoprocbypid (pid
);
1752 itrace("coproc_pidchk: pid %d has died", pid
);
1755 coproc_dispose (cp
);
1765 #if defined (ARRAY_VARS)
1769 if (cp
->c_name
== 0)
1772 l
= strlen (cp
->c_name
);
1773 namevar
= xmalloc (l
+ 16);
1775 #if defined (ARRAY_VARS)
1776 v
= find_variable (cp
->c_name
);
1778 v
= make_new_array_variable (cp
->c_name
);
1779 if (array_p (v
) == 0)
1780 v
= convert_var_to_array (v
);
1782 t
= itos (cp
->c_rfd
);
1784 v
= bind_array_variable (cp
->c_name
, ind
, t
, 0);
1787 t
= itos (cp
->c_wfd
);
1789 bind_array_variable (cp
->c_name
, ind
, t
, 0);
1792 sprintf (namevar
, "%s_READ", cp
->c_name
);
1793 t
= itos (cp
->c_rfd
);
1794 bind_variable (namevar
, t
, 0);
1796 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
1797 t
= itos (cp
->c_wfd
);
1798 bind_variable (namevar
, t
, 0);
1802 sprintf (namevar
, "%s_PID", cp
->c_name
);
1803 t
= itos (cp
->c_pid
);
1804 bind_variable (namevar
, t
, 0);
1811 coproc_unsetvars (cp
)
1817 if (cp
->c_name
== 0)
1820 l
= strlen (cp
->c_name
);
1821 namevar
= xmalloc (l
+ 16);
1823 sprintf (namevar
, "%s_PID", cp
->c_name
);
1824 unbind_variable (namevar
);
1826 #if defined (ARRAY_VARS)
1827 unbind_variable (cp
->c_name
);
1829 sprintf (namevar
, "%s_READ", cp
->c_name
);
1830 unbind_variable (namevar
);
1831 sprintf (namevar
, "%s_WRITE", cp
->c_name
);
1832 unbind_variable (namevar
);
1839 execute_coproc (command
, pipe_in
, pipe_out
, fds_to_close
)
1841 int pipe_in
, pipe_out
;
1842 struct fd_bitmap
*fds_to_close
;
1844 int rpipe
[2], wpipe
[2];
1849 /* XXX -- will require changes to handle multiple coprocs */
1850 if (sh_coproc
.c_pid
!= NO_PID
)
1853 internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc
.c_pid
, sh_coproc
.c_name
);
1854 return (last_command_exit_value
= EXECUTION_FAILURE
);
1856 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc
.c_pid
, sh_coproc
.c_name
);
1859 coproc_init (&sh_coproc
);
1861 command_string_index
= 0;
1862 tcmd
= make_command_string (command
);
1864 sh_openpipe ((int *)&rpipe
); /* 0 = parent read, 1 = child write */
1865 sh_openpipe ((int *)&wpipe
); /* 0 = child read, 1 = parent write */
1867 coproc_pid
= make_child (savestring (tcmd
), 1);
1868 if (coproc_pid
== 0)
1873 exit (execute_in_subshell (command
, 1, wpipe
[0], rpipe
[1], fds_to_close
));
1879 cp
= coproc_alloc (command
->value
.Coproc
->name
, coproc_pid
);
1880 cp
->c_rfd
= rpipe
[0];
1881 cp
->c_wfd
= wpipe
[1];
1883 SET_CLOSE_ON_EXEC (cp
->c_rfd
);
1884 SET_CLOSE_ON_EXEC (cp
->c_wfd
);
1886 coproc_setvars (cp
);
1889 itrace ("execute_coproc: [%d] %s", coproc_pid
, the_printed_command
);
1892 close_pipes (pipe_in
, pipe_out
);
1893 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
1894 unlink_fifo_list ();
1896 stop_pipeline (1, (COMMAND
*)NULL
);
1897 DESCRIBE_PID (coproc_pid
);
1898 run_pending_traps ();
1900 return (EXECUTION_SUCCESS
);
1905 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1907 int asynchronous
, pipe_in
, pipe_out
;
1908 struct fd_bitmap
*fds_to_close
;
1910 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
1912 struct fd_bitmap
*fd_bitmap
;
1914 #if defined (JOB_CONTROL)
1916 BLOCK_CHILD (set
, oset
);
1917 #endif /* JOB_CONTROL */
1919 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1924 while (cmd
&& cmd
->type
== cm_connection
&&
1925 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
1927 /* Make a pipeline between the two commands. */
1928 if (pipe (fildes
) < 0)
1930 sys_error (_("pipe error"));
1931 #if defined (JOB_CONTROL)
1932 terminate_current_pipeline ();
1933 kill_current_pipeline ();
1934 UNBLOCK_CHILD (oset
);
1935 #endif /* JOB_CONTROL */
1936 last_command_exit_value
= EXECUTION_FAILURE
;
1937 /* The unwind-protects installed below will take care
1938 of closing all of the open file descriptors. */
1939 throw_to_top_level ();
1940 return (EXECUTION_FAILURE
); /* XXX */
1943 /* Here is a problem: with the new file close-on-exec
1944 code, the read end of the pipe (fildes[0]) stays open
1945 in the first process, so that process will never get a
1946 SIGPIPE. There is no way to signal the first process
1947 that it should close fildes[0] after forking, so it
1948 remains open. No SIGPIPE is ever sent because there
1949 is still a file descriptor open for reading connected
1950 to the pipe. We take care of that here. This passes
1951 around a bitmap of file descriptors that must be
1952 closed after making a child process in execute_simple_command. */
1954 /* We need fd_bitmap to be at least as big as fildes[0].
1955 If fildes[0] is less than fds_to_close->size, then
1956 use fds_to_close->size. */
1957 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
1958 ? fds_to_close
->size
1961 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
1963 /* Now copy the old information into the new bitmap. */
1964 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
1966 /* And mark the pipe file descriptors to be closed. */
1967 fd_bitmap
->bitmap
[fildes
[0]] = 1;
1969 /* In case there are pipe or out-of-processes errors, we
1970 want all these file descriptors to be closed when
1971 unwind-protects are run, and the storage used for the
1972 bitmaps freed up. */
1973 begin_unwind_frame ("pipe-file-descriptors");
1974 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
1975 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
1977 add_unwind_protect (close
, prev
);
1978 dummyfd
= fildes
[1];
1979 add_unwind_protect (close
, dummyfd
);
1981 #if defined (JOB_CONTROL)
1982 add_unwind_protect (restore_signal_mask
, &oset
);
1983 #endif /* JOB_CONTROL */
1985 if (ignore_return
&& cmd
->value
.Connection
->first
)
1986 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1987 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
1988 prev
, fildes
[1], fd_bitmap
);
1996 dispose_fd_bitmap (fd_bitmap
);
1997 discard_unwind_frame ("pipe-file-descriptors");
1999 cmd
= cmd
->value
.Connection
->second
;
2002 /* Now execute the rightmost command in the pipeline. */
2003 if (ignore_return
&& cmd
)
2004 cmd
->flags
|= CMD_IGNORE_RETURN
;
2005 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
2010 #if defined (JOB_CONTROL)
2011 UNBLOCK_CHILD (oset
);
2014 return (exec_result
);
2018 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
2020 int asynchronous
, pipe_in
, pipe_out
;
2021 struct fd_bitmap
*fds_to_close
;
2024 COMMAND
*tc
, *second
;
2025 int ignore_return
, exec_result
;
2027 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
2029 switch (command
->value
.Connection
->connector
)
2031 /* Do the first command asynchronously. */
2033 tc
= command
->value
.Connection
->first
;
2035 return (EXECUTION_SUCCESS
);
2040 tc
->flags
|= CMD_IGNORE_RETURN
;
2041 tc
->flags
|= CMD_AMPERSAND
;
2043 /* If this shell was compiled without job control support,
2044 if we are currently in a subshell via `( xxx )', or if job
2045 control is not active then the standard input for an
2046 asynchronous command is forced to /dev/null. */
2047 #if defined (JOB_CONTROL)
2048 if ((subshell_environment
|| !job_control
) && !stdin_redir
)
2051 #endif /* JOB_CONTROL */
2052 tc
->flags
|= CMD_STDIN_REDIR
;
2054 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
2056 if (tc
->flags
& CMD_STDIN_REDIR
)
2057 tc
->flags
&= ~CMD_STDIN_REDIR
;
2059 second
= command
->value
.Connection
->second
;
2063 second
->flags
|= CMD_IGNORE_RETURN
;
2065 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2070 /* Just call execute command on both sides. */
2074 if (command
->value
.Connection
->first
)
2075 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2076 if (command
->value
.Connection
->second
)
2077 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2080 execute_command (command
->value
.Connection
->first
);
2082 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
2083 asynchronous
, pipe_in
, pipe_out
,
2088 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
2095 /* If we have something like `a && b &' or `a || b &', run the
2096 && or || stuff in a subshell. Force a subshell and just call
2097 execute_command_internal again. Leave asynchronous on
2098 so that we get a report from the parent shell about the
2100 command
->flags
|= CMD_FORCE_SUBSHELL
;
2101 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
2105 /* Execute the first command. If the result of that is successful
2106 and the connector is AND_AND, or the result is not successful
2107 and the connector is OR_OR, then execute the second command,
2108 otherwise return. */
2110 if (command
->value
.Connection
->first
)
2111 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
2113 exec_result
= execute_command (command
->value
.Connection
->first
);
2115 if (((command
->value
.Connection
->connector
== AND_AND
) &&
2116 (exec_result
== EXECUTION_SUCCESS
)) ||
2117 ((command
->value
.Connection
->connector
== OR_OR
) &&
2118 (exec_result
!= EXECUTION_SUCCESS
)))
2120 if (ignore_return
&& command
->value
.Connection
->second
)
2121 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
2123 exec_result
= execute_command (command
->value
.Connection
->second
);
2128 command_error ("execute_connection", CMDERR_BADCONN
, command
->value
.Connection
->connector
, 0);
2129 jump_to_top_level (DISCARD
);
2130 exec_result
= EXECUTION_FAILURE
;
2139 if (!interactive_shell) \
2140 reap_dead_jobs (); \
2144 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2147 execute_for_command (for_command
)
2148 FOR_COM
*for_command
;
2150 register WORD_LIST
*releaser
, *list
;
2153 int retval
, save_line_number
;
2155 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
2158 save_line_number
= line_number
;
2159 if (check_identifier (for_command
->name
, 1) == 0)
2161 if (posixly_correct
&& interactive_shell
== 0)
2163 last_command_exit_value
= EX_USAGE
;
2164 jump_to_top_level (ERREXIT
);
2166 return (EXECUTION_FAILURE
);
2170 identifier
= for_command
->name
->word
;
2172 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
2174 begin_unwind_frame ("for");
2175 add_unwind_protect (dispose_words
, releaser
);
2178 if (lexical_scoping
)
2180 old_value
= copy_variable (find_variable (identifier
));
2182 add_unwind_protect (dispose_variable
, old_value
);
2186 if (for_command
->flags
& CMD_IGNORE_RETURN
)
2187 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2189 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
2193 line_number
= for_command
->line
;
2195 /* Remember what this command looks like, for debugger. */
2196 command_string_index
= 0;
2197 print_for_command_head (for_command
);
2199 if (echo_command_at_execute
)
2200 xtrace_print_for_command_head (for_command
);
2202 /* Save this command unless it's a trap command and we're not running
2205 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2207 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2210 FREE (the_printed_command_except_trap
);
2211 the_printed_command_except_trap
= savestring (the_printed_command
);
2214 retval
= run_debug_trap ();
2215 #if defined (DEBUGGER)
2216 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2217 skip the command. */
2218 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2222 this_command_name
= (char *)NULL
;
2223 v
= bind_variable (identifier
, list
->word
->word
, 0);
2224 if (readonly_p (v
) || noassign_p (v
))
2226 line_number
= save_line_number
;
2227 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2229 last_command_exit_value
= EXECUTION_FAILURE
;
2230 jump_to_top_level (FORCE_EOF
);
2234 dispose_words (releaser
);
2235 discard_unwind_frame ("for");
2237 return (EXECUTION_FAILURE
);
2240 retval
= execute_command (for_command
->action
);
2259 line_number
= save_line_number
;
2262 if (lexical_scoping
)
2265 unbind_variable (identifier
);
2268 SHELL_VAR
*new_value
;
2270 new_value
= bind_variable (identifier
, value_cell(old_value
), 0);
2271 new_value
->attributes
= old_value
->attributes
;
2272 dispose_variable (old_value
);
2277 dispose_words (releaser
);
2278 discard_unwind_frame ("for");
2282 #if defined (ARITH_FOR_COMMAND)
2283 /* Execute an arithmetic for command. The syntax is
2285 for (( init ; step ; test ))
2290 The execution should be exactly equivalent to
2293 while eval \(\( test \)\) ; do
2299 eval_arith_for_expr (l
, okp
)
2307 new = expand_words_no_vars (l
);
2310 if (echo_command_at_execute
)
2311 xtrace_print_arith_cmd (new);
2312 this_command_name
= "(("; /* )) for expression error messages */
2314 command_string_index
= 0;
2315 print_arith_command (new);
2316 if (signal_in_progress (DEBUG_TRAP
) == 0)
2318 FREE (the_printed_command_except_trap
);
2319 the_printed_command_except_trap
= savestring (the_printed_command
);
2322 r
= run_debug_trap ();
2323 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2324 skip the command. */
2325 #if defined (DEBUGGER)
2326 if (debugging_mode
== 0 || r
== EXECUTION_SUCCESS
)
2327 expresult
= evalexp (new->word
->word
, okp
);
2335 expresult
= evalexp (new->word
->word
, okp
);
2337 dispose_words (new);
2349 execute_arith_for_command (arith_for_command
)
2350 ARITH_FOR_COM
*arith_for_command
;
2353 int expok
, body_status
, arith_lineno
, save_lineno
;
2355 body_status
= EXECUTION_SUCCESS
;
2357 save_lineno
= line_number
;
2359 if (arith_for_command
->flags
& CMD_IGNORE_RETURN
)
2360 arith_for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2362 this_command_name
= "(("; /* )) for expression error messages */
2364 /* save the starting line number of the command so we can reset
2365 line_number before executing each expression -- for $LINENO
2366 and the DEBUG trap. */
2367 line_number
= arith_lineno
= arith_for_command
->line
;
2368 if (variable_context
&& interactive_shell
)
2369 line_number
-= function_line_number
;
2371 /* Evaluate the initialization expression. */
2372 expresult
= eval_arith_for_expr (arith_for_command
->init
, &expok
);
2375 line_number
= save_lineno
;
2376 return (EXECUTION_FAILURE
);
2381 /* Evaluate the test expression. */
2382 line_number
= arith_lineno
;
2383 expresult
= eval_arith_for_expr (arith_for_command
->test
, &expok
);
2384 line_number
= save_lineno
;
2388 body_status
= EXECUTION_FAILURE
;
2395 /* Execute the body of the arithmetic for command. */
2397 body_status
= execute_command (arith_for_command
->action
);
2400 /* Handle any `break' or `continue' commands executed by the body. */
2414 /* Evaluate the step expression. */
2415 line_number
= arith_lineno
;
2416 expresult
= eval_arith_for_expr (arith_for_command
->step
, &expok
);
2417 line_number
= save_lineno
;
2421 body_status
= EXECUTION_FAILURE
;
2427 line_number
= save_lineno
;
2429 return (body_status
);
2433 #if defined (SELECT_COMMAND)
2434 static int LINES
, COLS
, tabsize
;
2436 #define RP_SPACE ") "
2437 #define RP_SPACE_LEN 2
2439 /* XXX - does not handle numbers > 1000000 at all. */
2440 #define NUMBER_LEN(s) \
2444 : ((s < 10000) ? 4 \
2445 : ((s < 100000) ? 5 \
2449 print_index_and_element (len
, ind
, list
)
2453 register WORD_LIST
*l
;
2458 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
2460 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
2461 return (STRLEN (l
->word
->word
));
2470 if ((to
/ tabsize
) > (from
/ tabsize
))
2472 putc ('\t', stderr
);
2473 from
+= tabsize
- from
% tabsize
;
2484 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
2486 int list_len
, max_elem_len
, indices_len
;
2488 int ind
, row
, elem_len
, pos
, cols
, rows
;
2489 int first_column_indices_len
, other_indices_len
;
2493 putc ('\n', stderr
);
2497 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
2500 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
2501 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
2509 first_column_indices_len
= NUMBER_LEN (rows
);
2510 other_indices_len
= indices_len
;
2512 for (row
= 0; row
< rows
; row
++)
2518 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
2519 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
2520 elem_len
+= indices_len
+ RP_SPACE_LEN
;
2522 if (ind
>= list_len
)
2524 indent (pos
+ elem_len
, pos
+ max_elem_len
);
2525 pos
+= max_elem_len
;
2527 putc ('\n', stderr
);
2531 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2532 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2533 If the number is between 1 and LIST_LEN, return that selection. If EOF
2534 is read, return a null string. If a blank line is entered, or an invalid
2535 number is entered, the loop is executed again. */
2537 select_query (list
, list_len
, prompt
, print_menu
)
2543 int max_elem_len
, indices_len
, len
;
2546 char *repl_string
, *t
;
2548 t
= get_string_value ("LINES");
2549 LINES
= (t
&& *t
) ? atoi (t
) : 24;
2550 t
= get_string_value ("COLUMNS");
2551 COLS
= (t
&& *t
) ? atoi (t
) : 80;
2554 t
= get_string_value ("TABSIZE");
2555 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
2563 for (l
= list
; l
; l
= l
->next
)
2565 len
= STRLEN (l
->word
->word
);
2566 if (len
> max_elem_len
)
2569 indices_len
= NUMBER_LEN (list_len
);
2570 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
2575 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
2576 fprintf (stderr
, "%s", prompt
);
2580 if (read_builtin ((WORD_LIST
*)NULL
) == EXECUTION_FAILURE
)
2583 return ((char *)NULL
);
2585 repl_string
= get_string_value ("REPLY");
2586 if (*repl_string
== 0)
2591 if (legal_number (repl_string
, &reply
) == 0)
2593 if (reply
< 1 || reply
> list_len
)
2596 for (l
= list
; l
&& --reply
; l
= l
->next
)
2598 return (l
->word
->word
);
2602 /* Execute a SELECT command. The syntax is:
2603 SELECT word IN list DO command_list DONE
2604 Only `break' or `return' in command_list will terminate
2607 execute_select_command (select_command
)
2608 SELECT_COM
*select_command
;
2610 WORD_LIST
*releaser
, *list
;
2612 char *identifier
, *ps3_prompt
, *selection
;
2613 int retval
, list_len
, show_menu
, save_line_number
;
2615 if (check_identifier (select_command
->name
, 1) == 0)
2616 return (EXECUTION_FAILURE
);
2618 save_line_number
= line_number
;
2619 line_number
= select_command
->line
;
2621 command_string_index
= 0;
2622 print_select_command_head (select_command
);
2624 if (echo_command_at_execute
)
2625 xtrace_print_select_command_head (select_command
);
2628 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2630 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2633 FREE (the_printed_command_except_trap
);
2634 the_printed_command_except_trap
= savestring (the_printed_command
);
2637 retval
= run_debug_trap ();
2638 #if defined (DEBUGGER)
2639 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2640 skip the command. */
2641 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2642 return (EXECUTION_SUCCESS
);
2646 identifier
= select_command
->name
->word
;
2648 /* command and arithmetic substitution, parameter and variable expansion,
2649 word splitting, pathname expansion, and quote removal. */
2650 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
2651 list_len
= list_length (list
);
2652 if (list
== 0 || list_len
== 0)
2655 dispose_words (list
);
2656 line_number
= save_line_number
;
2657 return (EXECUTION_SUCCESS
);
2660 begin_unwind_frame ("select");
2661 add_unwind_protect (dispose_words
, releaser
);
2663 if (select_command
->flags
& CMD_IGNORE_RETURN
)
2664 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2666 retval
= EXECUTION_SUCCESS
;
2671 line_number
= select_command
->line
;
2672 ps3_prompt
= get_string_value ("PS3");
2673 if (ps3_prompt
== 0)
2677 selection
= select_query (list
, list_len
, ps3_prompt
, show_menu
);
2681 /* select_query returns EXECUTION_FAILURE if the read builtin
2682 fails, so we want to return failure in this case. */
2683 retval
= EXECUTION_FAILURE
;
2687 v
= bind_variable (identifier
, selection
, 0);
2688 if (readonly_p (v
) || noassign_p (v
))
2690 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2692 last_command_exit_value
= EXECUTION_FAILURE
;
2693 jump_to_top_level (FORCE_EOF
);
2697 dispose_words (releaser
);
2698 discard_unwind_frame ("select");
2700 line_number
= save_line_number
;
2701 return (EXECUTION_FAILURE
);
2705 retval
= execute_command (select_command
->action
);
2723 #if defined (KSH_COMPATIBLE_SELECT)
2725 selection
= get_string_value ("REPLY");
2726 if (selection
&& *selection
== '\0')
2732 line_number
= save_line_number
;
2734 dispose_words (releaser
);
2735 discard_unwind_frame ("select");
2738 #endif /* SELECT_COMMAND */
2740 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2741 The pattern_list is a linked list of pattern clauses; each clause contains
2742 some patterns to compare word_desc against, and an associated command to
2745 execute_case_command (case_command
)
2746 CASE_COM
*case_command
;
2748 register WORD_LIST
*list
;
2749 WORD_LIST
*wlist
, *es
;
2750 PATTERN_LIST
*clauses
;
2751 char *word
, *pattern
;
2752 int retval
, match
, ignore_return
, save_line_number
;
2754 save_line_number
= line_number
;
2755 line_number
= case_command
->line
;
2757 command_string_index
= 0;
2758 print_case_command_head (case_command
);
2760 if (echo_command_at_execute
)
2761 xtrace_print_case_command_head (case_command
);
2764 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2766 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2769 FREE (the_printed_command_except_trap
);
2770 the_printed_command_except_trap
= savestring (the_printed_command
);
2773 retval
= run_debug_trap();
2774 #if defined (DEBUGGER)
2775 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2776 skip the command. */
2777 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2779 line_number
= save_line_number
;
2780 return (EXECUTION_SUCCESS
);
2784 wlist
= expand_word_unsplit (case_command
->word
, 0);
2785 word
= wlist
? string_list (wlist
) : savestring ("");
2786 dispose_words (wlist
);
2788 retval
= EXECUTION_SUCCESS
;
2789 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
2791 begin_unwind_frame ("case");
2792 add_unwind_protect ((Function
*)xfree
, word
);
2794 #define EXIT_CASE() goto exit_case_command
2796 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
2799 for (list
= clauses
->patterns
; list
; list
= list
->next
)
2801 es
= expand_word_leave_quoted (list
->word
, 0);
2803 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
2804 pattern
= quote_string_for_globbing (es
->word
->word
, QGLOB_CVTNULL
);
2807 pattern
= (char *)xmalloc (1);
2811 /* Since the pattern does not undergo quote removal (as per
2812 Posix.2, section 3.9.4.3), the strmatch () call must be able
2813 to recognize backslashes as escape characters. */
2814 match
= strmatch (pattern
, word
, FNMATCH_EXTFLAG
|FNMATCH_IGNCASE
) != FNM_NOMATCH
;
2823 if (clauses
->action
&& ignore_return
)
2824 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
2825 retval
= execute_command (clauses
->action
);
2827 while ((clauses
->flags
& CASEPAT_FALLTHROUGH
) && (clauses
= clauses
->next
));
2828 if ((clauses
->flags
& CASEPAT_TESTNEXT
) == 0)
2840 discard_unwind_frame ("case");
2841 line_number
= save_line_number
;
2848 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2849 Repeatedly execute action while executing test produces
2850 EXECUTION_SUCCESS. */
2852 execute_while_command (while_command
)
2853 WHILE_COM
*while_command
;
2855 return (execute_while_or_until (while_command
, CMD_WHILE
));
2858 /* UNTIL is just like WHILE except that the test result is negated. */
2860 execute_until_command (while_command
)
2861 WHILE_COM
*while_command
;
2863 return (execute_while_or_until (while_command
, CMD_UNTIL
));
2866 /* The body for both while and until. The only difference between the
2867 two is that the test value is treated differently. TYPE is
2868 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2869 be EXECUTION_SUCCESS if no commands in the body are executed, and
2870 the status of the last command executed in the body otherwise. */
2872 execute_while_or_until (while_command
, type
)
2873 WHILE_COM
*while_command
;
2876 int return_value
, body_status
;
2878 body_status
= EXECUTION_SUCCESS
;
2881 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2882 if (while_command
->flags
& CMD_IGNORE_RETURN
)
2883 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2887 return_value
= execute_command (while_command
->test
);
2890 /* Need to handle `break' in the test when we would break out of the
2891 loop. The job control code will set `breaking' to loop_level
2892 when a job in a loop is stopped with SIGTSTP. If the stopped job
2893 is in the loop test, `breaking' will not be reset unless we do
2894 this, and the shell will cease to execute commands. */
2895 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
2901 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
2909 body_status
= execute_command (while_command
->action
);
2927 return (body_status
);
2930 /* IF test THEN command [ELSE command].
2931 IF also allows ELIF in the place of ELSE IF, but
2932 the parser makes *that* stupidity transparent. */
2934 execute_if_command (if_command
)
2937 int return_value
, save_line_number
;
2939 save_line_number
= line_number
;
2940 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2941 return_value
= execute_command (if_command
->test
);
2942 line_number
= save_line_number
;
2944 if (return_value
== EXECUTION_SUCCESS
)
2948 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2949 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
2951 return (execute_command (if_command
->true_case
));
2957 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2958 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
2960 return (execute_command (if_command
->false_case
));
2964 #if defined (DPAREN_ARITHMETIC)
2966 execute_arith_command (arith_command
)
2967 ARITH_COM
*arith_command
;
2969 int expok
, save_line_number
, retval
;
2976 save_line_number
= line_number
;
2977 this_command_name
= "(("; /* )) */
2978 line_number
= arith_command
->line
;
2979 /* If we're in a function, update the line number information. */
2980 if (variable_context
&& interactive_shell
)
2981 line_number
-= function_line_number
;
2983 command_string_index
= 0;
2984 print_arith_command (arith_command
->exp
);
2986 if (signal_in_progress (DEBUG_TRAP
) == 0)
2988 FREE (the_printed_command_except_trap
);
2989 the_printed_command_except_trap
= savestring (the_printed_command
);
2992 /* Run the debug trap before each arithmetic command, but do it after we
2993 update the line number information and before we expand the various
2994 words in the expression. */
2995 retval
= run_debug_trap ();
2996 #if defined (DEBUGGER)
2997 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2998 skip the command. */
2999 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3001 line_number
= save_line_number
;
3002 return (EXECUTION_SUCCESS
);
3006 new = expand_words_no_vars (arith_command
->exp
);
3008 /* If we're tracing, make a new word list with `((' at the front and `))'
3009 at the back and print it. */
3010 if (echo_command_at_execute
)
3011 xtrace_print_arith_cmd (new);
3015 exp
= new->next
? string_list (new) : new->word
->word
;
3016 expresult
= evalexp (exp
, &expok
);
3017 line_number
= save_line_number
;
3018 if (exp
!= new->word
->word
)
3020 dispose_words (new);
3029 return (EXECUTION_FAILURE
);
3031 return (expresult
== 0 ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
3033 #endif /* DPAREN_ARITHMETIC */
3035 #if defined (COND_COMMAND)
3037 static char * const nullstr
= "";
3040 execute_cond_node (cond
)
3043 int result
, invert
, patmatch
, rmatch
, mflags
;
3046 invert
= (cond
->flags
& CMD_INVERT_RETURN
);
3048 if (cond
->type
== COND_EXPR
)
3049 result
= execute_cond_node (cond
->left
);
3050 else if (cond
->type
== COND_OR
)
3052 result
= execute_cond_node (cond
->left
);
3053 if (result
!= EXECUTION_SUCCESS
)
3054 result
= execute_cond_node (cond
->right
);
3056 else if (cond
->type
== COND_AND
)
3058 result
= execute_cond_node (cond
->left
);
3059 if (result
== EXECUTION_SUCCESS
)
3060 result
= execute_cond_node (cond
->right
);
3062 else if (cond
->type
== COND_UNARY
)
3064 arg1
= cond_expand_word (cond
->left
->op
, 0);
3067 if (echo_command_at_execute
)
3068 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, (char *)NULL
);
3069 result
= unary_test (cond
->op
->word
, arg1
) ? EXECUTION_SUCCESS
: EXECUTION_FAILURE
;
3070 if (arg1
!= nullstr
)
3073 else if (cond
->type
== COND_BINARY
)
3076 patmatch
= ((cond
->op
->word
[1] == '=') && (cond
->op
->word
[2] == '\0') &&
3077 (cond
->op
->word
[0] == '!' || cond
->op
->word
[0] == '=') ||
3078 (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '\0'));
3079 #if defined (COND_REGEXP)
3080 rmatch
= (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '~' &&
3081 cond
->op
->word
[2] == '\0');
3084 arg1
= cond_expand_word (cond
->left
->op
, 0);
3087 arg2
= cond_expand_word (cond
->right
->op
,
3088 (rmatch
&& shell_compatibility_level
> 31) ? 2 : (patmatch
? 1 : 0));
3092 if (echo_command_at_execute
)
3093 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, arg2
);
3095 #if defined (COND_REGEXP)
3098 mflags
= SHMAT_PWARN
;
3099 #if defined (ARRAY_VARS)
3100 mflags
|= SHMAT_SUBEXP
;
3103 result
= sh_regmatch (arg1
, arg2
, mflags
);
3106 #endif /* COND_REGEXP */
3111 result
= binary_test (cond
->op
->word
, arg1
, arg2
, TEST_PATMATCH
|TEST_ARITHEXP
)
3113 : EXECUTION_FAILURE
;
3116 if (arg1
!= nullstr
)
3118 if (arg2
!= nullstr
)
3123 command_error ("execute_cond_node", CMDERR_BADTYPE
, cond
->type
, 0);
3124 jump_to_top_level (DISCARD
);
3125 result
= EXECUTION_FAILURE
;
3129 result
= (result
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
;
3135 execute_cond_command (cond_command
)
3136 COND_COM
*cond_command
;
3138 int retval
, save_line_number
;
3140 retval
= EXECUTION_SUCCESS
;
3141 save_line_number
= line_number
;
3143 this_command_name
= "[[";
3144 line_number
= cond_command
->line
;
3145 /* If we're in a function, update the line number information. */
3146 if (variable_context
&& interactive_shell
)
3147 line_number
-= function_line_number
;
3149 command_string_index
= 0;
3150 print_cond_command (cond_command
);
3152 if (signal_in_progress (DEBUG_TRAP
) == 0)
3154 FREE (the_printed_command_except_trap
);
3155 the_printed_command_except_trap
= savestring (the_printed_command
);
3158 /* Run the debug trap before each conditional command, but do it after we
3159 update the line number information. */
3160 retval
= run_debug_trap ();
3161 #if defined (DEBUGGER)
3162 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3163 skip the command. */
3164 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
3166 line_number
= save_line_number
;
3167 return (EXECUTION_SUCCESS
);
3172 debug_print_cond_command (cond_command
);
3175 last_command_exit_value
= retval
= execute_cond_node (cond_command
);
3176 line_number
= save_line_number
;
3179 #endif /* COND_COMMAND */
3189 var
= bind_variable ("_", arg
, 0);
3190 VUNSETATTR (var
, att_exported
);
3193 /* Execute a null command. Fork a subshell if the command uses pipes or is
3194 to be run asynchronously. This handles all the side effects that are
3195 supposed to take place. */
3197 execute_null_command (redirects
, pipe_in
, pipe_out
, async
)
3198 REDIRECT
*redirects
;
3199 int pipe_in
, pipe_out
, async
;
3203 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
3205 /* We have a null command, but we really want a subshell to take
3206 care of it. Just fork, do piping and redirections, and exit. */
3207 if (make_child ((char *)NULL
, async
) == 0)
3209 /* Cancel traps, in trap.c. */
3210 restore_original_signals (); /* XXX */
3212 do_piping (pipe_in
, pipe_out
);
3214 #if defined (COPROCESS_SUPPORT)
3218 subshell_environment
= 0;
3220 subshell_environment
|= SUBSHELL_ASYNC
;
3221 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3222 subshell_environment
|= SUBSHELL_PIPE
;
3224 if (do_redirections (redirects
, RX_ACTIVE
) == 0)
3225 exit (EXECUTION_SUCCESS
);
3227 exit (EXECUTION_FAILURE
);
3231 close_pipes (pipe_in
, pipe_out
);
3232 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3233 unlink_fifo_list ();
3235 return (EXECUTION_SUCCESS
);
3240 /* Even if there aren't any command names, pretend to do the
3241 redirections that are specified. The user expects the side
3242 effects to take place. If the redirections fail, then return
3243 failure. Otherwise, if a command substitution took place while
3244 expanding the command or a redirection, return the value of that
3245 substitution. Otherwise, return EXECUTION_SUCCESS. */
3247 r
= do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
);
3248 cleanup_redirects (redirection_undo_list
);
3249 redirection_undo_list
= (REDIRECT
*)NULL
;
3252 return (EXECUTION_FAILURE
);
3253 else if (last_command_subst_pid
!= NO_PID
)
3254 return (last_command_exit_value
);
3256 return (EXECUTION_SUCCESS
);
3260 /* This is a hack to suppress word splitting for assignment statements
3261 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3263 fix_assignment_words (words
)
3276 for (w
= words
; w
; w
= w
->next
)
3277 if (w
->word
->flags
& W_ASSIGNMENT
)
3281 b
= builtin_address_internal (words
->word
->word
, 0);
3282 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3284 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3285 words
->word
->flags
|= W_ASSNBLTIN
;
3287 w
->word
->flags
|= (W_NOSPLIT
|W_NOGLOB
|W_TILDEEXP
|W_ASSIGNARG
);
3288 #if defined (ARRAY_VARS)
3290 w
->word
->flags
|= W_ASSIGNASSOC
;
3293 #if defined (ARRAY_VARS)
3294 /* Note that we saw an associative array option to a builtin that takes
3295 assignment statements. This is a bit of a kludge. */
3296 else if (w
->word
->word
[0] == '-' && strchr (w
->word
->word
, 'A'))
3300 b
= builtin_address_internal (words
->word
->word
, 0);
3301 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
3303 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
3304 words
->word
->flags
|= W_ASSNBLTIN
;
3306 if (words
->word
->flags
& W_ASSNBLTIN
)
3312 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3313 to PATHNAME, is a directory. Used by the autocd code below. */
3315 is_dirname (pathname
)
3319 temp
= search_for_command (pathname
);
3320 return (temp
? file_isdir (temp
) : file_isdir (pathname
));
3323 /* The meaty part of all the executions. We have to start hacking the
3324 real execution of commands here. Fork a process, set things up,
3325 execute the command. */
3327 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
3328 SIMPLE_COM
*simple_command
;
3329 int pipe_in
, pipe_out
, async
;
3330 struct fd_bitmap
*fds_to_close
;
3332 WORD_LIST
*words
, *lastword
;
3333 char *command_line
, *lastarg
, *temp
;
3334 int first_word_quoted
, result
, builtin_is_special
, already_forked
, dofork
;
3335 pid_t old_last_async_pid
;
3336 sh_builtin_func_t
*builtin
;
3339 result
= EXECUTION_SUCCESS
;
3340 special_builtin_failed
= builtin_is_special
= 0;
3341 command_line
= (char *)0;
3343 /* If we're in a function, update the line number information. */
3344 if (variable_context
&& interactive_shell
)
3345 line_number
-= function_line_number
;
3347 /* Remember what this command line looks like at invocation. */
3348 command_string_index
= 0;
3349 print_simple_command (simple_command
);
3352 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
3354 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
3357 FREE (the_printed_command_except_trap
);
3358 the_printed_command_except_trap
= the_printed_command
? savestring (the_printed_command
) : (char *)0;
3361 /* Run the debug trap before each simple command, but do it after we
3362 update the line number information. */
3363 result
= run_debug_trap ();
3364 #if defined (DEBUGGER)
3365 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3366 skip the command. */
3367 if (debugging_mode
&& result
!= EXECUTION_SUCCESS
)
3368 return (EXECUTION_SUCCESS
);
3372 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
) : 0;
3374 last_command_subst_pid
= NO_PID
;
3375 old_last_async_pid
= last_asynchronous_pid
;
3377 already_forked
= dofork
= 0;
3379 /* If we're in a pipeline or run in the background, set DOFORK so we
3380 make the child early, before word expansion. This keeps assignment
3381 statements from affecting the parent shell's environment when they
3383 dofork
= pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
;
3385 /* Something like `%2 &' should restart job 2 in the background, not cause
3386 the shell to fork here. */
3387 if (dofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&&
3388 simple_command
->words
&& simple_command
->words
->word
&&
3389 simple_command
->words
->word
->word
&&
3390 (simple_command
->words
->word
->word
[0] == '%'))
3395 /* Do this now, because execute_disk_command will do it anyway in the
3396 vast majority of cases. */
3397 maybe_make_export_env ();
3399 /* Don't let a DEBUG trap overwrite the command string to be saved with
3400 the process/job associated with this child. */
3401 if (make_child (savestring (the_printed_command_except_trap
), async
) == 0)
3404 simple_command
->flags
|= CMD_NO_FORK
;
3406 subshell_environment
= SUBSHELL_FORK
;
3407 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3408 subshell_environment
|= SUBSHELL_PIPE
;
3410 subshell_environment
|= SUBSHELL_ASYNC
;
3412 /* We need to do this before piping to handle some really
3413 pathological cases where one of the pipe file descriptors
3416 close_fd_bitmap (fds_to_close
);
3418 do_piping (pipe_in
, pipe_out
);
3419 pipe_in
= pipe_out
= NO_PIPE
;
3420 #if defined (COPROCESS_SUPPORT)
3424 last_asynchronous_pid
= old_last_async_pid
;
3428 close_pipes (pipe_in
, pipe_out
);
3429 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3430 unlink_fifo_list ();
3432 command_line
= (char *)NULL
; /* don't free this. */
3433 bind_lastarg ((char *)NULL
);
3438 /* If we are re-running this as the result of executing the `command'
3439 builtin, do not expand the command words a second time. */
3440 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
3442 current_fds_to_close
= fds_to_close
;
3443 fix_assignment_words (simple_command
->words
);
3444 words
= expand_words (simple_command
->words
);
3445 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
3448 words
= copy_word_list (simple_command
->words
);
3450 /* It is possible for WORDS not to have anything left in it.
3451 Perhaps all the words consisted of `$foo', and there was
3452 no variable `$foo'. */
3455 this_command_name
= 0;
3456 result
= execute_null_command (simple_command
->redirects
,
3458 already_forked
? 0 : async
);
3463 bind_lastarg ((char *)NULL
);
3464 set_pipestatus_from_exit (result
);
3469 lastarg
= (char *)NULL
;
3471 begin_unwind_frame ("simple-command");
3473 if (echo_command_at_execute
)
3474 xtrace_print_word_list (words
, 1);
3476 builtin
= (sh_builtin_func_t
*)NULL
;
3477 func
= (SHELL_VAR
*)NULL
;
3478 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
3480 /* Posix.2 says special builtins are found before functions. We
3481 don't set builtin_is_special anywhere other than here, because
3482 this path is followed only when the `command' builtin is *not*
3483 being used, and we don't want to exit the shell if a special
3484 builtin executed with `command builtin' fails. `command' is not
3485 a special builtin. */
3486 if (posixly_correct
)
3488 builtin
= find_special_builtin (words
->word
->word
);
3490 builtin_is_special
= 1;
3493 func
= find_function (words
->word
->word
);
3496 /* In POSIX mode, assignment errors in the temporary environment cause a
3497 non-interactive shell to exit. */
3498 if (builtin_is_special
&& interactive_shell
== 0 && tempenv_assign_error
)
3500 last_command_exit_value
= EXECUTION_FAILURE
;
3501 jump_to_top_level (ERREXIT
);
3504 add_unwind_protect (dispose_words
, words
);
3507 /* Bind the last word in this command to "$_" after execution. */
3508 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
3510 lastarg
= lastword
->word
->word
;
3512 #if defined (JOB_CONTROL)
3513 /* Is this command a job control related thing? */
3514 if (words
->word
->word
[0] == '%' && already_forked
== 0)
3516 this_command_name
= async
? "bg" : "fg";
3517 last_shell_builtin
= this_shell_builtin
;
3518 this_shell_builtin
= builtin_address (this_command_name
);
3519 result
= (*this_shell_builtin
) (words
);
3523 /* One other possiblilty. The user may want to resume an existing job.
3524 If they do, find out whether this word is a candidate for a running
3526 if (job_control
&& already_forked
== 0 && async
== 0 &&
3527 !first_word_quoted
&&
3529 words
->word
->word
[0] &&
3530 !simple_command
->redirects
&&
3531 pipe_in
== NO_PIPE
&&
3532 pipe_out
== NO_PIPE
&&
3533 (temp
= get_string_value ("auto_resume")))
3535 int job
, jflags
, started_status
;
3537 jflags
= JM_STOPPED
|JM_FIRSTMATCH
;
3538 if (STREQ (temp
, "exact"))
3540 else if (STREQ (temp
, "substring"))
3541 jflags
|= JM_SUBSTRING
;
3543 jflags
|= JM_PREFIX
;
3544 job
= get_job_by_name (words
->word
->word
, jflags
);
3547 run_unwind_frame ("simple-command");
3548 this_command_name
= "fg";
3549 last_shell_builtin
= this_shell_builtin
;
3550 this_shell_builtin
= builtin_address ("fg");
3552 started_status
= start_job (job
, 1);
3553 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
3556 #endif /* JOB_CONTROL */
3559 /* Remember the name of this command globally. */
3560 this_command_name
= words
->word
->word
;
3564 /* This command could be a shell builtin or a user-defined function.
3565 We have already found special builtins by this time, so we do not
3566 set builtin_is_special. If this is a function or builtin, and we
3567 have pipes, then fork a subshell in here. Otherwise, just execute
3568 the command directly. */
3569 if (func
== 0 && builtin
== 0)
3570 builtin
= find_shell_builtin (this_command_name
);
3572 last_shell_builtin
= this_shell_builtin
;
3573 this_shell_builtin
= builtin
;
3575 if (builtin
|| func
)
3578 unwind_protect_int (executing_builtin
); /* modified in execute_builtin */
3581 /* reset_terminating_signals (); */ /* XXX */
3582 /* Cancel traps, in trap.c. */
3583 restore_original_signals ();
3587 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
3588 pipe_in
== NO_PIPE
&&
3589 (stdin_redirects (simple_command
->redirects
) == 0))
3590 async_redirect_stdin ();
3591 setup_async_signals ();
3595 execute_subshell_builtin_or_function
3596 (words
, simple_command
->redirects
, builtin
, func
,
3597 pipe_in
, pipe_out
, async
, fds_to_close
,
3598 simple_command
->flags
);
3603 result
= execute_builtin_or_function
3604 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
3605 simple_command
->flags
);
3608 if (result
> EX_SHERRBASE
)
3610 result
= builtin_status (result
);
3611 if (builtin_is_special
)
3612 special_builtin_failed
= 1;
3614 /* In POSIX mode, if there are assignment statements preceding
3615 a special builtin, they persist after the builtin
3617 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
3618 merge_temporary_env ();
3622 if (result
== EX_USAGE
)
3623 result
= EX_BADUSAGE
;
3624 else if (result
> EX_SHERRBASE
)
3625 result
= EXECUTION_FAILURE
;
3628 set_pipestatus_from_exit (result
);
3634 if (autocd
&& interactive
&& words
->word
&& is_dirname (words
->word
->word
))
3636 words
= make_word_list (make_word ("cd"), words
);
3637 xtrace_print_word_list (words
, 0);
3641 if (command_line
== 0)
3642 command_line
= savestring (the_printed_command_except_trap
);
3644 #if defined (PROCESS_SUBSTITUTION)
3645 if ((subshell_environment
& SUBSHELL_COMSUB
) && (simple_command
->flags
& CMD_NO_FORK
) && fifos_pending() > 0)
3646 simple_command
->flags
&= ~CMD_NO_FORK
;
3649 execute_disk_command (words
, simple_command
->redirects
, command_line
,
3650 pipe_in
, pipe_out
, async
, fds_to_close
,
3651 simple_command
->flags
);
3654 bind_lastarg (lastarg
);
3655 FREE (command_line
);
3656 dispose_words (words
);
3657 discard_unwind_frame ("simple-command");
3658 this_command_name
= (char *)NULL
; /* points to freed memory now */
3662 /* Translate the special builtin exit statuses. We don't really need a
3663 function for this; it's a placeholder for future work. */
3665 builtin_status (result
)
3679 r
= EXECUTION_FAILURE
;
3682 r
= EXECUTION_SUCCESS
;
3689 execute_builtin (builtin
, words
, flags
, subshell
)
3690 sh_builtin_func_t
*builtin
;
3692 int flags
, subshell
;
3694 int old_e_flag
, result
, eval_unwind
;
3697 old_e_flag
= exit_immediately_on_error
;
3698 /* The eval builtin calls parse_and_execute, which does not know about
3699 the setting of flags, and always calls the execution functions with
3700 flags that will exit the shell on an error if -e is set. If the
3701 eval builtin is being called, and we're supposed to ignore the exit
3702 value of the command, we turn the -e flag off ourselves, then
3703 restore it when the command completes. This is also a problem (as
3704 below) for the command and source/. builtins. */
3705 if (subshell
== 0 && (flags
& CMD_IGNORE_RETURN
) &&
3706 (builtin
== eval_builtin
|| builtin
== command_builtin
|| builtin
== source_builtin
))
3708 begin_unwind_frame ("eval_builtin");
3709 unwind_protect_int (exit_immediately_on_error
);
3710 exit_immediately_on_error
= 0;
3716 /* The temporary environment for a builtin is supposed to apply to
3717 all commands executed by that builtin. Currently, this is a
3718 problem only with the `unset', `source' and `eval' builtins. */
3720 isbltinenv
= (builtin
== source_builtin
|| builtin
== eval_builtin
|| builtin
== unset_builtin
);
3725 begin_unwind_frame ("builtin_env");
3729 push_scope (VC_BLTNENV
, temporary_env
);
3731 add_unwind_protect (pop_scope
, (flags
& CMD_COMMAND_BUILTIN
) ? 0 : "1");
3732 temporary_env
= (HASH_TABLE
*)NULL
;
3736 /* `return' does a longjmp() back to a saved environment in execute_function.
3737 If a variable assignment list preceded the command, and the shell is
3738 running in POSIX mode, we need to merge that into the shell_variables
3739 table, since `return' is a POSIX special builtin. */
3740 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3742 begin_unwind_frame ("return_temp_env");
3743 add_unwind_protect (merge_temporary_env
, (char *)NULL
);
3746 executing_builtin
++;
3747 result
= ((*builtin
) (words
->next
));
3749 /* This shouldn't happen, but in case `return' comes back instead of
3750 longjmp'ing, we need to unwind. */
3751 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3752 discard_unwind_frame ("return_temp_env");
3754 if (subshell
== 0 && isbltinenv
)
3755 run_unwind_frame ("builtin_env");
3759 exit_immediately_on_error
+= old_e_flag
;
3760 discard_unwind_frame ("eval_builtin");
3767 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
3771 struct fd_bitmap
*fds_to_close
;
3772 int async
, subshell
;
3774 int return_val
, result
;
3775 COMMAND
*tc
, *fc
, *save_current
;
3776 char *debug_trap
, *error_trap
, *return_trap
;
3777 #if defined (ARRAY_VARS)
3778 SHELL_VAR
*funcname_v
, *nfv
, *bash_source_v
, *bash_lineno_v
;
3779 ARRAY
*funcname_a
, *bash_source_a
, *bash_lineno_a
;
3781 FUNCTION_DEF
*shell_fn
;
3783 static int funcnest
= 0;
3787 #if defined (ARRAY_VARS)
3788 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v
, funcname_a
);
3789 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v
, bash_source_a
);
3790 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v
, bash_lineno_a
);
3793 tc
= (COMMAND
*)copy_command (function_cell (var
));
3794 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
3795 tc
->flags
|= CMD_IGNORE_RETURN
;
3799 begin_unwind_frame ("function_calling");
3800 push_context (var
->name
, subshell
, temporary_env
);
3801 add_unwind_protect (pop_context
, (char *)NULL
);
3802 unwind_protect_int (line_number
);
3803 unwind_protect_int (return_catch_flag
);
3804 unwind_protect_jmp_buf (return_catch
);
3805 add_unwind_protect (dispose_command
, (char *)tc
);
3806 unwind_protect_pointer (this_shell_function
);
3807 unwind_protect_int (loop_level
);
3810 push_context (var
->name
, subshell
, temporary_env
); /* don't unwind-protect for subshells */
3812 temporary_env
= (HASH_TABLE
*)NULL
;
3814 this_shell_function
= var
;
3815 make_funcname_visible (1);
3817 debug_trap
= TRAP_STRING(DEBUG_TRAP
);
3818 error_trap
= TRAP_STRING(ERROR_TRAP
);
3819 return_trap
= TRAP_STRING(RETURN_TRAP
);
3821 /* The order of the unwind protects for debug_trap, error_trap and
3822 return_trap is important here! unwind-protect commands are run
3823 in reverse order of registration. If this causes problems, take
3824 out the xfree unwind-protect calls and live with the small memory leak. */
3826 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3827 if the function has the trace attribute set, it inherits the DEBUG trap */
3828 if (debug_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
3832 debug_trap
= savestring (debug_trap
);
3833 add_unwind_protect (xfree
, debug_trap
);
3834 add_unwind_protect (set_debug_trap
, debug_trap
);
3836 restore_default_signal (DEBUG_TRAP
);
3839 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3840 if (error_trap
&& error_trace_mode
== 0)
3844 error_trap
= savestring (error_trap
);
3845 add_unwind_protect (xfree
, error_trap
);
3846 add_unwind_protect (set_error_trap
, error_trap
);
3848 restore_default_signal (ERROR_TRAP
);
3851 /* Shell functions inherit the RETURN trap if function tracing is on
3852 globally or on individually for this function. */
3854 if (return_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
3856 if (return_trap
&& (signal_in_progress (DEBUG_TRAP
) || ((trace_p (var
) == 0) && function_trace_mode
== 0)))
3861 return_trap
= savestring (return_trap
);
3862 add_unwind_protect (xfree
, return_trap
);
3863 add_unwind_protect (set_return_trap
, return_trap
);
3865 restore_default_signal (RETURN_TRAP
);
3869 #if defined (ARRAY_VARS)
3870 /* This is quite similar to the code in shell.c and elsewhere. */
3871 shell_fn
= find_function_def (this_shell_function
->name
);
3872 sfile
= shell_fn
? shell_fn
->source_file
: "";
3873 array_push (funcname_a
, this_shell_function
->name
);
3875 array_push (bash_source_a
, sfile
);
3876 t
= itos (executing_line_number ());
3877 array_push (bash_lineno_a
, t
);
3881 /* The temporary environment for a function is supposed to apply to
3882 all commands executed within the function body. */
3884 remember_args (words
->next
, 1);
3886 /* Update BASH_ARGV and BASH_ARGC */
3888 push_args (words
->next
);
3890 /* Number of the line on which the function body starts. */
3891 line_number
= function_line_number
= tc
->line
;
3893 #if defined (JOB_CONTROL)
3895 stop_pipeline (async
, (COMMAND
*)NULL
);
3900 return_catch_flag
++;
3901 return_val
= setjmp (return_catch
);
3905 result
= return_catch_value
;
3906 /* Run the RETURN trap in the function's context. */
3907 save_current
= currently_executing_command
;
3909 currently_executing_command
= save_current
;
3913 /* Run the debug trap here so we can trap at the start of a function's
3914 execution rather than the execution of the body's first command. */
3915 showing_function_line
= 1;
3916 save_current
= currently_executing_command
;
3917 result
= run_debug_trap ();
3918 #if defined (DEBUGGER)
3919 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3920 skip the command. */
3921 if (debugging_mode
== 0 || result
== EXECUTION_SUCCESS
)
3923 showing_function_line
= 0;
3924 currently_executing_command
= save_current
;
3925 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
3927 /* Run the RETURN trap in the function's context */
3928 save_current
= currently_executing_command
;
3930 currently_executing_command
= save_current
;
3933 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
3935 save_current
= currently_executing_command
;
3937 currently_executing_command
= save_current
;
3939 showing_function_line
= 0;
3942 /* Restore BASH_ARGC and BASH_ARGV */
3947 run_unwind_frame ("function_calling");
3950 #if defined (ARRAY_VARS)
3951 /* These two variables cannot be unset, and cannot be affected by the
3953 array_pop (bash_source_a
);
3954 array_pop (bash_lineno_a
);
3956 /* FUNCNAME can be unset, and so can potentially be changed by the
3958 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv
, funcname_a
);
3959 if (nfv
== funcname_v
)
3960 array_pop (funcname_a
);
3963 if (variable_context
== 0 || this_shell_function
== 0)
3964 make_funcname_visible (0);
3969 /* A convenience routine for use by other parts of the shell to execute
3970 a particular shell function. */
3972 execute_shell_function (var
, words
)
3977 struct fd_bitmap
*bitmap
;
3979 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
3980 begin_unwind_frame ("execute-shell-function");
3981 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
3983 ret
= execute_function (var
, words
, 0, bitmap
, 0, 0);
3985 dispose_fd_bitmap (bitmap
);
3986 discard_unwind_frame ("execute-shell-function");
3991 /* Execute a shell builtin or function in a subshell environment. This
3992 routine does not return; it only calls exit(). If BUILTIN is non-null,
3993 it points to a function to call to execute a shell builtin; otherwise
3994 VAR points at the body of a function to execute. WORDS is the arguments
3995 to the command, REDIRECTS specifies redirections to perform before the
3996 command is executed. */
3998 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
3999 pipe_in
, pipe_out
, async
, fds_to_close
,
4002 REDIRECT
*redirects
;
4003 sh_builtin_func_t
*builtin
;
4005 int pipe_in
, pipe_out
, async
;
4006 struct fd_bitmap
*fds_to_close
;
4009 int result
, r
, funcvalue
;
4010 #if defined (JOB_CONTROL)
4013 jobs_hack
= (builtin
== jobs_builtin
) &&
4014 ((subshell_environment
& SUBSHELL_ASYNC
) == 0 || pipe_out
!= NO_PIPE
);
4017 /* A subshell is neither a login shell nor interactive. */
4018 login_shell
= interactive
= 0;
4021 subshell_environment
|= SUBSHELL_ASYNC
;
4022 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
4023 subshell_environment
|= SUBSHELL_PIPE
;
4025 maybe_make_export_env (); /* XXX - is this needed? */
4027 #if defined (JOB_CONTROL)
4028 /* Eradicate all traces of job control after we fork the subshell, so
4029 all jobs begun by this subshell are in the same process group as
4030 the shell itself. */
4032 /* Allow the output of `jobs' to be piped. */
4034 kill_current_pipeline ();
4036 without_job_control ();
4038 set_sigchld_handler ();
4039 #endif /* JOB_CONTROL */
4041 set_sigint_handler ();
4044 close_fd_bitmap (fds_to_close
);
4046 do_piping (pipe_in
, pipe_out
);
4048 if (do_redirections (redirects
, RX_ACTIVE
) != 0)
4049 exit (EXECUTION_FAILURE
);
4053 /* Give builtins a place to jump back to on failure,
4054 so we don't go back up to main(). */
4055 result
= setjmp (top_level
);
4057 /* Give the return builtin a place to jump to when executed in a subshell
4060 if (return_catch_flag
&& builtin
== return_builtin
)
4061 funcvalue
= setjmp (return_catch
);
4063 if (result
== EXITPROG
)
4064 exit (last_command_exit_value
);
4066 exit (EXECUTION_FAILURE
);
4068 exit (return_catch_value
);
4071 r
= execute_builtin (builtin
, words
, flags
, 1);
4080 r
= execute_function (var
, words
, flags
, fds_to_close
, async
, 1);
4086 /* Execute a builtin or function in the current shell context. If BUILTIN
4087 is non-null, it is the builtin command to execute, otherwise VAR points
4088 to the body of a function. WORDS are the command's arguments, REDIRECTS
4089 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4090 file descriptors to close.
4092 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4093 not undone before this function returns. */
4095 execute_builtin_or_function (words
, builtin
, var
, redirects
,
4096 fds_to_close
, flags
)
4098 sh_builtin_func_t
*builtin
;
4100 REDIRECT
*redirects
;
4101 struct fd_bitmap
*fds_to_close
;
4105 REDIRECT
*saved_undo_list
;
4106 sh_builtin_func_t
*saved_this_shell_builtin
;
4108 if (do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
4110 cleanup_redirects (redirection_undo_list
);
4111 redirection_undo_list
= (REDIRECT
*)NULL
;
4112 dispose_exec_redirects ();
4113 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
4116 saved_this_shell_builtin
= this_shell_builtin
;
4117 saved_undo_list
= redirection_undo_list
;
4119 /* Calling the "exec" builtin changes redirections forever. */
4120 if (builtin
== exec_builtin
)
4122 dispose_redirects (saved_undo_list
);
4123 saved_undo_list
= exec_redirection_undo_list
;
4124 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
4127 dispose_exec_redirects ();
4129 if (saved_undo_list
)
4131 begin_unwind_frame ("saved redirects");
4132 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
4135 redirection_undo_list
= (REDIRECT
*)NULL
;
4138 result
= execute_builtin (builtin
, words
, flags
, 0);
4140 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
4142 /* We do this before undoing the effects of any redirections. */
4145 if (ferror (stdout
))
4148 /* If we are executing the `command' builtin, but this_shell_builtin is
4149 set to `exec_builtin', we know that we have something like
4150 `command exec [redirection]', since otherwise `exec' would have
4151 overwritten the shell and we wouldn't get here. In this case, we
4152 want to behave as if the `command' builtin had not been specified
4153 and preserve the redirections. */
4154 if (builtin
== command_builtin
&& this_shell_builtin
== exec_builtin
)
4156 if (saved_undo_list
)
4157 dispose_redirects (saved_undo_list
);
4158 redirection_undo_list
= exec_redirection_undo_list
;
4159 saved_undo_list
= exec_redirection_undo_list
= (REDIRECT
*)NULL
;
4160 discard_unwind_frame ("saved_redirects");
4163 if (saved_undo_list
)
4165 redirection_undo_list
= saved_undo_list
;
4166 discard_unwind_frame ("saved redirects");
4169 if (redirection_undo_list
)
4171 cleanup_redirects (redirection_undo_list
);
4172 redirection_undo_list
= (REDIRECT
*)NULL
;
4179 setup_async_signals ()
4181 #if defined (__BEOS__)
4182 set_signal_handler (SIGHUP
, SIG_IGN
); /* they want csh-like behavior */
4185 #if defined (JOB_CONTROL)
4186 if (job_control
== 0)
4189 set_signal_handler (SIGINT
, SIG_IGN
);
4190 set_signal_ignored (SIGINT
);
4191 set_signal_handler (SIGQUIT
, SIG_IGN
);
4192 set_signal_ignored (SIGQUIT
);
4196 /* Execute a simple command that is hopefully defined in a disk file
4201 3) look up the command
4204 6) If the execve failed, see if the file has executable mode set.
4205 If so, and it isn't a directory, then execute its contents as
4208 Note that the filename hashing stuff has to take place up here,
4209 in the parent. This is probably why the Bourne style shells
4210 don't handle it, since that would require them to go through
4211 this gnarly hair, for no good reason.
4213 NOTE: callers expect this to fork or exit(). */
4215 /* Name of a shell function to call when a command name is not found. */
4216 #ifndef NOTFOUND_HOOK
4217 # define NOTFOUND_HOOK "command_not_found_handle"
4221 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
4222 async
, fds_to_close
, cmdflags
)
4224 REDIRECT
*redirects
;
4226 int pipe_in
, pipe_out
, async
;
4227 struct fd_bitmap
*fds_to_close
;
4230 char *pathname
, *command
, **args
;
4236 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
4237 pathname
= words
->word
->word
;
4239 #if defined (RESTRICTED_SHELL)
4240 command
= (char *)NULL
;
4241 if (restricted
&& xstrchr (pathname
, '/'))
4243 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4245 last_command_exit_value
= EXECUTION_FAILURE
;
4247 /* If we're not going to fork below, we must already be in a child
4248 process or a context in which it's safe to call exit(2). */
4249 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
4250 exit (last_command_exit_value
);
4254 #endif /* RESTRICTED_SHELL */
4256 command
= search_for_command (pathname
);
4260 maybe_make_export_env ();
4261 put_command_name_into_env (command
);
4264 /* We have to make the child before we check for the non-existence
4265 of COMMAND, since we want the error messages to be redirected. */
4266 /* If we can get away without forking and there are no pipes to deal with,
4267 don't bother to fork, just directly exec the command. */
4268 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
4271 pid
= make_child (savestring (command_line
), async
);
4275 int old_interactive
;
4278 /* This has been disabled for the time being. */
4279 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4280 if (posixly_correct
== 0)
4281 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags
);
4285 /* Cancel traps, in trap.c. */
4286 restore_original_signals ();
4288 /* restore_original_signals may have undone the work done
4289 by make_child to ensure that SIGINT and SIGQUIT are ignored
4290 in asynchronous children. */
4293 if ((cmdflags
& CMD_STDIN_REDIR
) &&
4294 pipe_in
== NO_PIPE
&&
4295 (stdin_redirects (redirects
) == 0))
4296 async_redirect_stdin ();
4297 setup_async_signals ();
4300 /* This functionality is now provided by close-on-exec of the
4301 file descriptors manipulated by redirection and piping.
4302 Some file descriptors still need to be closed in all children
4303 because of the way bash does pipes; fds_to_close is a
4304 bitmap of all such file descriptors. */
4306 close_fd_bitmap (fds_to_close
);
4308 do_piping (pipe_in
, pipe_out
);
4310 old_interactive
= interactive
;
4314 subshell_environment
= SUBSHELL_FORK
;
4316 if (redirects
&& (do_redirections (redirects
, RX_ACTIVE
) != 0))
4318 #if defined (PROCESS_SUBSTITUTION)
4319 /* Try to remove named pipes that may have been created as the
4320 result of redirections. */
4321 unlink_fifo_list ();
4322 #endif /* PROCESS_SUBSTITUTION */
4323 exit (EXECUTION_FAILURE
);
4327 interactive
= old_interactive
;
4331 hookf
= find_function (NOTFOUND_HOOK
);
4334 internal_error (_("%s: command not found"), pathname
);
4335 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
4338 wl
= make_word_list (make_word (NOTFOUND_HOOK
), words
);
4339 exit (execute_shell_function (hookf
, wl
));
4342 /* Execve expects the command name to be in args[0]. So we
4343 leave it there, in the same format that the user used to
4345 args
= strvec_from_word_list (words
, 0, 0, (int *)NULL
);
4346 exit (shell_execve (command
, args
, export_env
));
4351 /* Make sure that the pipes are closed in the parent. */
4352 close_pipes (pipe_in
, pipe_out
);
4353 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4354 unlink_fifo_list ();
4360 /* CPP defines to decide whether a particular index into the #! line
4361 corresponds to a valid interpreter name or argument character, or
4362 whitespace. The MSDOS define is to allow \r to be treated the same
4365 #if !defined (MSDOS)
4366 # define STRINGCHAR(ind) \
4367 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4368 # define WHITECHAR(ind) \
4369 (ind < sample_len && whitespace (sample[ind]))
4371 # define STRINGCHAR(ind) \
4372 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4373 # define WHITECHAR(ind) \
4374 (ind < sample_len && whitespace (sample[ind]))
4378 getinterp (sample
, sample_len
, endp
)
4380 int sample_len
, *endp
;
4386 /* Find the name of the interpreter to exec. */
4387 for (i
= 2; i
< sample_len
&& whitespace (sample
[i
]); i
++)
4390 for (start
= i
; STRINGCHAR(i
); i
++)
4393 execname
= substring (sample
, start
, i
);
4400 #if !defined (HAVE_HASH_BANG_EXEC)
4401 /* If the operating system on which we're running does not handle
4402 the #! executable format, then help out. SAMPLE is the text read
4403 from the file, SAMPLE_LEN characters. COMMAND is the name of
4404 the script; it and ARGS, the arguments given by the user, will
4405 become arguments to the specified interpreter. ENV is the environment
4406 to pass to the interpreter.
4408 The word immediately following the #! is the interpreter to execute.
4409 A single argument to the interpreter is allowed. */
4412 execute_shell_script (sample
, sample_len
, command
, args
, env
)
4418 char *execname
, *firstarg
;
4419 int i
, start
, size_increment
, larry
;
4421 /* Find the name of the interpreter to exec. */
4422 execname
= getinterp (sample
, sample_len
, &i
);
4425 /* Now the argument, if any. */
4426 for (firstarg
= (char *)NULL
, start
= i
; WHITECHAR(i
); i
++)
4429 /* If there is more text on the line, then it is an argument for the
4434 for (start
= i
; STRINGCHAR(i
); i
++)
4436 firstarg
= substring ((char *)sample
, start
, i
);
4440 larry
= strvec_len (args
) + size_increment
;
4441 args
= strvec_resize (args
, larry
+ 1);
4443 for (i
= larry
- 1; i
; i
--)
4444 args
[i
] = args
[i
- size_increment
];
4455 args
[larry
] = (char *)NULL
;
4457 return (shell_execve (execname
, args
, env
));
4462 #endif /* !HAVE_HASH_BANG_EXEC */
4465 initialize_subshell ()
4468 /* Forget about any aliases that we knew of. We are in a subshell. */
4469 delete_all_aliases ();
4472 #if defined (HISTORY)
4473 /* Forget about the history lines we have read. This is a non-interactive
4475 history_lines_this_session
= 0;
4478 #if defined (JOB_CONTROL)
4479 /* Forget about the way job control was working. We are in a subshell. */
4480 without_job_control ();
4481 set_sigchld_handler ();
4483 #endif /* JOB_CONTROL */
4485 /* Reset the values of the shell flags and options. */
4486 reset_shell_flags ();
4487 reset_shell_options ();
4488 reset_shopt_options ();
4490 /* Zero out builtin_env, since this could be a shell script run from a
4491 sourced file with a temporary environment supplied to the `source/.'
4492 builtin. Such variables are not supposed to be exported (empirical
4493 testing with sh and ksh). Just throw it away; don't worry about a
4495 if (vc_isbltnenv (shell_variables
))
4496 shell_variables
= shell_variables
->down
;
4498 clear_unwind_protect_list (0);
4499 /* XXX -- are there other things we should be resetting here? */
4500 parse_and_execute_level
= 0; /* nothing left to restore it */
4502 /* We're no longer inside a shell function. */
4503 variable_context
= return_catch_flag
= 0;
4505 /* If we're not interactive, close the file descriptor from which we're
4506 reading the current shell script. */
4507 if (interactive_shell
== 0)
4508 unset_bash_input (0);
4511 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4512 # define SETOSTYPE(x) __setostype(x)
4514 # define SETOSTYPE(x)
4517 #define READ_SAMPLE_BUF(file, buf, len) \
4520 fd = open(file, O_RDONLY); \
4523 len = read (fd, buf, 80); \
4531 /* Call execve (), handling interpreting shell scripts, and handling
4534 shell_execve (command
, args
, env
)
4543 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
4544 execve (command
, args
, env
);
4545 i
= errno
; /* error from execve() */
4548 /* If we get to this point, then start checking out the file.
4549 Maybe it is something we can hack ourselves. */
4552 if ((stat (command
, &finfo
) == 0) && (S_ISDIR (finfo
.st_mode
)))
4553 internal_error (_("%s: is a directory"), command
);
4554 else if (executable_file (command
) == 0)
4557 file_error (command
);
4559 /* errors not involving the path argument to execve. */
4560 else if (i
== E2BIG
|| i
== ENOMEM
)
4563 file_error (command
);
4567 /* The file has the execute bits set, but the kernel refuses to
4568 run it for some reason. See why. */
4569 #if defined (HAVE_HASH_BANG_EXEC)
4570 READ_SAMPLE_BUF (command
, sample
, sample_len
);
4571 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
4576 interp
= getinterp (sample
, sample_len
, (int *)NULL
);
4577 ilen
= strlen (interp
);
4579 if (interp
[ilen
- 1] == '\r')
4581 interp
= xrealloc (interp
, ilen
+ 2);
4582 interp
[ilen
- 1] = '^';
4584 interp
[ilen
+ 1] = '\0';
4586 sys_error (_("%s: %s: bad interpreter"), command
, interp
? interp
: "");
4592 file_error (command
);
4594 return ((i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
); /* XXX Posix.2 says that exit status is 126 */
4597 /* This file is executable.
4598 If it begins with #!, then help out people with losing operating
4599 systems. Otherwise, check to see if it is a binary file by seeing
4600 if the contents of the first line (or up to 80 characters) are in the
4601 ASCII set. If it's a text file, execute the contents as shell commands,
4602 otherwise return 126 (EX_BINARY_FILE). */
4603 READ_SAMPLE_BUF (command
, sample
, sample_len
);
4605 if (sample_len
== 0)
4606 return (EXECUTION_SUCCESS
);
4608 /* Is this supposed to be an executable script?
4609 If so, the format of the line is "#! interpreter [argument]".
4610 A single argument is allowed. The BSD kernel restricts
4611 the length of the entire line to 32 characters (32 bytes
4612 being the size of the BSD exec header), but we allow 80
4616 #if !defined (HAVE_HASH_BANG_EXEC)
4617 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
4618 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
4621 if (check_binary_file (sample
, sample_len
))
4623 internal_error (_("%s: cannot execute binary file"), command
);
4624 return (EX_BINARY_FILE
);
4628 /* We have committed to attempting to execute the contents of this file
4629 as shell commands. */
4631 initialize_subshell ();
4633 set_sigint_handler ();
4635 /* Insert the name of this shell into the argument list. */
4636 larray
= strvec_len (args
) + 1;
4637 args
= strvec_resize (args
, larray
+ 1);
4639 for (i
= larray
- 1; i
; i
--)
4640 args
[i
] = args
[i
- 1];
4642 args
[0] = shell_name
;
4644 args
[larray
] = (char *)NULL
;
4646 if (args
[0][0] == '-')
4649 #if defined (RESTRICTED_SHELL)
4651 change_flag ('r', FLAG_OFF
);
4656 /* Can't free subshell_argv[0]; that is shell_name. */
4657 for (i
= 1; i
< subshell_argc
; i
++)
4658 free (subshell_argv
[i
]);
4659 free (subshell_argv
);
4662 dispose_command (currently_executing_command
); /* XXX */
4663 currently_executing_command
= (COMMAND
*)NULL
;
4665 subshell_argc
= larray
;
4666 subshell_argv
= args
;
4667 subshell_envp
= env
;
4669 unbind_args (); /* remove the positional parameters */
4671 longjmp (subshell_top_level
, 1);
4676 execute_intern_function (name
, function
)
4682 if (check_identifier (name
, posixly_correct
) == 0)
4684 if (posixly_correct
&& interactive_shell
== 0)
4686 last_command_exit_value
= EX_USAGE
;
4687 jump_to_top_level (ERREXIT
);
4689 return (EXECUTION_FAILURE
);
4692 var
= find_function (name
->word
);
4693 if (var
&& (readonly_p (var
) || noassign_p (var
)))
4695 if (readonly_p (var
))
4696 internal_error (_("%s: readonly function"), var
->name
);
4697 return (EXECUTION_FAILURE
);
4700 bind_function (name
->word
, function
);
4701 return (EXECUTION_SUCCESS
);
4704 #if defined (INCLUDE_UNUSED)
4705 #if defined (PROCESS_SUBSTITUTION)
4709 register int i
, fd_table_size
;
4711 fd_table_size
= getdtablesize ();
4712 if (fd_table_size
> 256) /* clamp to a reasonable value */
4713 fd_table_size
= 256;
4715 for (i
= 3; i
< fd_table_size
; i
++)
4718 #endif /* PROCESS_SUBSTITUTION */
4722 close_pipes (in
, out
)
4732 dup_error (oldd
, newd
)
4735 sys_error (_("cannot duplicate fd %d to fd %d"), oldd
, newd
);
4738 /* Redirect input and output to be from and to the specified pipes.
4739 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4741 do_piping (pipe_in
, pipe_out
)
4742 int pipe_in
, pipe_out
;
4744 if (pipe_in
!= NO_PIPE
)
4746 if (dup2 (pipe_in
, 0) < 0)
4747 dup_error (pipe_in
, 0);
4751 if (pipe_out
!= NO_PIPE
)
4753 if (pipe_out
!= REDIRECT_BOTH
)
4755 if (dup2 (pipe_out
, 1) < 0)
4756 dup_error (pipe_out
, 1);
4757 if (pipe_out
== 0 || pipe_out
> 1)
4762 if (dup2 (1, 2) < 0)