1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2005 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 it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
27 #include "chartypes.h"
28 #include "bashtypes.h"
29 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
30 # include <sys/file.h>
33 #include "posixstat.h"
36 # include <sys/param.h>
39 #if defined (HAVE_UNISTD_H)
43 #include "posixtime.h"
45 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
46 # include <sys/resource.h>
49 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
50 # include <sys/times.h>
64 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
69 #include "execute_cmd.h"
76 #if defined (COND_COMMAND)
80 #include "builtins/common.h"
81 #include "builtins/builtext.h" /* list of builtins */
83 #include <glob/strmatch.h>
84 #include <tilde/tilde.h>
86 #if defined (BUFFERED_INPUT)
95 # include "bashhist.h"
98 extern int posixly_correct
;
99 extern int breaking
, continuing
, loop_level
;
100 extern int expand_aliases
;
101 extern int parse_and_execute_level
, running_trap
;
102 extern int command_string_index
, line_number
;
103 extern int dot_found_in_search
;
104 extern int already_making_children
;
105 extern int tempenv_assign_error
;
106 extern char *the_printed_command
, *shell_name
;
107 extern pid_t last_command_subst_pid
;
108 extern sh_builtin_func_t
*last_shell_builtin
, *this_shell_builtin
;
109 extern char **subshell_argv
, **subshell_envp
;
110 extern int subshell_argc
;
112 extern char *glob_argv_flags
;
115 extern int close
__P((int));
117 /* Static functions defined and used in this file. */
118 static void close_pipes
__P((int, int));
119 static void do_piping
__P((int, int));
120 static void bind_lastarg
__P((char *));
121 static int shell_control_structure
__P((enum command_type
));
122 static void cleanup_redirects
__P((REDIRECT
*));
124 #if defined (JOB_CONTROL)
125 static int restore_signal_mask
__P((sigset_t
*));
128 static void async_redirect_stdin
__P((void));
130 static int builtin_status
__P((int));
132 static int execute_for_command
__P((FOR_COM
*));
133 #if defined (SELECT_COMMAND)
134 static int print_index_and_element
__P((int, int, WORD_LIST
*));
135 static void indent
__P((int, int));
136 static void print_select_list
__P((WORD_LIST
*, int, int, int));
137 static char *select_query
__P((WORD_LIST
*, int, char *, int));
138 static int execute_select_command
__P((SELECT_COM
*));
140 #if defined (DPAREN_ARITHMETIC)
141 static int execute_arith_command
__P((ARITH_COM
*));
143 #if defined (COND_COMMAND)
144 static int execute_cond_node
__P((COND_COM
*));
145 static int execute_cond_command
__P((COND_COM
*));
147 #if defined (COMMAND_TIMING)
148 static int mkfmt
__P((char *, int, int, time_t, int));
149 static void print_formatted_time
__P((FILE *, char *,
150 time_t, int, time_t, int,
152 static int time_command
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
154 #if defined (ARITH_FOR_COMMAND)
155 static intmax_t eval_arith_for_expr
__P((WORD_LIST
*, int *));
156 static int execute_arith_for_command
__P((ARITH_FOR_COM
*));
158 static int execute_case_command
__P((CASE_COM
*));
159 static int execute_while_command
__P((WHILE_COM
*));
160 static int execute_until_command
__P((WHILE_COM
*));
161 static int execute_while_or_until
__P((WHILE_COM
*, int));
162 static int execute_if_command
__P((IF_COM
*));
163 static int execute_null_command
__P((REDIRECT
*, int, int, int));
164 static void fix_assignment_words
__P((WORD_LIST
*));
165 static int execute_simple_command
__P((SIMPLE_COM
*, int, int, int, struct fd_bitmap
*));
166 static int execute_builtin
__P((sh_builtin_func_t
*, WORD_LIST
*, int, int));
167 static int execute_function
__P((SHELL_VAR
*, WORD_LIST
*, int, struct fd_bitmap
*, int, int));
168 static int execute_builtin_or_function
__P((WORD_LIST
*, sh_builtin_func_t
*,
170 REDIRECT
*, struct fd_bitmap
*, int));
171 static void execute_subshell_builtin_or_function
__P((WORD_LIST
*, REDIRECT
*,
177 static void execute_disk_command
__P((WORD_LIST
*, REDIRECT
*, char *,
178 int, int, int, struct fd_bitmap
*, int));
180 static char *getinterp
__P((char *, int, int *));
181 static void initialize_subshell
__P((void));
182 static int execute_in_subshell
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
184 static int execute_pipeline
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
186 static int execute_connection
__P((COMMAND
*, int, int, int, struct fd_bitmap
*));
188 static int execute_intern_function
__P((WORD_DESC
*, COMMAND
*));
190 /* The line number that the currently executing function starts on. */
191 static int function_line_number
;
193 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
194 so that reader_loop can set it to zero before executing a command. */
197 /* The name of the command that is currently being executed.
198 `test' needs this, for example. */
199 char *this_command_name
;
201 /* The printed representation of the currently-executing command (same as
202 the_printed_command), except when a trap is being executed. Useful for
203 a debugger to know where exactly the program is currently executing. */
204 char *the_printed_command_except_trap
;
206 static COMMAND
*currently_executing_command
;
208 struct stat SB
; /* used for debugging */
210 static int special_builtin_failed
;
212 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
213 number containing the function name. Used by executing_line_number to
214 report the correct line number. Kind of a hack. */
215 static int showing_function_line
;
217 static int line_number_for_err_trap
;
219 /* For catching RETURN in a function. */
220 int return_catch_flag
;
221 int return_catch_value
;
222 procenv_t return_catch
;
224 /* The value returned by the last synchronous command. */
225 int last_command_exit_value
;
227 /* Whether or not the last command (corresponding to last_command_exit_value)
228 was terminated by a signal, and, if so, which one. */
229 int last_command_exit_signal
;
231 /* The list of redirections to perform which will undo the redirections
232 that I made in the shell. */
233 REDIRECT
*redirection_undo_list
= (REDIRECT
*)NULL
;
235 /* The list of redirections to perform which will undo the internal
236 redirections performed by the `exec' builtin. These are redirections
237 that must be undone even when exec discards redirection_undo_list. */
238 REDIRECT
*exec_redirection_undo_list
= (REDIRECT
*)NULL
;
240 /* Non-zero if we have just forked and are currently running in a subshell
242 int subshell_environment
;
244 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
245 int subshell_level
= 0;
247 /* Currently-executing shell function. */
248 SHELL_VAR
*this_shell_function
;
250 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
251 int match_ignore_case
= 0;
253 struct fd_bitmap
*current_fds_to_close
= (struct fd_bitmap
*)NULL
;
255 #define FD_BITMAP_DEFAULT_SIZE 32
257 /* Functions to allocate and deallocate the structures used to pass
258 information from the shell to its children about file descriptors
264 struct fd_bitmap
*ret
;
266 ret
= (struct fd_bitmap
*)xmalloc (sizeof (struct fd_bitmap
));
272 ret
->bitmap
= (char *)xmalloc (size
);
273 memset (ret
->bitmap
, '\0', size
);
276 ret
->bitmap
= (char *)NULL
;
281 dispose_fd_bitmap (fdbp
)
282 struct fd_bitmap
*fdbp
;
289 close_fd_bitmap (fdbp
)
290 struct fd_bitmap
*fdbp
;
296 for (i
= 0; i
< fdbp
->size
; i
++)
305 /* Return the line number of the currently executing command. */
307 executing_line_number ()
309 if (executing
&& showing_function_line
== 0 &&
310 (variable_context
== 0 || interactive_shell
== 0) &&
311 currently_executing_command
)
313 #if defined (COND_COMMAND)
314 if (currently_executing_command
->type
== cm_cond
)
315 return currently_executing_command
->value
.Cond
->line
;
317 #if defined (DPAREN_ARITHMETIC)
318 else if (currently_executing_command
->type
== cm_arith
)
319 return currently_executing_command
->value
.Arith
->line
;
321 #if defined (ARITH_FOR_COMMAND)
322 else if (currently_executing_command
->type
== cm_arith_for
)
323 return currently_executing_command
->value
.ArithFor
->line
;
332 /* Execute the command passed in COMMAND. COMMAND is exactly what
333 read_command () places into GLOBAL_COMMAND. See "command.h" for the
334 details of the command structure.
336 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
337 return values. Executing a command with nothing in it returns
338 EXECUTION_SUCCESS. */
340 execute_command (command
)
343 struct fd_bitmap
*bitmap
;
346 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
347 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
348 begin_unwind_frame ("execute-command");
349 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
351 /* Just do the command, but not asynchronously. */
352 result
= execute_command_internal (command
, 0, NO_PIPE
, NO_PIPE
, bitmap
);
354 dispose_fd_bitmap (bitmap
);
355 discard_unwind_frame ("execute-command");
357 #if defined (PROCESS_SUBSTITUTION)
358 /* don't unlink fifos if we're in a shell function; wait until the function
360 if (variable_context
== 0)
362 #endif /* PROCESS_SUBSTITUTION */
368 /* Return 1 if TYPE is a shell control structure type. */
370 shell_control_structure (type
)
371 enum command_type type
;
375 #if defined (ARITH_FOR_COMMAND)
378 #if defined (SELECT_COMMAND)
381 #if defined (DPAREN_ARITHMETIC)
384 #if defined (COND_COMMAND)
393 case cm_function_def
:
401 /* A function to use to unwind_protect the redirection undo list
404 cleanup_redirects (list
)
407 do_redirections (list
, RX_ACTIVE
);
408 dispose_redirects (list
);
412 /* Function to unwind_protect the redirections for functions and builtins. */
414 cleanup_func_redirects (list
)
417 do_redirections (list
, RX_ACTIVE
);
422 dispose_exec_redirects ()
424 if (exec_redirection_undo_list
)
426 dispose_redirects (exec_redirection_undo_list
);
427 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
431 #if defined (JOB_CONTROL)
432 /* A function to restore the signal mask to its proper value when the shell
433 is interrupted or errors occur while creating a pipeline. */
435 restore_signal_mask (set
)
438 return (sigprocmask (SIG_SETMASK
, set
, (sigset_t
*)NULL
));
440 #endif /* JOB_CONTROL */
443 /* A debugging function that can be called from gdb, for instance. */
448 int f
, fd_table_size
;
450 fd_table_size
= getdtablesize ();
452 fprintf (stderr
, "pid %ld open files:", (long)getpid ());
453 for (i
= 3; i
< fd_table_size
; i
++)
455 if ((f
= fcntl (i
, F_GETFD
, 0)) != -1)
456 fprintf (stderr
, " %d (%s)", i
, f
? "close" : "open");
458 fprintf (stderr
, "\n");
463 async_redirect_stdin ()
467 fd
= open ("/dev/null", O_RDONLY
);
474 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno
));
477 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
479 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
480 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
481 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
482 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
483 from and where it goes. They can have the value of NO_PIPE, which means
485 FDS_TO_CLOSE is a list of file descriptors to close once the child has
486 been forked. This list often contains the unusable sides of pipes, etc.
488 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
489 return values. Executing a command with nothing in it returns
490 EXECUTION_SUCCESS. */
492 execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
,
496 int pipe_in
, pipe_out
;
497 struct fd_bitmap
*fds_to_close
;
499 int exec_result
, invert
, ignore_return
, was_error_trap
;
500 REDIRECT
*my_undo_list
, *exec_undo_list
;
501 volatile int last_pid
;
502 volatile int save_line_number
;
504 if (command
== 0 || breaking
|| continuing
|| read_but_dont_execute
)
505 return (EXECUTION_SUCCESS
);
508 run_pending_traps ();
511 if (running_trap
== 0)
513 currently_executing_command
= command
;
515 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
517 /* If we're inverting the return value and `set -e' has been executed,
518 we don't want a failing command to inadvertently cause the shell
520 if (exit_immediately_on_error
&& invert
) /* XXX */
521 command
->flags
|= CMD_IGNORE_RETURN
; /* XXX */
523 exec_result
= EXECUTION_SUCCESS
;
525 /* If a command was being explicitly run in a subshell, or if it is
526 a shell control-structure, and it has a pipe, then we do the command
528 if (command
->type
== cm_subshell
&& (command
->flags
& CMD_NO_FORK
))
529 return (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
531 if (command
->type
== cm_subshell
||
532 (command
->flags
& (CMD_WANT_SUBSHELL
|CMD_FORCE_SUBSHELL
)) ||
533 (shell_control_structure (command
->type
) &&
534 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
|| asynchronous
)))
538 /* Fork a subshell, turn off the subshell bit, turn off job
539 control and call execute_command () on the command again. */
540 paren_pid
= make_child (savestring (make_command_string (command
)),
543 exit (execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
));
547 close_pipes (pipe_in
, pipe_out
);
549 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
552 /* If we are part of a pipeline, and not the end of the pipeline,
553 then we should simply return and let the last command in the
554 pipe be waited for. If we are not in a pipeline, or are the
555 last command in the pipeline, then we wait for the subshell
556 and return its exit status as usual. */
557 if (pipe_out
!= NO_PIPE
)
558 return (EXECUTION_SUCCESS
);
560 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
562 if (asynchronous
== 0)
564 last_command_exit_value
= wait_for (paren_pid
);
566 /* If we have to, invert the return value. */
568 exec_result
= ((last_command_exit_value
== EXECUTION_SUCCESS
)
570 : EXECUTION_SUCCESS
);
572 exec_result
= last_command_exit_value
;
574 return (last_command_exit_value
= exec_result
);
578 DESCRIBE_PID (paren_pid
);
580 run_pending_traps ();
582 return (EXECUTION_SUCCESS
);
587 #if defined (COMMAND_TIMING)
588 if (command
->flags
& CMD_TIME_PIPELINE
)
592 command
->flags
|= CMD_FORCE_SUBSHELL
;
593 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
597 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
599 if (running_trap
== 0)
601 currently_executing_command
= (COMMAND
*)NULL
;
603 return (exec_result
);
605 #endif /* COMMAND_TIMING */
607 if (shell_control_structure (command
->type
) && command
->redirects
)
608 stdin_redir
= stdin_redirects (command
->redirects
);
610 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
612 if (do_redirections (command
->redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
614 cleanup_redirects (redirection_undo_list
);
615 redirection_undo_list
= (REDIRECT
*)NULL
;
616 dispose_exec_redirects ();
617 return (EXECUTION_FAILURE
);
620 if (redirection_undo_list
)
622 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
623 dispose_redirects (redirection_undo_list
);
624 redirection_undo_list
= (REDIRECT
*)NULL
;
627 my_undo_list
= (REDIRECT
*)NULL
;
629 if (exec_redirection_undo_list
)
631 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
632 dispose_redirects (exec_redirection_undo_list
);
633 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
636 exec_undo_list
= (REDIRECT
*)NULL
;
638 if (my_undo_list
|| exec_undo_list
)
639 begin_unwind_frame ("loop_redirections");
642 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
645 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
647 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
651 switch (command
->type
)
655 save_line_number
= line_number
;
656 /* We can't rely on variables retaining their values across a
657 call to execute_simple_command if a longjmp occurs as the
658 result of a `return' builtin. This is true for sure with gcc. */
659 #if defined (RECYCLES_PIDS)
660 last_made_pid
= NO_PID
;
662 last_pid
= last_made_pid
;
663 was_error_trap
= signal_is_trapped (ERROR_TRAP
) && signal_is_ignored (ERROR_TRAP
) == 0;
665 if (ignore_return
&& command
->value
.Simple
)
666 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
667 if (command
->flags
& CMD_STDIN_REDIR
)
668 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
670 line_number_for_err_trap
= line_number
= command
->value
.Simple
->line
;
672 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
673 asynchronous
, fds_to_close
);
674 line_number
= save_line_number
;
676 /* The temporary environment should be used for only the simple
677 command immediately following its definition. */
678 dispose_used_env_vars ();
680 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
681 /* Reclaim memory allocated with alloca () on machines which
682 may be using the alloca emulation code. */
684 #endif /* (ultrix && mips) || C_ALLOCA */
686 /* If we forked to do the command, then we must wait_for ()
689 /* XXX - this is something to watch out for if there are problems
690 when the shell is compiled without job control. */
691 if (already_making_children
&& pipe_out
== NO_PIPE
&&
692 last_made_pid
!= last_pid
)
694 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
698 DESCRIBE_PID (last_made_pid
);
701 #if !defined (JOB_CONTROL)
702 /* Do not wait for asynchronous processes started from
704 if (last_made_pid
!= last_asynchronous_pid
)
706 /* When executing a shell function that executes other
707 commands, this causes the last simple command in
708 the function to be waited for twice. This also causes
709 subshells forked to execute builtin commands (e.g., in
710 pipelines) to be waited for twice. */
711 exec_result
= wait_for (last_made_pid
);
715 if (was_error_trap
&& ignore_return
== 0 && invert
== 0 && exec_result
!= EXECUTION_SUCCESS
)
717 last_command_exit_value
= exec_result
;
721 if (ignore_return
== 0 && invert
== 0 &&
722 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
723 (exit_immediately_on_error
&& (exec_result
!= EXECUTION_SUCCESS
))))
725 last_command_exit_value
= exec_result
;
726 run_pending_traps ();
727 jump_to_top_level (ERREXIT
);
734 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
735 exec_result
= execute_for_command (command
->value
.For
);
738 #if defined (ARITH_FOR_COMMAND)
741 command
->value
.ArithFor
->flags
|= CMD_IGNORE_RETURN
;
742 exec_result
= execute_arith_for_command (command
->value
.ArithFor
);
746 #if defined (SELECT_COMMAND)
749 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
750 exec_result
= execute_select_command (command
->value
.Select
);
756 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
757 exec_result
= execute_case_command (command
->value
.Case
);
762 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
763 exec_result
= execute_while_command (command
->value
.While
);
768 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
769 exec_result
= execute_until_command (command
->value
.While
);
774 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
775 exec_result
= execute_if_command (command
->value
.If
);
780 /* This code can be executed from either of two paths: an explicit
781 '{}' command, or via a function call. If we are executed via a
782 function call, we have already taken care of the function being
783 executed in the background (down there in execute_simple_command ()),
784 and this command should *not* be marked as asynchronous. If we
785 are executing a regular '{}' group command, and asynchronous == 1,
786 we must want to execute the whole command in the background, so we
787 need a subshell, and we want the stuff executed in that subshell
788 (this group command) to be executed in the foreground of that
789 subshell (i.e. there will not be *another* subshell forked).
791 What we do is to force a subshell if asynchronous, and then call
792 execute_command_internal again with asynchronous still set to 1,
793 but with the original group command, so the printed command will
796 The code above that handles forking off subshells will note that
797 both subshell and async are on, and turn off async in the child
798 after forking the subshell (but leave async set in the parent, so
799 the normal call to describe_pid is made). This turning off
800 async is *crucial*; if it is not done, this will fall into an
801 infinite loop of executions through this spot in subshell after
802 subshell until the process limit is exhausted. */
806 command
->flags
|= CMD_FORCE_SUBSHELL
;
808 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
813 if (ignore_return
&& command
->value
.Group
->command
)
814 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
816 execute_command_internal (command
->value
.Group
->command
,
817 asynchronous
, pipe_in
, pipe_out
,
823 exec_result
= execute_connection (command
, asynchronous
,
824 pipe_in
, pipe_out
, fds_to_close
);
827 #if defined (DPAREN_ARITHMETIC)
830 command
->value
.Arith
->flags
|= CMD_IGNORE_RETURN
;
831 exec_result
= execute_arith_command (command
->value
.Arith
);
835 #if defined (COND_COMMAND)
838 command
->value
.Cond
->flags
|= CMD_IGNORE_RETURN
;
839 save_line_number
= line_number
;
840 exec_result
= execute_cond_command (command
->value
.Cond
);
841 line_number
= save_line_number
;
845 case cm_function_def
:
846 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
847 command
->value
.Function_def
->command
);
851 command_error ("execute_command", CMDERR_BADTYPE
, command
->type
, 0);
856 do_redirections (my_undo_list
, RX_ACTIVE
);
857 dispose_redirects (my_undo_list
);
861 dispose_redirects (exec_undo_list
);
863 if (my_undo_list
|| exec_undo_list
)
864 discard_unwind_frame ("loop_redirections");
866 /* Invert the return value if we have to */
868 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
872 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
873 /* This is where we set PIPESTATUS from the exit status of the appropriate
874 compound commands (the ones that look enough like simple commands to
875 cause confusion). We might be able to optimize by not doing this if
876 subshell_environment != 0. */
877 switch (command
->type
)
879 # if defined (DPAREN_ARITHMETIC)
882 # if defined (COND_COMMAND)
885 set_pipestatus_from_exit (exec_result
);
890 last_command_exit_value
= exec_result
;
891 run_pending_traps ();
893 if (running_trap
== 0)
895 currently_executing_command
= (COMMAND
*)NULL
;
896 return (last_command_exit_value
);
899 #if defined (COMMAND_TIMING)
901 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
902 extern struct timeval
*difftimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
903 extern struct timeval
*addtimeval
__P((struct timeval
*, struct timeval
*, struct timeval
*));
904 extern int timeval_to_cpu
__P((struct timeval
*, struct timeval
*, struct timeval
*));
907 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
908 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
910 static int precs
[] = { 0, 100, 10, 1 };
912 /* Expand one `%'-prefixed escape sequence from a time format string. */
914 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
921 char abuf
[INT_STRLEN_BOUND(time_t) + 1];
925 abuf
[sizeof(abuf
) - 1] = '\0';
927 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
932 aind
= sizeof(abuf
) - 2;
934 abuf
[aind
--] = (min
% 10) + '0';
938 buf
[ind
++] = abuf
[aind
++];
942 /* Now add the seconds. */
943 aind
= sizeof (abuf
) - 2;
945 abuf
[aind
--] = (sec
% 10) + '0';
949 buf
[ind
++] = abuf
[aind
++];
951 /* We want to add a decimal point and PREC places after it if PREC is
952 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
957 for (aind
= 1; aind
<= prec
; aind
++)
959 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
960 sec_fraction
%= precs
[aind
];
971 /* Interpret the format string FORMAT, interpolating the following escape
975 where the optional `prec' is a precision, meaning the number of
976 characters after the decimal point, the optional `l' means to format
977 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
978 and the last character is one of
980 R number of seconds of `real' time
981 U number of seconds of `user' time
982 S number of seconds of `system' time
984 An occurrence of `%%' in the format string is translated to a `%'. The
985 result is printed to FP, a pointer to a FILE. The other variables are
986 the seconds and thousandths of a second of real, user, and system time,
989 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1000 char *str
, *s
, ts
[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1005 len
= strlen (format
);
1006 ssize
= (len
+ 64) - (len
% 64);
1007 str
= (char *)xmalloc (ssize
);
1010 for (s
= format
; *s
; s
++)
1012 if (*s
!= '%' || s
[1] == '\0')
1014 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1017 else if (s
[1] == '%')
1020 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1023 else if (s
[1] == 'P')
1029 sum_frac
= (cpu
% 100) * 10;
1030 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1031 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1032 strcpy (str
+ sindex
, ts
);
1037 prec
= 3; /* default is three places past the decimal point. */
1038 lng
= 0; /* default is to not use minutes or append `s' */
1040 if (DIGIT (*s
)) /* `precision' */
1043 if (prec
> 3) prec
= 3;
1045 if (*s
== 'l') /* `length extender' */
1050 if (*s
== 'R' || *s
== 'E')
1051 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1053 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1055 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1058 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s
);
1062 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1063 strcpy (str
+ sindex
, ts
);
1069 fprintf (fp
, "%s\n", str
);
1076 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1078 int asynchronous
, pipe_in
, pipe_out
;
1079 struct fd_bitmap
*fds_to_close
;
1081 int rv
, posix_time
, old_flags
;
1087 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1088 struct timeval real
, user
, sys
;
1089 struct timeval before
, after
;
1090 # if defined (HAVE_STRUCT_TIMEZONE)
1091 struct timezone dtz
; /* posix doesn't define this */
1093 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1095 # if defined (HAVE_TIMES)
1096 clock_t tbefore
, tafter
, real
, user
, sys
;
1097 struct tms before
, after
;
1101 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1102 # if defined (HAVE_STRUCT_TIMEZONE)
1103 gettimeofday (&before
, &dtz
);
1105 gettimeofday (&before
, (void *)NULL
);
1106 # endif /* !HAVE_STRUCT_TIMEZONE */
1107 getrusage (RUSAGE_SELF
, &selfb
);
1108 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1110 # if defined (HAVE_TIMES)
1111 tbefore
= times (&before
);
1115 posix_time
= (command
->flags
& CMD_TIME_POSIX
);
1117 old_flags
= command
->flags
;
1118 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1119 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1120 command
->flags
= old_flags
;
1123 rsf
= usf
= ssf
= cpu
= 0;
1125 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1126 # if defined (HAVE_STRUCT_TIMEZONE)
1127 gettimeofday (&after
, &dtz
);
1129 gettimeofday (&after
, (void *)NULL
);
1130 # endif /* !HAVE_STRUCT_TIMEZONE */
1131 getrusage (RUSAGE_SELF
, &selfa
);
1132 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1134 difftimeval (&real
, &before
, &after
);
1135 timeval_to_secs (&real
, &rs
, &rsf
);
1137 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1138 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1139 timeval_to_secs (&user
, &us
, &usf
);
1141 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1142 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1143 timeval_to_secs (&sys
, &ss
, &ssf
);
1145 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1147 # if defined (HAVE_TIMES)
1148 tafter
= times (&after
);
1150 real
= tafter
- tbefore
;
1151 clock_t_to_secs (real
, &rs
, &rsf
);
1153 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1154 clock_t_to_secs (user
, &us
, &usf
);
1156 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1157 clock_t_to_secs (sys
, &ss
, &ssf
);
1159 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1163 rsf
= usf
= ssf
= cpu
= 0;
1168 time_format
= POSIX_TIMEFORMAT
;
1169 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1170 time_format
= BASH_TIMEFORMAT
;
1172 if (time_format
&& *time_format
)
1173 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1177 #endif /* COMMAND_TIMING */
1179 /* Execute a command that's supposed to be in a subshell. This must be
1180 called after make_child and we must be running in the child process.
1181 The caller will return or exit() immediately with the value this returns. */
1183 execute_in_subshell (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1186 int pipe_in
, pipe_out
;
1187 struct fd_bitmap
*fds_to_close
;
1189 int user_subshell
, return_code
, function_value
, should_redir_stdin
, invert
;
1193 USE_VAR(user_subshell
);
1196 USE_VAR(asynchronous
);
1199 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
1200 pipe_in
== NO_PIPE
&&
1201 stdin_redirects (command
->redirects
) == 0);
1203 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
1204 user_subshell
= command
->type
== cm_subshell
|| ((command
->flags
& CMD_WANT_SUBSHELL
) != 0);
1206 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
1208 /* If a command is asynchronous in a subshell (like ( foo ) & or
1209 the special case of an asynchronous GROUP command where the
1210 the subshell bit is turned on down in case cm_group: below),
1211 turn off `asynchronous', so that two subshells aren't spawned.
1212 XXX - asynchronous used to be set to 0 in this block, but that
1213 means that setup_async_signals was never run. Now it's set to
1214 0 after subshell_environment is set appropriately and setup_async_signals
1217 This seems semantically correct to me. For example,
1218 ( foo ) & seems to say ``do the command `foo' in a subshell
1219 environment, but don't wait for that subshell to finish'',
1220 and "{ foo ; bar ; } &" seems to me to be like functions or
1221 builtins in the background, which executed in a subshell
1222 environment. I just don't see the need to fork two subshells. */
1224 /* Don't fork again, we are already in a subshell. A `doubly
1225 async' shell is not interactive, however. */
1228 #if defined (JOB_CONTROL)
1229 /* If a construct like ( exec xxx yyy ) & is given while job
1230 control is active, we want to prevent exec from putting the
1231 subshell back into the original process group, carefully
1232 undoing all the work we just did in make_child. */
1234 #endif /* JOB_CONTROL */
1235 ois
= interactive_shell
;
1236 interactive_shell
= 0;
1237 /* This test is to prevent alias expansion by interactive shells that
1238 run `(command) &' but to allow scripts that have enabled alias
1239 expansion with `shopt -s expand_alias' to continue to expand
1241 if (ois
!= interactive_shell
)
1245 /* Subshells are neither login nor interactive. */
1246 login_shell
= interactive
= 0;
1249 subshell_environment
= SUBSHELL_PAREN
;
1252 subshell_environment
= 0; /* XXX */
1254 subshell_environment
|= SUBSHELL_ASYNC
;
1255 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
1256 subshell_environment
|= SUBSHELL_PIPE
;
1259 reset_terminating_signals (); /* in sig.c */
1260 /* Cancel traps, in trap.c. */
1261 restore_original_signals ();
1263 /* Make sure restore_original_signals doesn't undo the work done by
1264 make_child to ensure that asynchronous children are immune to SIGINT
1265 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1269 setup_async_signals ();
1273 #if defined (JOB_CONTROL)
1274 set_sigchld_handler ();
1275 #endif /* JOB_CONTROL */
1277 set_sigint_handler ();
1279 #if defined (JOB_CONTROL)
1280 /* Delete all traces that there were any jobs running. This is
1281 only for subshells. */
1282 without_job_control ();
1283 #endif /* JOB_CONTROL */
1286 close_fd_bitmap (fds_to_close
);
1288 do_piping (pipe_in
, pipe_out
);
1290 /* If this is a user subshell, set a flag if stdin was redirected.
1291 This is used later to decide whether to redirect fd 0 to
1292 /dev/null for async commands in the subshell. This adds more
1293 sh compatibility, but I'm not sure it's the right thing to do. */
1296 stdin_redir
= stdin_redirects (command
->redirects
);
1297 restore_default_signal (0);
1300 /* If this is an asynchronous command (command &), we want to
1301 redirect the standard input from /dev/null in the absence of
1302 any specific redirection involving stdin. */
1303 if (should_redir_stdin
&& stdin_redir
== 0)
1304 async_redirect_stdin ();
1306 /* Do redirections, then dispose of them before recursive call. */
1307 if (command
->redirects
)
1309 if (do_redirections (command
->redirects
, RX_ACTIVE
) != 0)
1310 exit (invert
? EXECUTION_SUCCESS
: EXECUTION_FAILURE
);
1312 dispose_redirects (command
->redirects
);
1313 command
->redirects
= (REDIRECT
*)NULL
;
1316 tcom
= (command
->type
== cm_subshell
) ? command
->value
.Subshell
->command
: command
;
1318 if (command
->flags
& CMD_TIME_PIPELINE
)
1319 tcom
->flags
|= CMD_TIME_PIPELINE
;
1320 if (command
->flags
& CMD_TIME_POSIX
)
1321 tcom
->flags
|= CMD_TIME_POSIX
;
1323 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1324 if ((command
->flags
& CMD_IGNORE_RETURN
) && tcom
!= command
)
1325 tcom
->flags
|= CMD_IGNORE_RETURN
;
1327 /* If this is a simple command, tell execute_disk_command that it
1328 might be able to get away without forking and simply exec.
1329 This means things like ( sleep 10 ) will only cause one fork.
1330 If we're timing the command or inverting its return value, however,
1331 we cannot do this optimization. */
1332 if (user_subshell
&& (tcom
->type
== cm_simple
|| tcom
->type
== cm_subshell
) &&
1333 ((tcom
->flags
& CMD_TIME_PIPELINE
) == 0) &&
1334 ((tcom
->flags
& CMD_INVERT_RETURN
) == 0))
1336 tcom
->flags
|= CMD_NO_FORK
;
1337 if (tcom
->type
== cm_simple
)
1338 tcom
->value
.Simple
->flags
|= CMD_NO_FORK
;
1341 invert
= (tcom
->flags
& CMD_INVERT_RETURN
) != 0;
1342 tcom
->flags
&= ~CMD_INVERT_RETURN
;
1344 /* If we're inside a function while executing this subshell, we
1345 need to handle a possible `return'. */
1347 if (return_catch_flag
)
1348 function_value
= setjmp (return_catch
);
1351 return_code
= return_catch_value
;
1353 return_code
= execute_command_internal (tcom
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
1355 /* If we are asked to, invert the return value. */
1357 return_code
= (return_code
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
1358 : EXECUTION_SUCCESS
;
1360 /* If we were explicitly placed in a subshell with (), we need
1361 to do the `shell cleanup' things, such as running traps[0]. */
1362 if (user_subshell
&& signal_is_trapped (0))
1364 last_command_exit_value
= return_code
;
1365 return_code
= run_exit_trap ();
1369 return (return_code
);
1374 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1376 int asynchronous
, pipe_in
, pipe_out
;
1377 struct fd_bitmap
*fds_to_close
;
1379 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
1381 struct fd_bitmap
*fd_bitmap
;
1383 #if defined (JOB_CONTROL)
1385 BLOCK_CHILD (set
, oset
);
1386 #endif /* JOB_CONTROL */
1388 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1393 while (cmd
&& cmd
->type
== cm_connection
&&
1394 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
1396 /* Make a pipeline between the two commands. */
1397 if (pipe (fildes
) < 0)
1399 sys_error ("pipe error");
1400 #if defined (JOB_CONTROL)
1401 terminate_current_pipeline ();
1402 kill_current_pipeline ();
1403 UNBLOCK_CHILD (oset
);
1404 #endif /* JOB_CONTROL */
1405 last_command_exit_value
= EXECUTION_FAILURE
;
1406 /* The unwind-protects installed below will take care
1407 of closing all of the open file descriptors. */
1408 throw_to_top_level ();
1409 return (EXECUTION_FAILURE
); /* XXX */
1412 /* Here is a problem: with the new file close-on-exec
1413 code, the read end of the pipe (fildes[0]) stays open
1414 in the first process, so that process will never get a
1415 SIGPIPE. There is no way to signal the first process
1416 that it should close fildes[0] after forking, so it
1417 remains open. No SIGPIPE is ever sent because there
1418 is still a file descriptor open for reading connected
1419 to the pipe. We take care of that here. This passes
1420 around a bitmap of file descriptors that must be
1421 closed after making a child process in execute_simple_command. */
1423 /* We need fd_bitmap to be at least as big as fildes[0].
1424 If fildes[0] is less than fds_to_close->size, then
1425 use fds_to_close->size. */
1426 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
1427 ? fds_to_close
->size
1430 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
1432 /* Now copy the old information into the new bitmap. */
1433 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
1435 /* And mark the pipe file descriptors to be closed. */
1436 fd_bitmap
->bitmap
[fildes
[0]] = 1;
1438 /* In case there are pipe or out-of-processes errors, we
1439 want all these file descriptors to be closed when
1440 unwind-protects are run, and the storage used for the
1441 bitmaps freed up. */
1442 begin_unwind_frame ("pipe-file-descriptors");
1443 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
1444 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
1446 add_unwind_protect (close
, prev
);
1447 dummyfd
= fildes
[1];
1448 add_unwind_protect (close
, dummyfd
);
1450 #if defined (JOB_CONTROL)
1451 add_unwind_protect (restore_signal_mask
, &oset
);
1452 #endif /* JOB_CONTROL */
1454 if (ignore_return
&& cmd
->value
.Connection
->first
)
1455 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1456 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
1457 prev
, fildes
[1], fd_bitmap
);
1465 dispose_fd_bitmap (fd_bitmap
);
1466 discard_unwind_frame ("pipe-file-descriptors");
1468 cmd
= cmd
->value
.Connection
->second
;
1471 /* Now execute the rightmost command in the pipeline. */
1472 if (ignore_return
&& cmd
)
1473 cmd
->flags
|= CMD_IGNORE_RETURN
;
1474 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
1479 #if defined (JOB_CONTROL)
1480 UNBLOCK_CHILD (oset
);
1483 return (exec_result
);
1487 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1489 int asynchronous
, pipe_in
, pipe_out
;
1490 struct fd_bitmap
*fds_to_close
;
1493 COMMAND
*tc
, *second
;
1494 int ignore_return
, exec_result
;
1496 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1498 switch (command
->value
.Connection
->connector
)
1500 /* Do the first command asynchronously. */
1502 tc
= command
->value
.Connection
->first
;
1504 return (EXECUTION_SUCCESS
);
1509 tc
->flags
|= CMD_IGNORE_RETURN
;
1510 tc
->flags
|= CMD_AMPERSAND
;
1512 /* If this shell was compiled without job control support,
1513 if we are currently in a subshell via `( xxx )', or if job
1514 control is not active then the standard input for an
1515 asynchronous command is forced to /dev/null. */
1516 #if defined (JOB_CONTROL)
1517 if ((subshell_environment
|| !job_control
) && !stdin_redir
)
1520 #endif /* JOB_CONTROL */
1521 tc
->flags
|= CMD_STDIN_REDIR
;
1523 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
1525 if (tc
->flags
& CMD_STDIN_REDIR
)
1526 tc
->flags
&= ~CMD_STDIN_REDIR
;
1528 second
= command
->value
.Connection
->second
;
1532 second
->flags
|= CMD_IGNORE_RETURN
;
1534 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1539 /* Just call execute command on both sides. */
1543 if (command
->value
.Connection
->first
)
1544 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1545 if (command
->value
.Connection
->second
)
1546 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
1549 execute_command (command
->value
.Connection
->first
);
1551 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
1552 asynchronous
, pipe_in
, pipe_out
,
1557 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1564 /* If we have something like `a && b &' or `a || b &', run the
1565 && or || stuff in a subshell. Force a subshell and just call
1566 execute_command_internal again. Leave asynchronous on
1567 so that we get a report from the parent shell about the
1569 command
->flags
|= CMD_FORCE_SUBSHELL
;
1570 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
1574 /* Execute the first command. If the result of that is successful
1575 and the connector is AND_AND, or the result is not successful
1576 and the connector is OR_OR, then execute the second command,
1577 otherwise return. */
1579 if (command
->value
.Connection
->first
)
1580 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1582 exec_result
= execute_command (command
->value
.Connection
->first
);
1584 if (((command
->value
.Connection
->connector
== AND_AND
) &&
1585 (exec_result
== EXECUTION_SUCCESS
)) ||
1586 ((command
->value
.Connection
->connector
== OR_OR
) &&
1587 (exec_result
!= EXECUTION_SUCCESS
)))
1589 if (ignore_return
&& command
->value
.Connection
->second
)
1590 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
1592 exec_result
= execute_command (command
->value
.Connection
->second
);
1597 command_error ("execute_connection", CMDERR_BADCONN
, command
->value
.Connection
->connector
, 0);
1598 jump_to_top_level (DISCARD
);
1599 exec_result
= EXECUTION_FAILURE
;
1608 if (!interactive_shell) \
1609 reap_dead_jobs (); \
1613 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1616 execute_for_command (for_command
)
1617 FOR_COM
*for_command
;
1619 register WORD_LIST
*releaser
, *list
;
1622 int retval
, save_line_number
;
1624 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
1627 save_line_number
= line_number
;
1628 if (check_identifier (for_command
->name
, 1) == 0)
1630 if (posixly_correct
&& interactive_shell
== 0)
1632 last_command_exit_value
= EX_USAGE
;
1633 jump_to_top_level (ERREXIT
);
1635 return (EXECUTION_FAILURE
);
1639 identifier
= for_command
->name
->word
;
1641 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
1643 begin_unwind_frame ("for");
1644 add_unwind_protect (dispose_words
, releaser
);
1647 if (lexical_scoping
)
1649 old_value
= copy_variable (find_variable (identifier
));
1651 add_unwind_protect (dispose_variable
, old_value
);
1655 if (for_command
->flags
& CMD_IGNORE_RETURN
)
1656 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
1658 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
1662 line_number
= for_command
->line
;
1664 /* Remember what this command looks like, for debugger. */
1665 command_string_index
= 0;
1666 print_for_command_head (for_command
);
1668 if (echo_command_at_execute
)
1669 xtrace_print_for_command_head (for_command
);
1671 /* Save this command unless it's a trap command and we're not running
1674 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
1676 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
1679 FREE (the_printed_command_except_trap
);
1680 the_printed_command_except_trap
= savestring (the_printed_command
);
1683 retval
= run_debug_trap ();
1684 #if defined (DEBUGGER)
1685 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1686 skip the command. */
1687 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
1691 this_command_name
= (char *)NULL
;
1692 v
= bind_variable (identifier
, list
->word
->word
, 0);
1693 if (readonly_p (v
) || noassign_p (v
))
1695 line_number
= save_line_number
;
1696 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
1698 last_command_exit_value
= EXECUTION_FAILURE
;
1699 jump_to_top_level (FORCE_EOF
);
1703 dispose_words (releaser
);
1704 discard_unwind_frame ("for");
1706 return (EXECUTION_FAILURE
);
1709 retval
= execute_command (for_command
->action
);
1728 line_number
= save_line_number
;
1731 if (lexical_scoping
)
1734 unbind_variable (identifier
);
1737 SHELL_VAR
*new_value
;
1739 new_value
= bind_variable (identifier
, value_cell(old_value
), 0);
1740 new_value
->attributes
= old_value
->attributes
;
1741 dispose_variable (old_value
);
1746 dispose_words (releaser
);
1747 discard_unwind_frame ("for");
1751 #if defined (ARITH_FOR_COMMAND)
1752 /* Execute an arithmetic for command. The syntax is
1754 for (( init ; step ; test ))
1759 The execution should be exactly equivalent to
1762 while eval \(\( test \)\) ; do
1768 eval_arith_for_expr (l
, okp
)
1776 new = expand_words_no_vars (l
);
1779 if (echo_command_at_execute
)
1780 xtrace_print_arith_cmd (new);
1781 this_command_name
= "(("; /* )) for expression error messages */
1783 command_string_index
= 0;
1784 print_arith_command (new);
1785 if (signal_in_progress (DEBUG_TRAP
) == 0)
1787 FREE (the_printed_command_except_trap
);
1788 the_printed_command_except_trap
= savestring (the_printed_command
);
1791 r
= run_debug_trap ();
1792 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1793 skip the command. */
1794 #if defined (DEBUGGER)
1795 if (debugging_mode
== 0 || r
== EXECUTION_SUCCESS
)
1796 expresult
= evalexp (new->word
->word
, okp
);
1804 expresult
= evalexp (new->word
->word
, okp
);
1806 dispose_words (new);
1818 execute_arith_for_command (arith_for_command
)
1819 ARITH_FOR_COM
*arith_for_command
;
1822 int expok
, body_status
, arith_lineno
, save_lineno
;
1824 body_status
= EXECUTION_SUCCESS
;
1826 save_lineno
= line_number
;
1828 if (arith_for_command
->flags
& CMD_IGNORE_RETURN
)
1829 arith_for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
1831 this_command_name
= "(("; /* )) for expression error messages */
1833 /* save the starting line number of the command so we can reset
1834 line_number before executing each expression -- for $LINENO
1835 and the DEBUG trap. */
1836 line_number
= arith_lineno
= arith_for_command
->line
;
1837 if (variable_context
&& interactive_shell
)
1838 line_number
-= function_line_number
;
1840 /* Evaluate the initialization expression. */
1841 expresult
= eval_arith_for_expr (arith_for_command
->init
, &expok
);
1844 line_number
= save_lineno
;
1845 return (EXECUTION_FAILURE
);
1850 /* Evaluate the test expression. */
1851 line_number
= arith_lineno
;
1852 expresult
= eval_arith_for_expr (arith_for_command
->test
, &expok
);
1853 line_number
= save_lineno
;
1857 body_status
= EXECUTION_FAILURE
;
1864 /* Execute the body of the arithmetic for command. */
1866 body_status
= execute_command (arith_for_command
->action
);
1869 /* Handle any `break' or `continue' commands executed by the body. */
1883 /* Evaluate the step expression. */
1884 line_number
= arith_lineno
;
1885 expresult
= eval_arith_for_expr (arith_for_command
->step
, &expok
);
1886 line_number
= save_lineno
;
1890 body_status
= EXECUTION_FAILURE
;
1896 line_number
= save_lineno
;
1898 return (body_status
);
1902 #if defined (SELECT_COMMAND)
1903 static int LINES
, COLS
, tabsize
;
1905 #define RP_SPACE ") "
1906 #define RP_SPACE_LEN 2
1908 /* XXX - does not handle numbers > 1000000 at all. */
1909 #define NUMBER_LEN(s) \
1913 : ((s < 10000) ? 4 \
1914 : ((s < 100000) ? 5 \
1918 print_index_and_element (len
, ind
, list
)
1922 register WORD_LIST
*l
;
1927 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
1929 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
1930 return (STRLEN (l
->word
->word
));
1939 if ((to
/ tabsize
) > (from
/ tabsize
))
1941 putc ('\t', stderr
);
1942 from
+= tabsize
- from
% tabsize
;
1953 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
1955 int list_len
, max_elem_len
, indices_len
;
1957 int ind
, row
, elem_len
, pos
, cols
, rows
;
1958 int first_column_indices_len
, other_indices_len
;
1962 putc ('\n', stderr
);
1966 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
1969 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
1970 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
1978 first_column_indices_len
= NUMBER_LEN (rows
);
1979 other_indices_len
= indices_len
;
1981 for (row
= 0; row
< rows
; row
++)
1987 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
1988 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
1989 elem_len
+= indices_len
+ RP_SPACE_LEN
;
1991 if (ind
>= list_len
)
1993 indent (pos
+ elem_len
, pos
+ max_elem_len
);
1994 pos
+= max_elem_len
;
1996 putc ('\n', stderr
);
2000 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2001 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2002 If the number is between 1 and LIST_LEN, return that selection. If EOF
2003 is read, return a null string. If a blank line is entered, or an invalid
2004 number is entered, the loop is executed again. */
2006 select_query (list
, list_len
, prompt
, print_menu
)
2012 int max_elem_len
, indices_len
, len
;
2015 char *repl_string
, *t
;
2017 t
= get_string_value ("LINES");
2018 LINES
= (t
&& *t
) ? atoi (t
) : 24;
2019 t
= get_string_value ("COLUMNS");
2020 COLS
= (t
&& *t
) ? atoi (t
) : 80;
2023 t
= get_string_value ("TABSIZE");
2024 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
2032 for (l
= list
; l
; l
= l
->next
)
2034 len
= STRLEN (l
->word
->word
);
2035 if (len
> max_elem_len
)
2038 indices_len
= NUMBER_LEN (list_len
);
2039 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
2044 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
2045 fprintf (stderr
, "%s", prompt
);
2049 if (read_builtin ((WORD_LIST
*)NULL
) == EXECUTION_FAILURE
)
2052 return ((char *)NULL
);
2054 repl_string
= get_string_value ("REPLY");
2055 if (*repl_string
== 0)
2060 if (legal_number (repl_string
, &reply
) == 0)
2062 if (reply
< 1 || reply
> list_len
)
2065 for (l
= list
; l
&& --reply
; l
= l
->next
)
2067 return (l
->word
->word
);
2071 /* Execute a SELECT command. The syntax is:
2072 SELECT word IN list DO command_list DONE
2073 Only `break' or `return' in command_list will terminate
2076 execute_select_command (select_command
)
2077 SELECT_COM
*select_command
;
2079 WORD_LIST
*releaser
, *list
;
2081 char *identifier
, *ps3_prompt
, *selection
;
2082 int retval
, list_len
, show_menu
, save_line_number
;
2084 if (check_identifier (select_command
->name
, 1) == 0)
2085 return (EXECUTION_FAILURE
);
2087 save_line_number
= line_number
;
2088 line_number
= select_command
->line
;
2090 command_string_index
= 0;
2091 print_select_command_head (select_command
);
2093 if (echo_command_at_execute
)
2094 xtrace_print_select_command_head (select_command
);
2097 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2099 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2102 FREE (the_printed_command_except_trap
);
2103 the_printed_command_except_trap
= savestring (the_printed_command
);
2106 retval
= run_debug_trap ();
2107 #if defined (DEBUGGER)
2108 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2109 skip the command. */
2110 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2111 return (EXECUTION_SUCCESS
);
2115 identifier
= select_command
->name
->word
;
2117 /* command and arithmetic substitution, parameter and variable expansion,
2118 word splitting, pathname expansion, and quote removal. */
2119 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
2120 list_len
= list_length (list
);
2121 if (list
== 0 || list_len
== 0)
2124 dispose_words (list
);
2125 line_number
= save_line_number
;
2126 return (EXECUTION_SUCCESS
);
2129 begin_unwind_frame ("select");
2130 add_unwind_protect (dispose_words
, releaser
);
2132 if (select_command
->flags
& CMD_IGNORE_RETURN
)
2133 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2135 retval
= EXECUTION_SUCCESS
;
2140 line_number
= select_command
->line
;
2141 ps3_prompt
= get_string_value ("PS3");
2142 if (ps3_prompt
== 0)
2146 selection
= select_query (list
, list_len
, ps3_prompt
, show_menu
);
2150 /* select_query returns EXECUTION_FAILURE if the read builtin
2151 fails, so we want to return failure in this case. */
2152 retval
= EXECUTION_FAILURE
;
2156 v
= bind_variable (identifier
, selection
, 0);
2157 if (readonly_p (v
) || noassign_p (v
))
2159 if (readonly_p (v
) && interactive_shell
== 0 && posixly_correct
)
2161 last_command_exit_value
= EXECUTION_FAILURE
;
2162 jump_to_top_level (FORCE_EOF
);
2166 dispose_words (releaser
);
2167 discard_unwind_frame ("select");
2169 line_number
= save_line_number
;
2170 return (EXECUTION_FAILURE
);
2174 retval
= execute_command (select_command
->action
);
2192 #if defined (KSH_COMPATIBLE_SELECT)
2194 selection
= get_string_value ("REPLY");
2195 if (selection
&& *selection
== '\0')
2201 line_number
= save_line_number
;
2203 dispose_words (releaser
);
2204 discard_unwind_frame ("select");
2207 #endif /* SELECT_COMMAND */
2209 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2210 The pattern_list is a linked list of pattern clauses; each clause contains
2211 some patterns to compare word_desc against, and an associated command to
2214 execute_case_command (case_command
)
2215 CASE_COM
*case_command
;
2217 register WORD_LIST
*list
;
2218 WORD_LIST
*wlist
, *es
;
2219 PATTERN_LIST
*clauses
;
2220 char *word
, *pattern
;
2221 int retval
, match
, ignore_return
, save_line_number
;
2223 save_line_number
= line_number
;
2224 line_number
= case_command
->line
;
2226 command_string_index
= 0;
2227 print_case_command_head (case_command
);
2229 if (echo_command_at_execute
)
2230 xtrace_print_case_command_head (case_command
);
2233 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2235 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2238 FREE (the_printed_command_except_trap
);
2239 the_printed_command_except_trap
= savestring (the_printed_command
);
2242 retval
= run_debug_trap();
2243 #if defined (DEBUGGER)
2244 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2245 skip the command. */
2246 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2248 line_number
= save_line_number
;
2249 return (EXECUTION_SUCCESS
);
2253 wlist
= expand_word_unsplit (case_command
->word
, 0);
2254 word
= wlist
? string_list (wlist
) : savestring ("");
2255 dispose_words (wlist
);
2257 retval
= EXECUTION_SUCCESS
;
2258 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
2260 begin_unwind_frame ("case");
2261 add_unwind_protect ((Function
*)xfree
, word
);
2263 #define EXIT_CASE() goto exit_case_command
2265 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
2268 for (list
= clauses
->patterns
; list
; list
= list
->next
)
2270 es
= expand_word_leave_quoted (list
->word
, 0);
2272 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
2273 pattern
= quote_string_for_globbing (es
->word
->word
, QGLOB_CVTNULL
);
2276 pattern
= (char *)xmalloc (1);
2280 /* Since the pattern does not undergo quote removal (as per
2281 Posix.2, section 3.9.4.3), the strmatch () call must be able
2282 to recognize backslashes as escape characters. */
2283 match
= strmatch (pattern
, word
, FNMATCH_EXTFLAG
|FNMATCH_IGNCASE
) != FNM_NOMATCH
;
2290 if (clauses
->action
&& ignore_return
)
2291 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
2292 retval
= execute_command (clauses
->action
);
2302 discard_unwind_frame ("case");
2303 line_number
= save_line_number
;
2310 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2311 Repeatedly execute action while executing test produces
2312 EXECUTION_SUCCESS. */
2314 execute_while_command (while_command
)
2315 WHILE_COM
*while_command
;
2317 return (execute_while_or_until (while_command
, CMD_WHILE
));
2320 /* UNTIL is just like WHILE except that the test result is negated. */
2322 execute_until_command (while_command
)
2323 WHILE_COM
*while_command
;
2325 return (execute_while_or_until (while_command
, CMD_UNTIL
));
2328 /* The body for both while and until. The only difference between the
2329 two is that the test value is treated differently. TYPE is
2330 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2331 be EXECUTION_SUCCESS if no commands in the body are executed, and
2332 the status of the last command executed in the body otherwise. */
2334 execute_while_or_until (while_command
, type
)
2335 WHILE_COM
*while_command
;
2338 int return_value
, body_status
;
2340 body_status
= EXECUTION_SUCCESS
;
2343 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2344 if (while_command
->flags
& CMD_IGNORE_RETURN
)
2345 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2349 return_value
= execute_command (while_command
->test
);
2352 /* Need to handle `break' in the test when we would break out of the
2353 loop. The job control code will set `breaking' to loop_level
2354 when a job in a loop is stopped with SIGTSTP. If the stopped job
2355 is in the loop test, `breaking' will not be reset unless we do
2356 this, and the shell will cease to execute commands. */
2357 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
2363 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
2371 body_status
= execute_command (while_command
->action
);
2389 return (body_status
);
2392 /* IF test THEN command [ELSE command].
2393 IF also allows ELIF in the place of ELSE IF, but
2394 the parser makes *that* stupidity transparent. */
2396 execute_if_command (if_command
)
2399 int return_value
, save_line_number
;
2401 save_line_number
= line_number
;
2402 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2403 return_value
= execute_command (if_command
->test
);
2404 line_number
= save_line_number
;
2406 if (return_value
== EXECUTION_SUCCESS
)
2410 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2411 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
2413 return (execute_command (if_command
->true_case
));
2419 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2420 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
2422 return (execute_command (if_command
->false_case
));
2426 #if defined (DPAREN_ARITHMETIC)
2428 execute_arith_command (arith_command
)
2429 ARITH_COM
*arith_command
;
2431 int expok
, save_line_number
, retval
;
2438 save_line_number
= line_number
;
2439 this_command_name
= "(("; /* )) */
2440 line_number
= arith_command
->line
;
2441 /* If we're in a function, update the line number information. */
2442 if (variable_context
&& interactive_shell
)
2443 line_number
-= function_line_number
;
2445 command_string_index
= 0;
2446 print_arith_command (arith_command
->exp
);
2448 if (signal_in_progress (DEBUG_TRAP
) == 0)
2450 FREE (the_printed_command_except_trap
);
2451 the_printed_command_except_trap
= savestring (the_printed_command
);
2454 /* Run the debug trap before each arithmetic command, but do it after we
2455 update the line number information and before we expand the various
2456 words in the expression. */
2457 retval
= run_debug_trap ();
2458 #if defined (DEBUGGER)
2459 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2460 skip the command. */
2461 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2463 line_number
= save_line_number
;
2464 return (EXECUTION_SUCCESS
);
2468 new = expand_words_no_vars (arith_command
->exp
);
2470 /* If we're tracing, make a new word list with `((' at the front and `))'
2471 at the back and print it. */
2472 if (echo_command_at_execute
)
2473 xtrace_print_arith_cmd (new);
2477 exp
= new->next
? string_list (new) : new->word
->word
;
2478 expresult
= evalexp (exp
, &expok
);
2479 line_number
= save_line_number
;
2480 if (exp
!= new->word
->word
)
2482 dispose_words (new);
2491 return (EXECUTION_FAILURE
);
2493 return (expresult
== 0 ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
);
2495 #endif /* DPAREN_ARITHMETIC */
2497 #if defined (COND_COMMAND)
2499 static char *nullstr
= "";
2502 execute_cond_node (cond
)
2505 int result
, invert
, patmatch
, rmatch
, mflags
;
2508 invert
= (cond
->flags
& CMD_INVERT_RETURN
);
2510 if (cond
->type
== COND_EXPR
)
2511 result
= execute_cond_node (cond
->left
);
2512 else if (cond
->type
== COND_OR
)
2514 result
= execute_cond_node (cond
->left
);
2515 if (result
!= EXECUTION_SUCCESS
)
2516 result
= execute_cond_node (cond
->right
);
2518 else if (cond
->type
== COND_AND
)
2520 result
= execute_cond_node (cond
->left
);
2521 if (result
== EXECUTION_SUCCESS
)
2522 result
= execute_cond_node (cond
->right
);
2524 else if (cond
->type
== COND_UNARY
)
2526 arg1
= cond_expand_word (cond
->left
->op
, 0);
2529 if (echo_command_at_execute
)
2530 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, (char *)NULL
);
2531 result
= unary_test (cond
->op
->word
, arg1
) ? EXECUTION_SUCCESS
: EXECUTION_FAILURE
;
2532 if (arg1
!= nullstr
)
2535 else if (cond
->type
== COND_BINARY
)
2538 patmatch
= ((cond
->op
->word
[1] == '=') && (cond
->op
->word
[2] == '\0') &&
2539 (cond
->op
->word
[0] == '!' || cond
->op
->word
[0] == '=') ||
2540 (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '\0'));
2541 #if defined (COND_REGEXP)
2542 rmatch
= (cond
->op
->word
[0] == '=' && cond
->op
->word
[1] == '~' &&
2543 cond
->op
->word
[2] == '\0');
2546 arg1
= cond_expand_word (cond
->left
->op
, 0);
2549 arg2
= cond_expand_word (cond
->right
->op
, patmatch
||rmatch
);
2553 if (echo_command_at_execute
)
2554 xtrace_print_cond_term (cond
->type
, invert
, cond
->op
, arg1
, arg2
);
2556 #if defined (COND_REGEXP)
2559 mflags
= SHMAT_PWARN
;
2560 #if defined (ARRAY_VARS)
2561 mflags
|= SHMAT_SUBEXP
;
2564 result
= sh_regmatch (arg1
, arg2
, mflags
);
2567 #endif /* COND_REGEXP */
2572 result
= binary_test (cond
->op
->word
, arg1
, arg2
, TEST_PATMATCH
|TEST_ARITHEXP
)
2574 : EXECUTION_FAILURE
;
2577 if (arg1
!= nullstr
)
2579 if (arg2
!= nullstr
)
2584 command_error ("execute_cond_node", CMDERR_BADTYPE
, cond
->type
, 0);
2585 jump_to_top_level (DISCARD
);
2586 result
= EXECUTION_FAILURE
;
2590 result
= (result
== EXECUTION_SUCCESS
) ? EXECUTION_FAILURE
: EXECUTION_SUCCESS
;
2596 execute_cond_command (cond_command
)
2597 COND_COM
*cond_command
;
2599 int retval
, save_line_number
;
2601 retval
= EXECUTION_SUCCESS
;
2602 save_line_number
= line_number
;
2604 this_command_name
= "[[";
2605 line_number
= cond_command
->line
;
2606 /* If we're in a function, update the line number information. */
2607 if (variable_context
&& interactive_shell
)
2608 line_number
-= function_line_number
;
2610 command_string_index
= 0;
2611 print_cond_command (cond_command
);
2613 if (signal_in_progress (DEBUG_TRAP
) == 0)
2615 FREE (the_printed_command_except_trap
);
2616 the_printed_command_except_trap
= savestring (the_printed_command
);
2619 /* Run the debug trap before each conditional command, but do it after we
2620 update the line number information. */
2621 retval
= run_debug_trap ();
2622 #if defined (DEBUGGER)
2623 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2624 skip the command. */
2625 if (debugging_mode
&& retval
!= EXECUTION_SUCCESS
)
2627 line_number
= save_line_number
;
2628 return (EXECUTION_SUCCESS
);
2633 debug_print_cond_command (cond_command
);
2636 last_command_exit_value
= retval
= execute_cond_node (cond_command
);
2637 line_number
= save_line_number
;
2640 #endif /* COND_COMMAND */
2650 var
= bind_variable ("_", arg
, 0);
2651 VUNSETATTR (var
, att_exported
);
2654 /* Execute a null command. Fork a subshell if the command uses pipes or is
2655 to be run asynchronously. This handles all the side effects that are
2656 supposed to take place. */
2658 execute_null_command (redirects
, pipe_in
, pipe_out
, async
)
2659 REDIRECT
*redirects
;
2660 int pipe_in
, pipe_out
, async
;
2664 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
2666 /* We have a null command, but we really want a subshell to take
2667 care of it. Just fork, do piping and redirections, and exit. */
2668 if (make_child ((char *)NULL
, async
) == 0)
2670 /* Cancel traps, in trap.c. */
2671 restore_original_signals (); /* XXX */
2673 do_piping (pipe_in
, pipe_out
);
2676 subshell_environment
|= SUBSHELL_ASYNC
;
2677 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
2678 subshell_environment
|= SUBSHELL_PIPE
;
2680 if (do_redirections (redirects
, RX_ACTIVE
) == 0)
2681 exit (EXECUTION_SUCCESS
);
2683 exit (EXECUTION_FAILURE
);
2687 close_pipes (pipe_in
, pipe_out
);
2688 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2689 unlink_fifo_list ();
2691 return (EXECUTION_SUCCESS
);
2696 /* Even if there aren't any command names, pretend to do the
2697 redirections that are specified. The user expects the side
2698 effects to take place. If the redirections fail, then return
2699 failure. Otherwise, if a command substitution took place while
2700 expanding the command or a redirection, return the value of that
2701 substitution. Otherwise, return EXECUTION_SUCCESS. */
2703 r
= do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
);
2704 cleanup_redirects (redirection_undo_list
);
2705 redirection_undo_list
= (REDIRECT
*)NULL
;
2708 return (EXECUTION_FAILURE
);
2709 else if (last_command_subst_pid
!= NO_PID
)
2710 return (last_command_exit_value
);
2712 return (EXECUTION_SUCCESS
);
2716 /* This is a hack to suppress word splitting for assignment statements
2717 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2719 fix_assignment_words (words
)
2730 for (w
= words
; w
; w
= w
->next
)
2731 if (w
->word
->flags
& W_ASSIGNMENT
)
2735 b
= builtin_address_internal (words
->word
->word
, 0);
2736 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
2738 else if (b
&& (b
->flags
& ASSIGNMENT_BUILTIN
))
2739 words
->word
->flags
|= W_ASSNBLTIN
;
2741 w
->word
->flags
|= (W_NOSPLIT
|W_NOGLOB
|W_TILDEEXP
|W_ASSIGNARG
);
2745 /* The meaty part of all the executions. We have to start hacking the
2746 real execution of commands here. Fork a process, set things up,
2747 execute the command. */
2749 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
2750 SIMPLE_COM
*simple_command
;
2751 int pipe_in
, pipe_out
, async
;
2752 struct fd_bitmap
*fds_to_close
;
2754 WORD_LIST
*words
, *lastword
;
2755 char *command_line
, *lastarg
, *temp
;
2756 int first_word_quoted
, result
, builtin_is_special
, already_forked
, dofork
;
2757 pid_t old_last_async_pid
;
2758 sh_builtin_func_t
*builtin
;
2761 result
= EXECUTION_SUCCESS
;
2762 special_builtin_failed
= builtin_is_special
= 0;
2763 command_line
= (char *)0;
2765 /* If we're in a function, update the line number information. */
2766 if (variable_context
&& interactive_shell
)
2767 line_number
-= function_line_number
;
2769 /* Remember what this command line looks like at invocation. */
2770 command_string_index
= 0;
2771 print_simple_command (simple_command
);
2774 if (signal_in_progress (DEBUG_TRAP
) == 0 && (this_command_name
== 0 || (STREQ (this_command_name
, "trap") == 0)))
2776 if (signal_in_progress (DEBUG_TRAP
) == 0 && running_trap
== 0)
2779 FREE (the_printed_command_except_trap
);
2780 the_printed_command_except_trap
= the_printed_command
? savestring (the_printed_command
) : (char *)0;
2783 /* Run the debug trap before each simple command, but do it after we
2784 update the line number information. */
2785 result
= run_debug_trap ();
2786 #if defined (DEBUGGER)
2787 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2788 skip the command. */
2789 if (debugging_mode
&& result
!= EXECUTION_SUCCESS
)
2790 return (EXECUTION_SUCCESS
);
2794 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
): 0;
2796 last_command_subst_pid
= NO_PID
;
2797 old_last_async_pid
= last_asynchronous_pid
;
2799 already_forked
= dofork
= 0;
2801 /* If we're in a pipeline or run in the background, set DOFORK so we
2802 make the child early, before word expansion. This keeps assignment
2803 statements from affecting the parent shell's environment when they
2805 dofork
= pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
;
2807 /* Something like `%2 &' should restart job 2 in the background, not cause
2808 the shell to fork here. */
2809 if (dofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
&&
2810 simple_command
->words
&& simple_command
->words
->word
&&
2811 simple_command
->words
->word
->word
&&
2812 (simple_command
->words
->word
->word
[0] == '%'))
2817 /* Do this now, because execute_disk_command will do it anyway in the
2818 vast majority of cases. */
2819 maybe_make_export_env ();
2821 /* Don't let a DEBUG trap overwrite the command string to be saved with
2822 the process/job associated with this child. */
2823 if (make_child (savestring (the_printed_command_except_trap
), async
) == 0)
2826 simple_command
->flags
|= CMD_NO_FORK
;
2828 subshell_environment
= SUBSHELL_FORK
;
2829 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
2830 subshell_environment
|= SUBSHELL_PIPE
;
2832 subshell_environment
|= SUBSHELL_ASYNC
;
2834 /* We need to do this before piping to handle some really
2835 pathological cases where one of the pipe file descriptors
2838 close_fd_bitmap (fds_to_close
);
2840 do_piping (pipe_in
, pipe_out
);
2841 pipe_in
= pipe_out
= NO_PIPE
;
2843 last_asynchronous_pid
= old_last_async_pid
;
2847 close_pipes (pipe_in
, pipe_out
);
2848 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2849 unlink_fifo_list ();
2851 command_line
= (char *)NULL
; /* don't free this. */
2852 bind_lastarg ((char *)NULL
);
2857 /* If we are re-running this as the result of executing the `command'
2858 builtin, do not expand the command words a second time. */
2859 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
2861 current_fds_to_close
= fds_to_close
;
2862 fix_assignment_words (simple_command
->words
);
2863 words
= expand_words (simple_command
->words
);
2864 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
2867 words
= copy_word_list (simple_command
->words
);
2869 /* It is possible for WORDS not to have anything left in it.
2870 Perhaps all the words consisted of `$foo', and there was
2871 no variable `$foo'. */
2874 this_command_name
= 0;
2875 result
= execute_null_command (simple_command
->redirects
,
2877 already_forked
? 0 : async
);
2882 bind_lastarg ((char *)NULL
);
2883 set_pipestatus_from_exit (result
);
2888 lastarg
= (char *)NULL
;
2890 begin_unwind_frame ("simple-command");
2892 if (echo_command_at_execute
)
2893 xtrace_print_word_list (words
, 1);
2895 builtin
= (sh_builtin_func_t
*)NULL
;
2896 func
= (SHELL_VAR
*)NULL
;
2897 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
2899 /* Posix.2 says special builtins are found before functions. We
2900 don't set builtin_is_special anywhere other than here, because
2901 this path is followed only when the `command' builtin is *not*
2902 being used, and we don't want to exit the shell if a special
2903 builtin executed with `command builtin' fails. `command' is not
2904 a special builtin. */
2905 if (posixly_correct
)
2907 builtin
= find_special_builtin (words
->word
->word
);
2909 builtin_is_special
= 1;
2912 func
= find_function (words
->word
->word
);
2915 /* In POSIX mode, assignment errors in the temporary environment cause a
2916 non-interactive shell to exit. */
2917 if (builtin_is_special
&& interactive_shell
== 0 && tempenv_assign_error
)
2919 last_command_exit_value
= EXECUTION_FAILURE
;
2920 jump_to_top_level (ERREXIT
);
2923 add_unwind_protect (dispose_words
, words
);
2926 /* Bind the last word in this command to "$_" after execution. */
2927 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
2929 lastarg
= lastword
->word
->word
;
2931 #if defined (JOB_CONTROL)
2932 /* Is this command a job control related thing? */
2933 if (words
->word
->word
[0] == '%' && already_forked
== 0)
2935 this_command_name
= async
? "bg" : "fg";
2936 last_shell_builtin
= this_shell_builtin
;
2937 this_shell_builtin
= builtin_address (this_command_name
);
2938 result
= (*this_shell_builtin
) (words
);
2942 /* One other possiblilty. The user may want to resume an existing job.
2943 If they do, find out whether this word is a candidate for a running
2945 if (job_control
&& already_forked
== 0 && async
== 0 &&
2946 !first_word_quoted
&&
2948 words
->word
->word
[0] &&
2949 !simple_command
->redirects
&&
2950 pipe_in
== NO_PIPE
&&
2951 pipe_out
== NO_PIPE
&&
2952 (temp
= get_string_value ("auto_resume")))
2954 int job
, jflags
, started_status
;
2956 jflags
= JM_STOPPED
|JM_FIRSTMATCH
;
2957 if (STREQ (temp
, "exact"))
2959 else if (STREQ (temp
, "substring"))
2960 jflags
|= JM_SUBSTRING
;
2962 jflags
|= JM_PREFIX
;
2963 job
= get_job_by_name (words
->word
->word
, jflags
);
2966 run_unwind_frame ("simple-command");
2967 this_command_name
= "fg";
2968 last_shell_builtin
= this_shell_builtin
;
2969 this_shell_builtin
= builtin_address ("fg");
2971 started_status
= start_job (job
, 1);
2972 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
2975 #endif /* JOB_CONTROL */
2977 /* Remember the name of this command globally. */
2978 this_command_name
= words
->word
->word
;
2982 /* This command could be a shell builtin or a user-defined function.
2983 We have already found special builtins by this time, so we do not
2984 set builtin_is_special. If this is a function or builtin, and we
2985 have pipes, then fork a subshell in here. Otherwise, just execute
2986 the command directly. */
2987 if (func
== 0 && builtin
== 0)
2988 builtin
= find_shell_builtin (this_command_name
);
2990 last_shell_builtin
= this_shell_builtin
;
2991 this_shell_builtin
= builtin
;
2993 if (builtin
|| func
)
2997 /* reset_terminating_signals (); */ /* XXX */
2998 /* Cancel traps, in trap.c. */
2999 restore_original_signals ();
3003 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
3004 pipe_in
== NO_PIPE
&&
3005 (stdin_redirects (simple_command
->redirects
) == 0))
3006 async_redirect_stdin ();
3007 setup_async_signals ();
3011 execute_subshell_builtin_or_function
3012 (words
, simple_command
->redirects
, builtin
, func
,
3013 pipe_in
, pipe_out
, async
, fds_to_close
,
3014 simple_command
->flags
);
3019 result
= execute_builtin_or_function
3020 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
3021 simple_command
->flags
);
3024 if (result
> EX_SHERRBASE
)
3026 result
= builtin_status (result
);
3027 if (builtin_is_special
)
3028 special_builtin_failed
= 1;
3030 /* In POSIX mode, if there are assignment statements preceding
3031 a special builtin, they persist after the builtin
3033 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
3034 merge_temporary_env ();
3038 if (result
== EX_USAGE
)
3039 result
= EX_BADUSAGE
;
3040 else if (result
> EX_SHERRBASE
)
3041 result
= EXECUTION_FAILURE
;
3044 set_pipestatus_from_exit (result
);
3050 if (command_line
== 0)
3051 command_line
= savestring (the_printed_command_except_trap
);
3053 execute_disk_command (words
, simple_command
->redirects
, command_line
,
3054 pipe_in
, pipe_out
, async
, fds_to_close
,
3055 simple_command
->flags
);
3058 bind_lastarg (lastarg
);
3059 FREE (command_line
);
3060 dispose_words (words
);
3061 discard_unwind_frame ("simple-command");
3062 this_command_name
= (char *)NULL
; /* points to freed memory now */
3066 /* Translate the special builtin exit statuses. We don't really need a
3067 function for this; it's a placeholder for future work. */
3069 builtin_status (result
)
3083 r
= EXECUTION_FAILURE
;
3086 r
= EXECUTION_SUCCESS
;
3093 execute_builtin (builtin
, words
, flags
, subshell
)
3094 sh_builtin_func_t
*builtin
;
3096 int flags
, subshell
;
3098 int old_e_flag
, result
, eval_unwind
;
3101 old_e_flag
= exit_immediately_on_error
;
3102 /* The eval builtin calls parse_and_execute, which does not know about
3103 the setting of flags, and always calls the execution functions with
3104 flags that will exit the shell on an error if -e is set. If the
3105 eval builtin is being called, and we're supposed to ignore the exit
3106 value of the command, we turn the -e flag off ourselves, then
3107 restore it when the command completes. */
3108 if (subshell
== 0 && builtin
== eval_builtin
&& (flags
& CMD_IGNORE_RETURN
))
3110 begin_unwind_frame ("eval_builtin");
3111 unwind_protect_int (exit_immediately_on_error
);
3112 exit_immediately_on_error
= 0;
3118 /* The temporary environment for a builtin is supposed to apply to
3119 all commands executed by that builtin. Currently, this is a
3120 problem only with the `unset', `source' and `eval' builtins. */
3122 isbltinenv
= (builtin
== source_builtin
|| builtin
== eval_builtin
|| builtin
== unset_builtin
);
3127 begin_unwind_frame ("builtin_env");
3131 push_scope (VC_BLTNENV
, temporary_env
);
3133 add_unwind_protect (pop_scope
, (flags
& CMD_COMMAND_BUILTIN
) ? 0 : "1");
3134 temporary_env
= (HASH_TABLE
*)NULL
;
3138 /* `return' does a longjmp() back to a saved environment in execute_function.
3139 If a variable assignment list preceded the command, and the shell is
3140 running in POSIX mode, we need to merge that into the shell_variables
3141 table, since `return' is a POSIX special builtin. */
3142 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3144 begin_unwind_frame ("return_temp_env");
3145 add_unwind_protect (merge_temporary_env
, (char *)NULL
);
3148 result
= ((*builtin
) (words
->next
));
3150 /* This shouldn't happen, but in case `return' comes back instead of
3151 longjmp'ing, we need to unwind. */
3152 if (posixly_correct
&& subshell
== 0 && builtin
== return_builtin
&& temporary_env
)
3153 discard_unwind_frame ("return_temp_env");
3155 if (subshell
== 0 && isbltinenv
)
3156 run_unwind_frame ("builtin_env");
3160 exit_immediately_on_error
+= old_e_flag
;
3161 discard_unwind_frame ("eval_builtin");
3168 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
3172 struct fd_bitmap
*fds_to_close
;
3173 int async
, subshell
;
3175 int return_val
, result
;
3176 COMMAND
*tc
, *fc
, *save_current
;
3177 char *debug_trap
, *error_trap
, *return_trap
;
3178 #if defined (ARRAY_VARS)
3179 SHELL_VAR
*funcname_v
, *nfv
, *bash_source_v
, *bash_lineno_v
;
3180 ARRAY
*funcname_a
, *bash_source_a
, *bash_lineno_a
;
3182 FUNCTION_DEF
*shell_fn
;
3184 static int funcnest
= 0;
3188 #if defined (ARRAY_VARS)
3189 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v
, funcname_a
);
3190 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v
, bash_source_a
);
3191 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v
, bash_lineno_a
);
3194 tc
= (COMMAND
*)copy_command (function_cell (var
));
3195 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
3196 tc
->flags
|= CMD_IGNORE_RETURN
;
3200 begin_unwind_frame ("function_calling");
3201 push_context (var
->name
, subshell
, temporary_env
);
3202 add_unwind_protect (pop_context
, (char *)NULL
);
3203 unwind_protect_int (line_number
);
3204 unwind_protect_int (return_catch_flag
);
3205 unwind_protect_jmp_buf (return_catch
);
3206 add_unwind_protect (dispose_command
, (char *)tc
);
3207 unwind_protect_pointer (this_shell_function
);
3208 unwind_protect_int (loop_level
);
3211 push_context (var
->name
, subshell
, temporary_env
); /* don't unwind-protect for subshells */
3213 temporary_env
= (HASH_TABLE
*)NULL
;
3215 this_shell_function
= var
;
3216 make_funcname_visible (1);
3218 debug_trap
= TRAP_STRING(DEBUG_TRAP
);
3219 error_trap
= TRAP_STRING(ERROR_TRAP
);
3220 return_trap
= TRAP_STRING(RETURN_TRAP
);
3222 /* The order of the unwind protects for debug_trap, error_trap and
3223 return_trap is important here! unwind-protect commands are run
3224 in reverse order of registration. If this causes problems, take
3225 out the xfree unwind-protect calls and live with the small memory leak. */
3227 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3228 if the function has the trace attribute set, it inherits the DEBUG trap */
3229 if (debug_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
3233 debug_trap
= savestring (debug_trap
);
3234 add_unwind_protect (xfree
, debug_trap
);
3235 add_unwind_protect (set_debug_trap
, debug_trap
);
3237 restore_default_signal (DEBUG_TRAP
);
3240 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3241 if (error_trap
&& error_trace_mode
== 0)
3245 error_trap
= savestring (error_trap
);
3246 add_unwind_protect (xfree
, error_trap
);
3247 add_unwind_protect (set_error_trap
, error_trap
);
3249 restore_default_signal (ERROR_TRAP
);
3252 /* Shell functions inherit the RETURN trap if function tracing is on
3253 globally or on individually for this function. */
3255 if (return_trap
&& ((trace_p (var
) == 0) && function_trace_mode
== 0))
3257 if (return_trap
&& (signal_in_progress (DEBUG_TRAP
) || ((trace_p (var
) == 0) && function_trace_mode
== 0)))
3262 return_trap
= savestring (return_trap
);
3263 add_unwind_protect (xfree
, return_trap
);
3264 add_unwind_protect (set_return_trap
, return_trap
);
3266 restore_default_signal (RETURN_TRAP
);
3270 #if defined (ARRAY_VARS)
3271 /* This is quite similar to the code in shell.c and elsewhere. */
3272 shell_fn
= find_function_def (this_shell_function
->name
);
3273 sfile
= shell_fn
? shell_fn
->source_file
: "";
3274 array_push (funcname_a
, this_shell_function
->name
);
3276 array_push (bash_source_a
, sfile
);
3277 t
= itos (executing_line_number ());
3278 array_push (bash_lineno_a
, t
);
3282 /* The temporary environment for a function is supposed to apply to
3283 all commands executed within the function body. */
3285 remember_args (words
->next
, 1);
3287 /* Update BASH_ARGV and BASH_ARGC */
3289 push_args (words
->next
);
3291 /* Number of the line on which the function body starts. */
3292 line_number
= function_line_number
= tc
->line
;
3294 #if defined (JOB_CONTROL)
3296 stop_pipeline (async
, (COMMAND
*)NULL
);
3301 return_catch_flag
++;
3302 return_val
= setjmp (return_catch
);
3306 result
= return_catch_value
;
3307 /* Run the RETURN trap in the function's context. */
3308 save_current
= currently_executing_command
;
3310 currently_executing_command
= save_current
;
3314 /* Run the debug trap here so we can trap at the start of a function's
3315 execution rather than the execution of the body's first command. */
3316 showing_function_line
= 1;
3317 save_current
= currently_executing_command
;
3318 result
= run_debug_trap ();
3319 #if defined (DEBUGGER)
3320 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3321 skip the command. */
3322 if (debugging_mode
== 0 || result
== EXECUTION_SUCCESS
)
3324 showing_function_line
= 0;
3325 currently_executing_command
= save_current
;
3326 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
3328 /* Run the RETURN trap in the function's context */
3329 save_current
= currently_executing_command
;
3331 currently_executing_command
= save_current
;
3334 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
3336 save_current
= currently_executing_command
;
3338 currently_executing_command
= save_current
;
3340 showing_function_line
= 0;
3343 /* Restore BASH_ARGC and BASH_ARGV */
3348 run_unwind_frame ("function_calling");
3351 #if defined (ARRAY_VARS)
3352 /* These two variables cannot be unset, and cannot be affected by the
3354 array_pop (bash_source_a
);
3355 array_pop (bash_lineno_a
);
3357 /* FUNCNAME can be unset, and so can potentially be changed by the
3359 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv
, funcname_a
);
3360 if (nfv
== funcname_v
)
3361 array_pop (funcname_a
);
3364 if (variable_context
== 0 || this_shell_function
== 0)
3365 make_funcname_visible (0);
3370 /* A convenience routine for use by other parts of the shell to execute
3371 a particular shell function. */
3373 execute_shell_function (var
, words
)
3378 struct fd_bitmap
*bitmap
;
3380 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
3381 begin_unwind_frame ("execute-shell-function");
3382 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
3384 ret
= execute_function (var
, words
, 0, bitmap
, 0, 0);
3386 dispose_fd_bitmap (bitmap
);
3387 discard_unwind_frame ("execute-shell-function");
3392 /* Execute a shell builtin or function in a subshell environment. This
3393 routine does not return; it only calls exit(). If BUILTIN is non-null,
3394 it points to a function to call to execute a shell builtin; otherwise
3395 VAR points at the body of a function to execute. WORDS is the arguments
3396 to the command, REDIRECTS specifies redirections to perform before the
3397 command is executed. */
3399 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
3400 pipe_in
, pipe_out
, async
, fds_to_close
,
3403 REDIRECT
*redirects
;
3404 sh_builtin_func_t
*builtin
;
3406 int pipe_in
, pipe_out
, async
;
3407 struct fd_bitmap
*fds_to_close
;
3410 int result
, r
, funcvalue
;
3411 #if defined (JOB_CONTROL)
3414 jobs_hack
= (builtin
== jobs_builtin
) &&
3415 ((subshell_environment
& SUBSHELL_ASYNC
) == 0 || pipe_out
!= NO_PIPE
);
3418 /* A subshell is neither a login shell nor interactive. */
3419 login_shell
= interactive
= 0;
3422 subshell_environment
|= SUBSHELL_ASYNC
;
3423 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
)
3424 subshell_environment
|= SUBSHELL_PIPE
;
3426 maybe_make_export_env (); /* XXX - is this needed? */
3428 #if defined (JOB_CONTROL)
3429 /* Eradicate all traces of job control after we fork the subshell, so
3430 all jobs begun by this subshell are in the same process group as
3431 the shell itself. */
3433 /* Allow the output of `jobs' to be piped. */
3435 kill_current_pipeline ();
3437 without_job_control ();
3439 set_sigchld_handler ();
3440 #endif /* JOB_CONTROL */
3442 set_sigint_handler ();
3445 close_fd_bitmap (fds_to_close
);
3447 do_piping (pipe_in
, pipe_out
);
3449 if (do_redirections (redirects
, RX_ACTIVE
) != 0)
3450 exit (EXECUTION_FAILURE
);
3454 /* Give builtins a place to jump back to on failure,
3455 so we don't go back up to main(). */
3456 result
= setjmp (top_level
);
3458 /* Give the return builtin a place to jump to when executed in a subshell
3461 if (return_catch_flag
&& builtin
== return_builtin
)
3462 funcvalue
= setjmp (return_catch
);
3464 if (result
== EXITPROG
)
3465 exit (last_command_exit_value
);
3467 exit (EXECUTION_FAILURE
);
3469 exit (return_catch_value
);
3472 r
= execute_builtin (builtin
, words
, flags
, 1);
3479 exit (execute_function (var
, words
, flags
, fds_to_close
, async
, 1));
3482 /* Execute a builtin or function in the current shell context. If BUILTIN
3483 is non-null, it is the builtin command to execute, otherwise VAR points
3484 to the body of a function. WORDS are the command's arguments, REDIRECTS
3485 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3486 file descriptors to close.
3488 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3489 not undone before this function returns. */
3491 execute_builtin_or_function (words
, builtin
, var
, redirects
,
3492 fds_to_close
, flags
)
3494 sh_builtin_func_t
*builtin
;
3496 REDIRECT
*redirects
;
3497 struct fd_bitmap
*fds_to_close
;
3501 REDIRECT
*saved_undo_list
;
3502 sh_builtin_func_t
*saved_this_shell_builtin
;
3504 if (do_redirections (redirects
, RX_ACTIVE
|RX_UNDOABLE
) != 0)
3506 cleanup_redirects (redirection_undo_list
);
3507 redirection_undo_list
= (REDIRECT
*)NULL
;
3508 dispose_exec_redirects ();
3509 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
3512 saved_this_shell_builtin
= this_shell_builtin
;
3513 saved_undo_list
= redirection_undo_list
;
3515 /* Calling the "exec" builtin changes redirections forever. */
3516 if (builtin
== exec_builtin
)
3518 dispose_redirects (saved_undo_list
);
3519 saved_undo_list
= exec_redirection_undo_list
;
3520 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
3523 dispose_exec_redirects ();
3525 if (saved_undo_list
)
3527 begin_unwind_frame ("saved redirects");
3528 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
3531 redirection_undo_list
= (REDIRECT
*)NULL
;
3534 result
= execute_builtin (builtin
, words
, flags
, 0);
3536 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
3538 /* We do this before undoing the effects of any redirections. */
3539 if (ferror (stdout
))
3542 /* If we are executing the `command' builtin, but this_shell_builtin is
3543 set to `exec_builtin', we know that we have something like
3544 `command exec [redirection]', since otherwise `exec' would have
3545 overwritten the shell and we wouldn't get here. In this case, we
3546 want to behave as if the `command' builtin had not been specified
3547 and preserve the redirections. */
3548 if (builtin
== command_builtin
&& this_shell_builtin
== exec_builtin
)
3550 if (saved_undo_list
)
3551 dispose_redirects (saved_undo_list
);
3552 redirection_undo_list
= exec_redirection_undo_list
;
3553 saved_undo_list
= exec_redirection_undo_list
= (REDIRECT
*)NULL
;
3554 discard_unwind_frame ("saved_redirects");
3557 if (saved_undo_list
)
3559 redirection_undo_list
= saved_undo_list
;
3560 discard_unwind_frame ("saved redirects");
3563 if (redirection_undo_list
)
3565 cleanup_redirects (redirection_undo_list
);
3566 redirection_undo_list
= (REDIRECT
*)NULL
;
3573 setup_async_signals ()
3575 #if defined (__BEOS__)
3576 set_signal_handler (SIGHUP
, SIG_IGN
); /* they want csh-like behavior */
3579 #if defined (JOB_CONTROL)
3580 if (job_control
== 0)
3583 set_signal_handler (SIGINT
, SIG_IGN
);
3584 set_signal_ignored (SIGINT
);
3585 set_signal_handler (SIGQUIT
, SIG_IGN
);
3586 set_signal_ignored (SIGQUIT
);
3590 /* Execute a simple command that is hopefully defined in a disk file
3595 3) look up the command
3598 6) If the execve failed, see if the file has executable mode set.
3599 If so, and it isn't a directory, then execute its contents as
3602 Note that the filename hashing stuff has to take place up here,
3603 in the parent. This is probably why the Bourne style shells
3604 don't handle it, since that would require them to go through
3605 this gnarly hair, for no good reason.
3607 NOTE: callers expect this to fork or exit(). */
3609 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
3610 async
, fds_to_close
, cmdflags
)
3612 REDIRECT
*redirects
;
3614 int pipe_in
, pipe_out
, async
;
3615 struct fd_bitmap
*fds_to_close
;
3618 char *pathname
, *command
, **args
;
3622 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
3623 pathname
= words
->word
->word
;
3625 #if defined (RESTRICTED_SHELL)
3626 command
= (char *)NULL
;
3627 if (restricted
&& xstrchr (pathname
, '/'))
3629 internal_error (_("%s: restricted: cannot specify `/' in command names"),
3631 last_command_exit_value
= EXECUTION_FAILURE
;
3633 /* If we're not going to fork below, we must already be in a child
3634 process or a context in which it's safe to call exit(2). */
3635 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
3636 exit (last_command_exit_value
);
3640 #endif /* RESTRICTED_SHELL */
3642 command
= search_for_command (pathname
);
3646 maybe_make_export_env ();
3647 put_command_name_into_env (command
);
3650 /* We have to make the child before we check for the non-existence
3651 of COMMAND, since we want the error messages to be redirected. */
3652 /* If we can get away without forking and there are no pipes to deal with,
3653 don't bother to fork, just directly exec the command. */
3654 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
3657 pid
= make_child (savestring (command_line
), async
);
3661 int old_interactive
;
3664 /* This has been disabled for the time being. */
3665 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3666 if (posixly_correct
== 0)
3667 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags
);
3671 /* Cancel traps, in trap.c. */
3672 restore_original_signals ();
3674 /* restore_original_signals may have undone the work done
3675 by make_child to ensure that SIGINT and SIGQUIT are ignored
3676 in asynchronous children. */
3679 if ((cmdflags
& CMD_STDIN_REDIR
) &&
3680 pipe_in
== NO_PIPE
&&
3681 (stdin_redirects (redirects
) == 0))
3682 async_redirect_stdin ();
3683 setup_async_signals ();
3686 /* This functionality is now provided by close-on-exec of the
3687 file descriptors manipulated by redirection and piping.
3688 Some file descriptors still need to be closed in all children
3689 because of the way bash does pipes; fds_to_close is a
3690 bitmap of all such file descriptors. */
3692 close_fd_bitmap (fds_to_close
);
3694 do_piping (pipe_in
, pipe_out
);
3696 old_interactive
= interactive
;
3700 subshell_environment
= SUBSHELL_FORK
;
3702 if (redirects
&& (do_redirections (redirects
, RX_ACTIVE
) != 0))
3704 #if defined (PROCESS_SUBSTITUTION)
3705 /* Try to remove named pipes that may have been created as the
3706 result of redirections. */
3707 unlink_fifo_list ();
3708 #endif /* PROCESS_SUBSTITUTION */
3709 exit (EXECUTION_FAILURE
);
3713 interactive
= old_interactive
;
3717 internal_error (_("%s: command not found"), pathname
);
3718 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
3721 /* Execve expects the command name to be in args[0]. So we
3722 leave it there, in the same format that the user used to
3724 args
= strvec_from_word_list (words
, 0, 0, (int *)NULL
);
3725 exit (shell_execve (command
, args
, export_env
));
3730 /* Make sure that the pipes are closed in the parent. */
3731 close_pipes (pipe_in
, pipe_out
);
3732 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3733 unlink_fifo_list ();
3739 /* CPP defines to decide whether a particular index into the #! line
3740 corresponds to a valid interpreter name or argument character, or
3741 whitespace. The MSDOS define is to allow \r to be treated the same
3744 #if !defined (MSDOS)
3745 # define STRINGCHAR(ind) \
3746 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3747 # define WHITECHAR(ind) \
3748 (ind < sample_len && whitespace (sample[ind]))
3750 # define STRINGCHAR(ind) \
3751 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3752 # define WHITECHAR(ind) \
3753 (ind < sample_len && whitespace (sample[ind]))
3757 getinterp (sample
, sample_len
, endp
)
3759 int sample_len
, *endp
;
3765 /* Find the name of the interpreter to exec. */
3766 for (i
= 2; i
< sample_len
&& whitespace (sample
[i
]); i
++)
3769 for (start
= i
; STRINGCHAR(i
); i
++)
3772 execname
= substring (sample
, start
, i
);
3779 #if !defined (HAVE_HASH_BANG_EXEC)
3780 /* If the operating system on which we're running does not handle
3781 the #! executable format, then help out. SAMPLE is the text read
3782 from the file, SAMPLE_LEN characters. COMMAND is the name of
3783 the script; it and ARGS, the arguments given by the user, will
3784 become arguments to the specified interpreter. ENV is the environment
3785 to pass to the interpreter.
3787 The word immediately following the #! is the interpreter to execute.
3788 A single argument to the interpreter is allowed. */
3791 execute_shell_script (sample
, sample_len
, command
, args
, env
)
3797 char *execname
, *firstarg
;
3798 int i
, start
, size_increment
, larry
;
3800 /* Find the name of the interpreter to exec. */
3801 execname
= getinterp (sample
, sample_len
, &i
);
3804 /* Now the argument, if any. */
3805 for (firstarg
= (char *)NULL
, start
= i
; WHITECHAR(i
); i
++)
3808 /* If there is more text on the line, then it is an argument for the
3813 for (start
= i
; STRINGCHAR(i
); i
++)
3815 firstarg
= substring ((char *)sample
, start
, i
);
3819 larry
= strvec_len (args
) + size_increment
;
3820 args
= strvec_resize (args
, larry
+ 1);
3822 for (i
= larry
- 1; i
; i
--)
3823 args
[i
] = args
[i
- size_increment
];
3834 args
[larry
] = (char *)NULL
;
3836 return (shell_execve (execname
, args
, env
));
3841 #endif /* !HAVE_HASH_BANG_EXEC */
3844 initialize_subshell ()
3847 /* Forget about any aliases that we knew of. We are in a subshell. */
3848 delete_all_aliases ();
3851 #if defined (HISTORY)
3852 /* Forget about the history lines we have read. This is a non-interactive
3854 history_lines_this_session
= 0;
3857 #if defined (JOB_CONTROL)
3858 /* Forget about the way job control was working. We are in a subshell. */
3859 without_job_control ();
3860 set_sigchld_handler ();
3862 #endif /* JOB_CONTROL */
3864 /* Reset the values of the shell flags and options. */
3865 reset_shell_flags ();
3866 reset_shell_options ();
3867 reset_shopt_options ();
3869 /* Zero out builtin_env, since this could be a shell script run from a
3870 sourced file with a temporary environment supplied to the `source/.'
3871 builtin. Such variables are not supposed to be exported (empirical
3872 testing with sh and ksh). Just throw it away; don't worry about a
3874 if (vc_isbltnenv (shell_variables
))
3875 shell_variables
= shell_variables
->down
;
3877 clear_unwind_protect_list (0);
3879 /* We're no longer inside a shell function. */
3880 variable_context
= return_catch_flag
= 0;
3882 /* If we're not interactive, close the file descriptor from which we're
3883 reading the current shell script. */
3884 if (interactive_shell
== 0)
3885 unset_bash_input (0);
3888 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3889 # define SETOSTYPE(x) __setostype(x)
3891 # define SETOSTYPE(x)
3894 #define READ_SAMPLE_BUF(file, buf, len) \
3897 fd = open(file, O_RDONLY); \
3900 len = read (fd, buf, 80); \
3908 /* Call execve (), handling interpreting shell scripts, and handling
3911 shell_execve (command
, args
, env
)
3920 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3921 execve (command
, args
, env
);
3922 i
= errno
; /* error from execve() */
3925 /* If we get to this point, then start checking out the file.
3926 Maybe it is something we can hack ourselves. */
3929 if ((stat (command
, &finfo
) == 0) && (S_ISDIR (finfo
.st_mode
)))
3930 internal_error (_("%s: is a directory"), command
);
3931 else if (executable_file (command
) == 0)
3934 file_error (command
);
3936 /* errors not involving the path argument to execve. */
3937 else if (i
== E2BIG
|| i
== ENOMEM
)
3940 file_error (command
);
3944 /* The file has the execute bits set, but the kernel refuses to
3945 run it for some reason. See why. */
3946 #if defined (HAVE_HASH_BANG_EXEC)
3947 READ_SAMPLE_BUF (command
, sample
, sample_len
);
3948 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
3953 interp
= getinterp (sample
, sample_len
, (int *)NULL
);
3954 ilen
= strlen (interp
);
3956 if (interp
[ilen
- 1] == '\r')
3958 interp
= xrealloc (interp
, ilen
+ 2);
3959 interp
[ilen
- 1] = '^';
3961 interp
[ilen
+ 1] = '\0';
3963 sys_error (_("%s: %s: bad interpreter"), command
, interp
? interp
: "");
3969 file_error (command
);
3971 return ((i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
); /* XXX Posix.2 says that exit status is 126 */
3974 /* This file is executable.
3975 If it begins with #!, then help out people with losing operating
3976 systems. Otherwise, check to see if it is a binary file by seeing
3977 if the contents of the first line (or up to 80 characters) are in the
3978 ASCII set. If it's a text file, execute the contents as shell commands,
3979 otherwise return 126 (EX_BINARY_FILE). */
3980 READ_SAMPLE_BUF (command
, sample
, sample_len
);
3982 if (sample_len
== 0)
3983 return (EXECUTION_SUCCESS
);
3985 /* Is this supposed to be an executable script?
3986 If so, the format of the line is "#! interpreter [argument]".
3987 A single argument is allowed. The BSD kernel restricts
3988 the length of the entire line to 32 characters (32 bytes
3989 being the size of the BSD exec header), but we allow 80
3993 #if !defined (HAVE_HASH_BANG_EXEC)
3994 if (sample_len
> 2 && sample
[0] == '#' && sample
[1] == '!')
3995 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
3998 if (check_binary_file (sample
, sample_len
))
4000 internal_error (_("%s: cannot execute binary file"), command
);
4001 return (EX_BINARY_FILE
);
4005 /* We have committed to attempting to execute the contents of this file
4006 as shell commands. */
4008 initialize_subshell ();
4010 set_sigint_handler ();
4012 /* Insert the name of this shell into the argument list. */
4013 larray
= strvec_len (args
) + 1;
4014 args
= strvec_resize (args
, larray
+ 1);
4016 for (i
= larray
- 1; i
; i
--)
4017 args
[i
] = args
[i
- 1];
4019 args
[0] = shell_name
;
4021 args
[larray
] = (char *)NULL
;
4023 if (args
[0][0] == '-')
4026 #if defined (RESTRICTED_SHELL)
4028 change_flag ('r', FLAG_OFF
);
4033 /* Can't free subshell_argv[0]; that is shell_name. */
4034 for (i
= 1; i
< subshell_argc
; i
++)
4035 free (subshell_argv
[i
]);
4036 free (subshell_argv
);
4039 dispose_command (currently_executing_command
); /* XXX */
4040 currently_executing_command
= (COMMAND
*)NULL
;
4042 subshell_argc
= larray
;
4043 subshell_argv
= args
;
4044 subshell_envp
= env
;
4046 unbind_args (); /* remove the positional parameters */
4048 longjmp (subshell_top_level
, 1);
4053 execute_intern_function (name
, function
)
4059 if (check_identifier (name
, posixly_correct
) == 0)
4061 if (posixly_correct
&& interactive_shell
== 0)
4063 last_command_exit_value
= EX_USAGE
;
4064 jump_to_top_level (ERREXIT
);
4066 return (EXECUTION_FAILURE
);
4069 var
= find_function (name
->word
);
4070 if (var
&& (readonly_p (var
) || noassign_p (var
)))
4072 if (readonly_p (var
))
4073 internal_error (_("%s: readonly function"), var
->name
);
4074 return (EXECUTION_FAILURE
);
4077 bind_function (name
->word
, function
);
4078 return (EXECUTION_SUCCESS
);
4081 #if defined (INCLUDE_UNUSED)
4082 #if defined (PROCESS_SUBSTITUTION)
4086 register int i
, fd_table_size
;
4088 fd_table_size
= getdtablesize ();
4089 if (fd_table_size
> 256) /* clamp to a reasonable value */
4090 fd_table_size
= 256;
4092 for (i
= 3; i
< fd_table_size
; i
++)
4095 #endif /* PROCESS_SUBSTITUTION */
4099 close_pipes (in
, out
)
4109 dup_error (oldd
, newd
)
4112 sys_error (_("cannot duplicate fd %d to fd %d"), oldd
, newd
);
4115 /* Redirect input and output to be from and to the specified pipes.
4116 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4118 do_piping (pipe_in
, pipe_out
)
4119 int pipe_in
, pipe_out
;
4121 if (pipe_in
!= NO_PIPE
)
4123 if (dup2 (pipe_in
, 0) < 0)
4124 dup_error (pipe_in
, 0);
4128 if (pipe_out
!= NO_PIPE
)
4130 if (pipe_out
!= REDIRECT_BOTH
)
4132 if (dup2 (pipe_out
, 1) < 0)
4133 dup_error (pipe_out
, 1);
4134 if (pipe_out
== 0 || pipe_out
> 1)
4139 if (dup2 (1, 2) < 0)