1 /* execute_command.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987,1991 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 1, 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, 675 Mass Ave, Cambridge, MA 02139, USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "bashtypes.h"
31 #include "posixstat.h"
33 #include <sys/param.h>
35 #if defined (HAVE_UNISTD_H)
39 #if defined (HAVE_LIMITS_H)
43 /* Some systems require this, mostly for the definition of `struct timezone'.
44 For example, Dynix/ptx has that definition in <time.h> rather than
46 #if defined (TIME_WITH_SYS_TIME)
47 # include <sys/time.h>
50 # if defined (HAVE_SYS_TIME_H)
51 # include <sys/time.h>
57 #if defined (HAVE_SYS_RESOURCE_H)
58 # include <sys/resource.h>
61 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
62 # include <sys/times.h>
75 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
80 #include "execute_cmd.h"
85 #include "builtins/common.h"
86 #include "builtins/builtext.h" /* list of builtins */
88 #include <glob/fnmatch.h>
89 #include <tilde/tilde.h>
91 #if defined (BUFFERED_INPUT)
100 # include "bashhist.h"
103 extern int posixly_correct
;
104 extern int executing
, breaking
, continuing
, loop_level
;
105 extern int interactive
, interactive_shell
, login_shell
, expand_aliases
;
106 extern int parse_and_execute_level
, running_trap
, trap_line_number
;
107 extern int command_string_index
, variable_context
, line_number
;
108 extern int dot_found_in_search
;
109 extern int already_making_children
;
110 extern char **temporary_env
, **function_env
, **builtin_env
;
111 extern char *the_printed_command
, *shell_name
;
112 extern pid_t last_command_subst_pid
;
113 extern Function
*last_shell_builtin
, *this_shell_builtin
;
114 extern char **subshell_argv
, **subshell_envp
;
115 extern int subshell_argc
;
116 extern char *glob_argv_flags
;
118 extern int getdtablesize ();
121 /* Static functions defined and used in this file. */
122 static void close_pipes (), do_piping (), bind_lastarg ();
123 static void cleanup_redirects ();
124 static void add_undo_close_redirect (), add_exec_redirect ();
125 static int add_undo_redirect ();
126 static int do_redirection_internal (), do_redirections ();
127 static int expandable_redirection_filename ();
128 static char *find_user_command_internal (), *find_user_command_in_path ();
129 static char *find_in_path_element (), *find_absolute_program ();
131 static int execute_for_command ();
132 #if defined (SELECT_COMMAND)
133 static int execute_select_command ();
135 #if defined (COMMAND_TIMING)
136 static int time_command ();
138 static int execute_case_command ();
139 static int execute_while_command (), execute_until_command ();
140 static int execute_while_or_until ();
141 static int execute_if_command ();
142 static int execute_simple_command ();
143 static int execute_builtin (), execute_function ();
144 static int execute_builtin_or_function ();
145 static int builtin_status ();
146 static void execute_subshell_builtin_or_function ();
147 static void execute_disk_command ();
148 static int execute_connection ();
149 static int execute_intern_function ();
151 /* The line number that the currently executing function starts on. */
152 static int function_line_number
;
154 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
155 so that reader_loop can set it to zero before executing a command. */
158 /* The name of the command that is currently being executed.
159 `test' needs this, for example. */
160 char *this_command_name
;
162 static COMMAND
*currently_executing_command
;
164 struct stat SB
; /* used for debugging */
166 static int special_builtin_failed
;
168 /* Spare redirector used when translating [N]>&WORD or [N]<&WORD to a new
169 redirection and when creating the redirection undo list. */
170 static REDIRECTEE rd
;
172 /* Set to errno when a here document cannot be created for some reason.
173 Used to print a reasonable error message. */
174 static int heredoc_errno
;
176 /* The file name which we would try to execute, except that it isn't
177 possible to execute it. This is the first file that matches the
178 name that we are looking for while we are searching $PATH for a
179 suitable one to execute. If we cannot find a suitable executable
180 file, then we use this one. */
181 static char *file_to_lose_on
;
183 /* For catching RETURN in a function. */
184 int return_catch_flag
;
185 int return_catch_value
;
186 procenv_t return_catch
;
188 /* The value returned by the last synchronous command. */
189 int last_command_exit_value
;
191 /* The list of redirections to perform which will undo the redirections
192 that I made in the shell. */
193 REDIRECT
*redirection_undo_list
= (REDIRECT
*)NULL
;
195 /* The list of redirections to perform which will undo the internal
196 redirections performed by the `exec' builtin. These are redirections
197 that must be undone even when exec discards redirection_undo_list. */
198 REDIRECT
*exec_redirection_undo_list
= (REDIRECT
*)NULL
;
200 /* Non-zero if we have just forked and are currently running in a subshell
202 int subshell_environment
;
204 /* Non-zero if we should stat every command found in the hash table to
205 make sure it still exists. */
206 int check_hashed_filenames
;
208 struct fd_bitmap
*current_fds_to_close
= (struct fd_bitmap
*)NULL
;
210 #define FD_BITMAP_DEFAULT_SIZE 32L
212 /* Functions to allocate and deallocate the structures used to pass
213 information from the shell to its children about file descriptors
219 struct fd_bitmap
*ret
;
221 ret
= (struct fd_bitmap
*)xmalloc (sizeof (struct fd_bitmap
));
227 ret
->bitmap
= xmalloc (size
);
228 bzero (ret
->bitmap
, size
);
231 ret
->bitmap
= (char *)NULL
;
236 dispose_fd_bitmap (fdbp
)
237 struct fd_bitmap
*fdbp
;
244 close_fd_bitmap (fdbp
)
245 struct fd_bitmap
*fdbp
;
251 for (i
= 0; i
< fdbp
->size
; i
++)
260 /* Return the line number of the currently executing command. */
262 executing_line_number ()
264 if (executing
&& variable_context
== 0 && currently_executing_command
&&
265 currently_executing_command
->type
== cm_simple
)
266 return currently_executing_command
->value
.Simple
->line
;
267 else if (running_trap
)
268 return trap_line_number
;
273 /* Execute the command passed in COMMAND. COMMAND is exactly what
274 read_command () places into GLOBAL_COMMAND. See "command.h" for the
275 details of the command structure.
277 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
278 return values. Executing a command with nothing in it returns
279 EXECUTION_SUCCESS. */
281 execute_command (command
)
284 struct fd_bitmap
*bitmap
;
287 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
288 bitmap
= new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE
);
289 begin_unwind_frame ("execute-command");
290 add_unwind_protect (dispose_fd_bitmap
, (char *)bitmap
);
292 /* Just do the command, but not asynchronously. */
293 result
= execute_command_internal (command
, 0, NO_PIPE
, NO_PIPE
, bitmap
);
295 dispose_fd_bitmap (bitmap
);
296 discard_unwind_frame ("execute-command");
298 #if defined (PROCESS_SUBSTITUTION)
300 #endif /* PROCESS_SUBSTITUTION */
305 /* Return 1 if TYPE is a shell control structure type. */
307 shell_control_structure (type
)
308 enum command_type type
;
313 #if defined (SELECT_COMMAND)
328 /* A function to use to unwind_protect the redirection undo list
331 cleanup_redirects (list
)
334 do_redirections (list
, 1, 0, 0);
335 dispose_redirects (list
);
339 /* Function to unwind_protect the redirections for functions and builtins. */
341 cleanup_func_redirects (list
)
344 do_redirections (list
, 1, 0, 0);
349 dispose_exec_redirects ()
351 if (exec_redirection_undo_list
)
353 dispose_redirects (exec_redirection_undo_list
);
354 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
358 #if defined (JOB_CONTROL)
359 /* A function to restore the signal mask to its proper value when the shell
360 is interrupted or errors occur while creating a pipeline. */
362 restore_signal_mask (set
)
365 return (sigprocmask (SIG_SETMASK
, &set
, (sigset_t
*)NULL
));
367 #endif /* JOB_CONTROL */
369 /* A debugging function that can be called from gdb, for instance. */
374 int f
, fd_table_size
;
376 fd_table_size
= getdtablesize ();
378 fprintf (stderr
, "pid %d open files:", (int)getpid ());
379 for (i
= 3; i
< fd_table_size
; i
++)
381 if ((f
= fcntl (i
, F_GETFD
, 0)) != -1)
382 fprintf (stderr
, " %d (%s)", i
, f
? "close" : "open");
384 fprintf (stderr
, "\n");
388 stdin_redirects (redirs
)
394 for (n
= 0, rp
= redirs
; rp
; rp
= rp
->next
)
395 switch (rp
->instruction
)
397 case r_input_direction
:
398 case r_inputa_direction
:
400 case r_reading_until
:
401 case r_deblank_reading_until
:
404 case r_duplicating_input
:
405 case r_duplicating_input_word
:
407 n
+= (rp
->redirector
== 0);
409 case r_output_direction
:
411 case r_duplicating_output
:
414 case r_duplicating_output_word
:
423 async_redirect_stdin ()
427 fd
= open ("/dev/null", O_RDONLY
);
434 internal_error ("cannot redirect standard input from /dev/null: %s", strerror (errno
));
437 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
439 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
440 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
441 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
442 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
443 from and where it goes. They can have the value of NO_PIPE, which means
445 FDS_TO_CLOSE is a list of file descriptors to close once the child has
446 been forked. This list often contains the unusable sides of pipes, etc.
448 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
449 return values. Executing a command with nothing in it returns
450 EXECUTION_SUCCESS. */
452 execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
,
456 int pipe_in
, pipe_out
;
457 struct fd_bitmap
*fds_to_close
;
459 int exec_result
, invert
, ignore_return
, was_debug_trap
;
460 REDIRECT
*my_undo_list
, *exec_undo_list
;
463 if (command
== 0 || breaking
|| continuing
|| read_but_dont_execute
)
464 return (EXECUTION_SUCCESS
);
466 run_pending_traps ();
468 if (running_trap
== 0)
469 currently_executing_command
= command
;
471 invert
= (command
->flags
& CMD_INVERT_RETURN
) != 0;
473 /* If we're inverting the return value and `set -e' has been executed,
474 we don't want a failing command to inadvertently cause the shell
476 if (exit_immediately_on_error
&& invert
) /* XXX */
477 command
->flags
|= CMD_IGNORE_RETURN
; /* XXX */
479 exec_result
= EXECUTION_SUCCESS
;
481 /* If a command was being explicitly run in a subshell, or if it is
482 a shell control-structure, and it has a pipe, then we do the command
485 if ((command
->flags
& (CMD_WANT_SUBSHELL
|CMD_FORCE_SUBSHELL
)) ||
486 (shell_control_structure (command
->type
) &&
487 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
|| asynchronous
)))
491 /* Fork a subshell, turn off the subshell bit, turn off job
492 control and call execute_command () on the command again. */
493 paren_pid
= make_child (savestring (make_command_string (command
)),
497 int user_subshell
, return_code
, function_value
, should_redir_stdin
;
499 should_redir_stdin
= (asynchronous
&& (command
->flags
& CMD_STDIN_REDIR
) &&
500 pipe_in
== NO_PIPE
&&
501 stdin_redirects (command
->redirects
) == 0);
503 user_subshell
= (command
->flags
& CMD_WANT_SUBSHELL
) != 0;
504 command
->flags
&= ~(CMD_FORCE_SUBSHELL
| CMD_WANT_SUBSHELL
| CMD_INVERT_RETURN
);
506 /* If a command is asynchronous in a subshell (like ( foo ) & or
507 the special case of an asynchronous GROUP command where the
508 the subshell bit is turned on down in case cm_group: below),
509 turn off `asynchronous', so that two subshells aren't spawned.
511 This seems semantically correct to me. For example,
512 ( foo ) & seems to say ``do the command `foo' in a subshell
513 environment, but don't wait for that subshell to finish'',
514 and "{ foo ; bar } &" seems to me to be like functions or
515 builtins in the background, which executed in a subshell
516 environment. I just don't see the need to fork two subshells. */
518 /* Don't fork again, we are already in a subshell. A `doubly
519 async' shell is not interactive, however. */
522 #if defined (JOB_CONTROL)
523 /* If a construct like ( exec xxx yyy ) & is given while job
524 control is active, we want to prevent exec from putting the
525 subshell back into the original process group, carefully
526 undoing all the work we just did in make_child. */
528 #endif /* JOB_CONTROL */
529 interactive_shell
= 0;
534 /* Subshells are neither login nor interactive. */
535 login_shell
= interactive
= 0;
537 subshell_environment
= user_subshell
? SUBSHELL_PAREN
: SUBSHELL_ASYNC
;
539 reset_terminating_signals (); /* in shell.c */
540 /* Cancel traps, in trap.c. */
541 restore_original_signals ();
543 setup_async_signals ();
545 #if defined (JOB_CONTROL)
546 set_sigchld_handler ();
547 #endif /* JOB_CONTROL */
549 set_sigint_handler ();
551 #if defined (JOB_CONTROL)
552 /* Delete all traces that there were any jobs running. This is
553 only for subshells. */
554 without_job_control ();
555 #endif /* JOB_CONTROL */
556 do_piping (pipe_in
, pipe_out
);
558 /* If this is a user subshell, set a flag if stdin was redirected.
559 This is used later to decide whether to redirect fd 0 to
560 /dev/null for async commands in the subshell. This adds more
561 sh compatibility, but I'm not sure it's the right thing to do. */
564 stdin_redir
= stdin_redirects (command
->redirects
);
565 restore_default_signal (0);
569 close_fd_bitmap (fds_to_close
);
571 /* If this is an asynchronous command (command &), we want to
572 redirect the standard input from /dev/null in the absence of
573 any specific redirection involving stdin. */
574 if (should_redir_stdin
&& stdin_redir
== 0)
575 async_redirect_stdin ();
577 /* Do redirections, then dispose of them before recursive call. */
578 if (command
->redirects
)
580 if (do_redirections (command
->redirects
, 1, 0, 0) != 0)
581 exit (EXECUTION_FAILURE
);
583 dispose_redirects (command
->redirects
);
584 command
->redirects
= (REDIRECT
*)NULL
;
587 /* If this is a simple command, tell execute_disk_command that it
588 might be able to get away without forking and simply exec.
589 This means things like ( sleep 10 ) will only cause one fork. */
590 if (user_subshell
&& command
->type
== cm_simple
)
592 command
->flags
|= CMD_NO_FORK
;
593 command
->value
.Simple
->flags
|= CMD_NO_FORK
;
596 /* If we're inside a function while executing this subshell, we
597 need to handle a possible `return'. */
599 if (return_catch_flag
)
600 function_value
= setjmp (return_catch
);
603 return_code
= return_catch_value
;
605 return_code
= execute_command_internal
606 (command
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
608 /* If we were explicitly placed in a subshell with (), we need
609 to do the `shell cleanup' things, such as running traps[0]. */
610 if (user_subshell
&& signal_is_trapped (0))
612 last_command_exit_value
= return_code
;
613 return_code
= run_exit_trap ();
620 close_pipes (pipe_in
, pipe_out
);
622 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
625 /* If we are part of a pipeline, and not the end of the pipeline,
626 then we should simply return and let the last command in the
627 pipe be waited for. If we are not in a pipeline, or are the
628 last command in the pipeline, then we wait for the subshell
629 and return its exit status as usual. */
630 if (pipe_out
!= NO_PIPE
)
631 return (EXECUTION_SUCCESS
);
633 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
635 if (asynchronous
== 0)
637 last_command_exit_value
= wait_for (paren_pid
);
639 /* If we have to, invert the return value. */
641 return ((last_command_exit_value
== EXECUTION_SUCCESS
)
643 : EXECUTION_SUCCESS
);
645 return (last_command_exit_value
);
649 DESCRIBE_PID (paren_pid
);
651 run_pending_traps ();
653 return (EXECUTION_SUCCESS
);
658 #if defined (COMMAND_TIMING)
659 if (command
->flags
& CMD_TIME_PIPELINE
)
663 command
->flags
|= CMD_FORCE_SUBSHELL
;
664 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
668 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
669 if (running_trap
== 0)
670 currently_executing_command
= (COMMAND
*)NULL
;
672 return (exec_result
);
674 #endif /* COMMAND_TIMING */
676 if (shell_control_structure (command
->type
) && command
->redirects
)
677 stdin_redir
= stdin_redirects (command
->redirects
);
679 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
681 if (do_redirections (command
->redirects
, 1, 1, 0) != 0)
683 cleanup_redirects (redirection_undo_list
);
684 redirection_undo_list
= (REDIRECT
*)NULL
;
685 dispose_exec_redirects ();
686 return (EXECUTION_FAILURE
);
689 if (redirection_undo_list
)
691 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
692 dispose_redirects (redirection_undo_list
);
693 redirection_undo_list
= (REDIRECT
*)NULL
;
696 my_undo_list
= (REDIRECT
*)NULL
;
698 if (exec_redirection_undo_list
)
700 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
701 dispose_redirects (exec_redirection_undo_list
);
702 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
705 exec_undo_list
= (REDIRECT
*)NULL
;
707 if (my_undo_list
|| exec_undo_list
)
708 begin_unwind_frame ("loop_redirections");
711 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
714 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
716 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
720 switch (command
->type
)
724 /* We can't rely on this variable retaining its value across a
725 call to execute_simple_command if a longjmp occurs as the
726 result of a `return' builtin. This is true for sure with gcc. */
727 last_pid
= last_made_pid
;
728 was_debug_trap
= signal_is_trapped (DEBUG_TRAP
) && signal_is_ignored (DEBUG_TRAP
) == 0;
730 if (ignore_return
&& command
->value
.Simple
)
731 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
732 if (command
->flags
& CMD_STDIN_REDIR
)
733 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
735 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
736 asynchronous
, fds_to_close
);
738 /* The temporary environment should be used for only the simple
739 command immediately following its definition. */
740 dispose_used_env_vars ();
742 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
743 /* Reclaim memory allocated with alloca () on machines which
744 may be using the alloca emulation code. */
746 #endif /* (ultrix && mips) || C_ALLOCA */
748 /* If we forked to do the command, then we must wait_for ()
751 /* XXX - this is something to watch out for if there are problems
752 when the shell is compiled without job control. */
753 if (already_making_children
&& pipe_out
== NO_PIPE
&&
754 last_pid
!= last_made_pid
)
756 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
760 DESCRIBE_PID (last_made_pid
);
763 #if !defined (JOB_CONTROL)
764 /* Do not wait for asynchronous processes started from
766 if (last_made_pid
!= last_asynchronous_pid
)
768 /* When executing a shell function that executes other
769 commands, this causes the last simple command in
770 the function to be waited for twice. */
771 exec_result
= wait_for (last_made_pid
);
778 if (ignore_return
== 0 && invert
== 0 &&
779 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
780 (exit_immediately_on_error
&& (exec_result
!= EXECUTION_SUCCESS
))))
782 last_command_exit_value
= exec_result
;
783 run_pending_traps ();
784 jump_to_top_level (EXITPROG
);
791 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
792 exec_result
= execute_for_command (command
->value
.For
);
795 #if defined (SELECT_COMMAND)
798 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
799 exec_result
= execute_select_command (command
->value
.Select
);
805 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
806 exec_result
= execute_case_command (command
->value
.Case
);
811 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
812 exec_result
= execute_while_command (command
->value
.While
);
817 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
818 exec_result
= execute_until_command (command
->value
.While
);
823 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
824 exec_result
= execute_if_command (command
->value
.If
);
829 /* This code can be executed from either of two paths: an explicit
830 '{}' command, or via a function call. If we are executed via a
831 function call, we have already taken care of the function being
832 executed in the background (down there in execute_simple_command ()),
833 and this command should *not* be marked as asynchronous. If we
834 are executing a regular '{}' group command, and asynchronous == 1,
835 we must want to execute the whole command in the background, so we
836 need a subshell, and we want the stuff executed in that subshell
837 (this group command) to be executed in the foreground of that
838 subshell (i.e. there will not be *another* subshell forked).
840 What we do is to force a subshell if asynchronous, and then call
841 execute_command_internal again with asynchronous still set to 1,
842 but with the original group command, so the printed command will
845 The code above that handles forking off subshells will note that
846 both subshell and async are on, and turn off async in the child
847 after forking the subshell (but leave async set in the parent, so
848 the normal call to describe_pid is made). This turning off
849 async is *crucial*; if it is not done, this will fall into an
850 infinite loop of executions through this spot in subshell after
851 subshell until the process limit is exhausted. */
855 command
->flags
|= CMD_FORCE_SUBSHELL
;
857 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
862 if (ignore_return
&& command
->value
.Group
->command
)
863 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
865 execute_command_internal (command
->value
.Group
->command
,
866 asynchronous
, pipe_in
, pipe_out
,
872 exec_result
= execute_connection (command
, asynchronous
,
873 pipe_in
, pipe_out
, fds_to_close
);
876 case cm_function_def
:
877 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
878 command
->value
.Function_def
->command
);
883 ("execute_command: bad command type `%d'", command
->type
);
888 do_redirections (my_undo_list
, 1, 0, 0);
889 dispose_redirects (my_undo_list
);
893 dispose_redirects (exec_undo_list
);
895 if (my_undo_list
|| exec_undo_list
)
896 discard_unwind_frame ("loop_redirections");
898 /* Invert the return value if we have to */
900 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
904 last_command_exit_value
= exec_result
;
905 run_pending_traps ();
906 if (running_trap
== 0)
907 currently_executing_command
= (COMMAND
*)NULL
;
908 return (last_command_exit_value
);
911 #if defined (COMMAND_TIMING)
912 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
913 static struct timeval
*
914 difftimeval (d
, t1
, t2
)
915 struct timeval
*d
, *t1
, *t2
;
917 d
->tv_sec
= t2
->tv_sec
- t1
->tv_sec
;
918 d
->tv_usec
= t2
->tv_usec
- t1
->tv_usec
;
921 d
->tv_usec
+= 1000000;
923 if (d
->tv_sec
< 0) /* ??? -- BSD/OS does this */
929 static struct timeval
*
930 addtimeval (d
, t1
, t2
)
931 struct timeval
*d
, *t1
, *t2
;
933 d
->tv_sec
= t1
->tv_sec
+ t2
->tv_sec
;
934 d
->tv_usec
= t1
->tv_usec
+ t2
->tv_usec
;
935 if (d
->tv_usec
> 1000000)
937 d
->tv_usec
-= 1000000;
943 /* Do "cpu = ((user + sys) * 10000) / real;" with timevals.
944 Barely-tested code from Deven T. Corzine <deven@ties.org>. */
946 timeval_to_cpu (rt
, ut
, st
)
947 struct timeval
*rt
, *ut
, *st
; /* real, user, sys */
949 struct timeval t1
, t2
;
952 addtimeval (&t1
, ut
, st
);
953 t2
.tv_sec
= rt
->tv_sec
;
954 t2
.tv_usec
= rt
->tv_usec
;
956 for (i
= 0; i
< 6; i
++)
958 if ((t1
.tv_sec
> 99999999) || (t2
.tv_sec
> 99999999))
961 t1
.tv_sec
+= t1
.tv_usec
/ 100000;
963 t1
.tv_usec
%= 1000000;
965 t2
.tv_sec
+= t2
.tv_usec
/ 100000;
967 t2
.tv_usec
%= 1000000;
969 for (i
= 0; i
< 4; i
++)
971 if (t1
.tv_sec
< 100000000)
977 return ((t2
.tv_sec
== 0) ? 0 : t1
.tv_sec
/ t2
.tv_sec
);
979 #endif /* HAVE_GETRUSAGE && HAVE_GETTIMEOFDAY */
981 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
982 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
984 static int precs
[] = { 0, 100, 10, 1 };
986 /* Expand one `%'-prefixed escape sequence from a time format string. */
988 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
1001 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1008 abuf
[aind
--] = (min
% 10) + '0';
1012 buf
[ind
++] = abuf
[aind
++];
1016 /* Now add the seconds. */
1019 abuf
[aind
--] = (sec
% 10) + '0';
1023 buf
[ind
++] = abuf
[aind
++];
1025 /* We want to add a decimal point and PREC places after it if PREC is
1026 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1031 for (aind
= 1; aind
<= prec
; aind
++)
1033 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
1034 sec_fraction
%= precs
[aind
];
1045 /* Interpret the format string FORMAT, interpolating the following escape
1049 where the optional `prec' is a precision, meaning the number of
1050 characters after the decimal point, the optional `l' means to format
1051 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1052 and the last character is one of
1054 R number of seconds of `real' time
1055 U number of seconds of `user' time
1056 S number of seconds of `system' time
1058 An occurrence of `%%' in the format string is translated to a `%'. The
1059 result is printed to FP, a pointer to a FILE. The other variables are
1060 the seconds and thousandths of a second of real, user, and system time,
1063 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1067 int rsf
, usf
, ssf
, cpu
;
1070 char *str
, *s
, ts
[32];
1074 len
= strlen (format
);
1075 ssize
= (len
+ 64) - (len
% 64);
1076 str
= xmalloc (ssize
);
1079 for (s
= format
; *s
; s
++)
1081 if (*s
!= '%' || s
[1] == '\0')
1083 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1086 else if (s
[1] == '%')
1089 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1092 else if (s
[1] == 'P')
1098 sum_frac
= (cpu
% 100) * 10;
1099 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1100 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1101 strcpy (str
+ sindex
, ts
);
1106 prec
= 3; /* default is three places past the decimal point. */
1107 lng
= 0; /* default is to not use minutes or append `s' */
1109 if (isdigit (*s
)) /* `precision' */
1112 if (prec
> 3) prec
= 3;
1114 if (*s
== 'l') /* `length extender' */
1119 if (*s
== 'R' || *s
== 'E')
1120 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1122 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1124 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1127 internal_error ("bad format character in time format: %c", *s
);
1131 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1132 strcpy (str
+ sindex
, ts
);
1138 fprintf (fp
, "%s\n", str
);
1145 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1147 int asynchronous
, pipe_in
, pipe_out
;
1148 struct fd_bitmap
*fds_to_close
;
1150 int rv
, posix_time
, old_flags
;
1156 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1157 struct timeval real
, user
, sys
;
1158 struct timeval before
, after
;
1159 struct timezone dtz
;
1160 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1162 # if defined (HAVE_TIMES)
1163 clock_t tbefore
, tafter
, real
, user
, sys
;
1164 struct tms before
, after
;
1168 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1169 gettimeofday (&before
, &dtz
);
1170 getrusage (RUSAGE_SELF
, &selfb
);
1171 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1173 # if defined (HAVE_TIMES)
1174 tbefore
= times (&before
);
1178 posix_time
= (command
->flags
& CMD_TIME_POSIX
);
1180 old_flags
= command
->flags
;
1181 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1182 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1183 command
->flags
= old_flags
;
1185 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1186 gettimeofday (&after
, &dtz
);
1187 getrusage (RUSAGE_SELF
, &selfa
);
1188 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1190 difftimeval (&real
, &before
, &after
);
1191 timeval_to_secs (&real
, &rs
, &rsf
);
1193 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1194 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1195 timeval_to_secs (&user
, &us
, &usf
);
1197 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1198 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1199 timeval_to_secs (&sys
, &ss
, &ssf
);
1201 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1203 # if defined (HAVE_TIMES)
1204 tafter
= times (&after
);
1206 real
= tafter
- tbefore
;
1207 clock_t_to_secs (real
, &rs
, &rsf
);
1209 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1210 clock_t_to_secs (user
, &us
, &usf
);
1212 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1213 clock_t_to_secs (sys
, &ss
, &ssf
);
1215 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1219 rsf
= usf
= ssf
= cpu
= 0;
1224 time_format
= POSIX_TIMEFORMAT
;
1225 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1226 time_format
= BASH_TIMEFORMAT
;
1228 if (time_format
&& *time_format
)
1229 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1233 #endif /* COMMAND_TIMING */
1236 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1238 int asynchronous
, pipe_in
, pipe_out
;
1239 struct fd_bitmap
*fds_to_close
;
1241 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
1243 struct fd_bitmap
*fd_bitmap
;
1245 #if defined (JOB_CONTROL)
1247 BLOCK_CHILD (set
, oset
);
1248 #endif /* JOB_CONTROL */
1250 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1255 while (cmd
&& cmd
->type
== cm_connection
&&
1256 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
1258 /* Make a pipeline between the two commands. */
1259 if (pipe (fildes
) < 0)
1261 sys_error ("pipe error");
1262 #if defined (JOB_CONTROL)
1263 terminate_current_pipeline ();
1264 kill_current_pipeline ();
1265 #endif /* JOB_CONTROL */
1266 last_command_exit_value
= EXECUTION_FAILURE
;
1267 /* The unwind-protects installed below will take care
1268 of closing all of the open file descriptors. */
1269 throw_to_top_level ();
1270 return (EXECUTION_FAILURE
); /* XXX */
1273 /* Here is a problem: with the new file close-on-exec
1274 code, the read end of the pipe (fildes[0]) stays open
1275 in the first process, so that process will never get a
1276 SIGPIPE. There is no way to signal the first process
1277 that it should close fildes[0] after forking, so it
1278 remains open. No SIGPIPE is ever sent because there
1279 is still a file descriptor open for reading connected
1280 to the pipe. We take care of that here. This passes
1281 around a bitmap of file descriptors that must be
1282 closed after making a child process in execute_simple_command. */
1284 /* We need fd_bitmap to be at least as big as fildes[0].
1285 If fildes[0] is less than fds_to_close->size, then
1286 use fds_to_close->size. */
1287 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
1288 ? fds_to_close
->size
1291 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
1293 /* Now copy the old information into the new bitmap. */
1294 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
1296 /* And mark the pipe file descriptors to be closed. */
1297 fd_bitmap
->bitmap
[fildes
[0]] = 1;
1299 /* In case there are pipe or out-of-processes errors, we
1300 want all these file descriptors to be closed when
1301 unwind-protects are run, and the storage used for the
1302 bitmaps freed up. */
1303 begin_unwind_frame ("pipe-file-descriptors");
1304 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
1305 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
1307 add_unwind_protect (close
, prev
);
1308 dummyfd
= fildes
[1];
1309 add_unwind_protect (close
, dummyfd
);
1311 #if defined (JOB_CONTROL)
1312 add_unwind_protect (restore_signal_mask
, oset
);
1313 #endif /* JOB_CONTROL */
1315 if (ignore_return
&& cmd
->value
.Connection
->first
)
1316 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1317 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
1318 prev
, fildes
[1], fd_bitmap
);
1326 dispose_fd_bitmap (fd_bitmap
);
1327 discard_unwind_frame ("pipe-file-descriptors");
1329 cmd
= cmd
->value
.Connection
->second
;
1332 /* Now execute the rightmost command in the pipeline. */
1333 if (ignore_return
&& cmd
)
1334 cmd
->flags
|= CMD_IGNORE_RETURN
;
1335 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
1340 #if defined (JOB_CONTROL)
1341 UNBLOCK_CHILD (oset
);
1344 return (exec_result
);
1348 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1350 int asynchronous
, pipe_in
, pipe_out
;
1351 struct fd_bitmap
*fds_to_close
;
1357 COMMAND
*tc
, *second
;
1358 int ignore_return
, exec_result
;
1360 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1362 switch (command
->value
.Connection
->connector
)
1364 /* Do the first command asynchronously. */
1366 tc
= command
->value
.Connection
->first
;
1368 return (EXECUTION_SUCCESS
);
1373 tc
->flags
|= CMD_IGNORE_RETURN
;
1374 tc
->flags
|= CMD_AMPERSAND
;
1376 /* If this shell was compiled without job control support, if
1377 the shell is not running interactively, if we are currently
1378 in a subshell via `( xxx )', or if job control is not active
1379 then the standard input for an asynchronous command is
1380 forced to /dev/null. */
1381 #if defined (JOB_CONTROL)
1382 if ((!interactive_shell
|| subshell_environment
|| !job_control
) && !stdin_redir
)
1385 #endif /* JOB_CONTROL */
1388 rd
.filename
= make_bare_word ("/dev/null");
1389 tr
= make_redirection (0, r_inputa_direction
, rd
);
1390 tr
->next
= tc
->redirects
;
1393 tc
->flags
|= CMD_STDIN_REDIR
;
1396 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
1398 if (tc
->flags
& CMD_STDIN_REDIR
)
1401 /* Remove the redirection we added above. It matters,
1402 especially for loops, which call execute_command ()
1403 multiple times with the same command. */
1408 tc
->redirects
= tc
->redirects
->next
;
1410 while (tc
->redirects
&& tc
->redirects
!= rp
);
1412 tl
->next
= (REDIRECT
*)NULL
;
1413 dispose_redirects (tr
);
1415 tc
->flags
&= ~CMD_STDIN_REDIR
;
1418 second
= command
->value
.Connection
->second
;
1422 second
->flags
|= CMD_IGNORE_RETURN
;
1424 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1429 /* Just call execute command on both sides. */
1433 if (command
->value
.Connection
->first
)
1434 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1435 if (command
->value
.Connection
->second
)
1436 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
1439 execute_command (command
->value
.Connection
->first
);
1441 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
1442 asynchronous
, pipe_in
, pipe_out
,
1447 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1454 /* If we have something like `a && b &' or `a || b &', run the
1455 && or || stuff in a subshell. Force a subshell and just call
1456 execute_command_internal again. Leave asynchronous on
1457 so that we get a report from the parent shell about the
1459 command
->flags
|= CMD_FORCE_SUBSHELL
;
1460 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
1464 /* Execute the first command. If the result of that is successful
1465 and the connector is AND_AND, or the result is not successful
1466 and the connector is OR_OR, then execute the second command,
1467 otherwise return. */
1469 if (command
->value
.Connection
->first
)
1470 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1472 exec_result
= execute_command (command
->value
.Connection
->first
);
1474 if (((command
->value
.Connection
->connector
== AND_AND
) &&
1475 (exec_result
== EXECUTION_SUCCESS
)) ||
1476 ((command
->value
.Connection
->connector
== OR_OR
) &&
1477 (exec_result
!= EXECUTION_SUCCESS
)))
1479 if (ignore_return
&& command
->value
.Connection
->second
)
1480 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
1482 exec_result
= execute_command (command
->value
.Connection
->second
);
1487 programming_error ("execute_connection: bad connector `%d'", command
->value
.Connection
->connector
);
1488 jump_to_top_level (DISCARD
);
1489 exec_result
= EXECUTION_FAILURE
;
1495 #if defined (JOB_CONTROL)
1499 if (!interactive_shell) \
1500 reap_dead_jobs (); \
1503 #else /* !JOB_CONTROL */
1507 if (!interactive_shell) \
1508 cleanup_dead_jobs (); \
1511 #endif /* !JOB_CONTROL */
1514 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1517 execute_for_command (for_command
)
1518 FOR_COM
*for_command
;
1520 register WORD_LIST
*releaser
, *list
;
1525 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
1528 if (check_identifier (for_command
->name
, 1) == 0)
1530 if (posixly_correct
&& interactive_shell
== 0)
1532 last_command_exit_value
= EX_USAGE
;
1533 jump_to_top_level (EXITPROG
);
1535 return (EXECUTION_FAILURE
);
1539 identifier
= for_command
->name
->word
;
1541 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
1543 begin_unwind_frame ("for");
1544 add_unwind_protect (dispose_words
, releaser
);
1547 if (lexical_scoping
)
1549 old_value
= copy_variable (find_variable (identifier
));
1551 add_unwind_protect (dispose_variable
, old_value
);
1555 if (for_command
->flags
& CMD_IGNORE_RETURN
)
1556 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
1558 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
1561 this_command_name
= (char *)NULL
;
1562 v
= bind_variable (identifier
, list
->word
->word
);
1565 if (interactive_shell
== 0 && posixly_correct
)
1567 last_command_exit_value
= EXECUTION_FAILURE
;
1568 jump_to_top_level (FORCE_EOF
);
1572 run_unwind_frame ("for");
1574 return (EXECUTION_FAILURE
);
1577 retval
= execute_command (for_command
->action
);
1598 if (lexical_scoping
)
1601 makunbound (identifier
, shell_variables
);
1604 SHELL_VAR
*new_value
;
1606 new_value
= bind_variable (identifier
, value_cell(old_value
));
1607 new_value
->attributes
= old_value
->attributes
;
1608 dispose_variable (old_value
);
1613 dispose_words (releaser
);
1614 discard_unwind_frame ("for");
1618 #if defined (SELECT_COMMAND)
1619 static int LINES
, COLS
, tabsize
;
1621 #define RP_SPACE ") "
1622 #define RP_SPACE_LEN 2
1624 /* XXX - does not handle numbers > 1000000 at all. */
1625 #define NUMBER_LEN(s) \
1629 : ((s < 10000) ? 4 \
1630 : ((s < 100000) ? 5 \
1634 print_index_and_element (len
, ind
, list
)
1638 register WORD_LIST
*l
;
1643 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
1645 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
1646 return (STRLEN (l
->word
->word
));
1655 if ((to
/ tabsize
) > (from
/ tabsize
))
1657 putc ('\t', stderr
);
1658 from
+= tabsize
- from
% tabsize
;
1669 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
1671 int list_len
, max_elem_len
, indices_len
;
1673 int ind
, row
, elem_len
, pos
, cols
, rows
;
1674 int first_column_indices_len
, other_indices_len
;
1678 putc ('\n', stderr
);
1682 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
1685 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
1686 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
1694 first_column_indices_len
= NUMBER_LEN (rows
);
1695 other_indices_len
= indices_len
;
1697 for (row
= 0; row
< rows
; row
++)
1703 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
1704 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
1705 elem_len
+= indices_len
+ RP_SPACE_LEN
;
1707 if (ind
>= list_len
)
1709 indent (pos
+ elem_len
, pos
+ max_elem_len
);
1710 pos
+= max_elem_len
;
1712 putc ('\n', stderr
);
1716 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1717 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1718 If the number is between 1 and LIST_LEN, return that selection. If EOF
1719 is read, return a null string. If a blank line is entered, the loop is
1722 select_query (list
, list_len
, prompt
)
1727 int max_elem_len
, indices_len
, len
, reply
;
1729 char *repl_string
, *t
;
1731 t
= get_string_value ("LINES");
1732 LINES
= (t
&& *t
) ? atoi (t
) : 24;
1733 t
= get_string_value ("COLUMNS");
1734 COLS
= (t
&& *t
) ? atoi (t
) : 80;
1737 t
= get_string_value ("TABSIZE");
1738 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
1746 for (l
= list
; l
; l
= l
->next
)
1748 len
= STRLEN (l
->word
->word
);
1749 if (len
> max_elem_len
)
1752 indices_len
= NUMBER_LEN (list_len
);
1753 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
1757 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
1758 fprintf (stderr
, "%s", prompt
);
1762 if (read_builtin ((WORD_LIST
*)NULL
) == EXECUTION_FAILURE
)
1765 return ((char *)NULL
);
1767 repl_string
= get_string_value ("REPLY");
1768 if (*repl_string
== 0)
1770 reply
= atoi (repl_string
);
1771 if (reply
< 1 || reply
> list_len
)
1774 for (l
= list
; l
&& --reply
; l
= l
->next
)
1776 return (l
->word
->word
);
1780 /* Execute a SELECT command. The syntax is:
1781 SELECT word IN list DO command_list DONE
1782 Only `break' or `return' in command_list will terminate
1785 execute_select_command (select_command
)
1786 SELECT_COM
*select_command
;
1788 WORD_LIST
*releaser
, *list
;
1790 char *identifier
, *ps3_prompt
, *selection
;
1791 int retval
, list_len
, return_val
;
1793 if (check_identifier (select_command
->name
, 1) == 0)
1794 return (EXECUTION_FAILURE
);
1797 identifier
= select_command
->name
->word
;
1799 /* command and arithmetic substitution, parameter and variable expansion,
1800 word splitting, pathname expansion, and quote removal. */
1801 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
1802 list_len
= list_length (list
);
1803 if (list
== 0 || list_len
== 0)
1806 dispose_words (list
);
1807 return (EXECUTION_SUCCESS
);
1810 begin_unwind_frame ("select");
1811 add_unwind_protect (dispose_words
, releaser
);
1813 if (select_command
->flags
& CMD_IGNORE_RETURN
)
1814 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
1816 retval
= EXECUTION_SUCCESS
;
1818 unwind_protect_int (return_catch_flag
);
1819 unwind_protect_jmp_buf (return_catch
);
1820 return_catch_flag
++;
1824 ps3_prompt
= get_string_value ("PS3");
1825 if (ps3_prompt
== 0)
1829 selection
= select_query (list
, list_len
, ps3_prompt
);
1834 v
= bind_variable (identifier
, selection
);
1837 if (interactive_shell
== 0 && posixly_correct
)
1839 last_command_exit_value
= EXECUTION_FAILURE
;
1840 jump_to_top_level (FORCE_EOF
);
1844 run_unwind_frame ("select");
1845 return (EXECUTION_FAILURE
);
1849 return_val
= setjmp (return_catch
);
1853 retval
= return_catch_value
;
1857 retval
= execute_command (select_command
->action
);
1871 run_unwind_frame ("select");
1874 #endif /* SELECT_COMMAND */
1876 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1877 The pattern_list is a linked list of pattern clauses; each clause contains
1878 some patterns to compare word_desc against, and an associated command to
1881 execute_case_command (case_command
)
1882 CASE_COM
*case_command
;
1884 register WORD_LIST
*list
;
1885 WORD_LIST
*wlist
, *es
;
1886 PATTERN_LIST
*clauses
;
1887 char *word
, *pattern
;
1888 int retval
, match
, ignore_return
;
1890 /* Posix.2 specifies that the WORD is tilde expanded. */
1891 if (member ('~', case_command
->word
->word
))
1893 word
= bash_tilde_expand (case_command
->word
->word
);
1894 free (case_command
->word
->word
);
1895 case_command
->word
->word
= word
;
1898 wlist
= expand_word_no_split (case_command
->word
, 0);
1899 word
= wlist
? string_list (wlist
) : savestring ("");
1900 dispose_words (wlist
);
1902 retval
= EXECUTION_SUCCESS
;
1903 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
1905 begin_unwind_frame ("case");
1906 add_unwind_protect ((Function
*)xfree
, word
);
1908 #define EXIT_CASE() goto exit_case_command
1910 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
1913 for (list
= clauses
->patterns
; list
; list
= list
->next
)
1915 /* Posix.2 specifies to tilde expand each member of the pattern
1917 if (member ('~', list
->word
->word
))
1919 pattern
= bash_tilde_expand (list
->word
->word
);
1920 free (list
->word
->word
);
1921 list
->word
->word
= pattern
;
1924 es
= expand_word_leave_quoted (list
->word
, 0);
1926 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
1927 pattern
= quote_string_for_globbing (es
->word
->word
, 1);
1930 pattern
= xmalloc (1);
1934 /* Since the pattern does not undergo quote removal (as per
1935 Posix.2, section 3.9.4.3), the fnmatch () call must be able
1936 to recognize backslashes as escape characters. */
1937 match
= fnmatch (pattern
, word
, 0) != FNM_NOMATCH
;
1944 if (clauses
->action
&& ignore_return
)
1945 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
1946 retval
= execute_command (clauses
->action
);
1956 discard_unwind_frame ("case");
1963 /* The WHILE command. Syntax: WHILE test DO action; DONE.
1964 Repeatedly execute action while executing test produces
1965 EXECUTION_SUCCESS. */
1967 execute_while_command (while_command
)
1968 WHILE_COM
*while_command
;
1970 return (execute_while_or_until (while_command
, CMD_WHILE
));
1973 /* UNTIL is just like WHILE except that the test result is negated. */
1975 execute_until_command (while_command
)
1976 WHILE_COM
*while_command
;
1978 return (execute_while_or_until (while_command
, CMD_UNTIL
));
1981 /* The body for both while and until. The only difference between the
1982 two is that the test value is treated differently. TYPE is
1983 CMD_WHILE or CMD_UNTIL. The return value for both commands should
1984 be EXECUTION_SUCCESS if no commands in the body are executed, and
1985 the status of the last command executed in the body otherwise. */
1987 execute_while_or_until (while_command
, type
)
1988 WHILE_COM
*while_command
;
1991 int return_value
, body_status
;
1993 body_status
= EXECUTION_SUCCESS
;
1996 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
1997 if (while_command
->flags
& CMD_IGNORE_RETURN
)
1998 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2002 return_value
= execute_command (while_command
->test
);
2005 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
2007 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
2011 body_status
= execute_command (while_command
->action
);
2029 return (body_status
);
2032 /* IF test THEN command [ELSE command].
2033 IF also allows ELIF in the place of ELSE IF, but
2034 the parser makes *that* stupidity transparent. */
2036 execute_if_command (if_command
)
2041 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2042 return_value
= execute_command (if_command
->test
);
2044 if (return_value
== EXECUTION_SUCCESS
)
2048 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2049 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
2051 return (execute_command (if_command
->true_case
));
2057 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2058 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
2060 return (execute_command (if_command
->false_case
));
2072 var
= bind_variable ("_", arg
);
2073 var
->attributes
&= ~att_exported
;
2076 /* Execute a null command. Fork a subshell if the command uses pipes or is
2077 to be run asynchronously. This handles all the side effects that are
2078 supposed to take place. */
2080 execute_null_command (redirects
, pipe_in
, pipe_out
, async
, old_last_command_subst_pid
)
2081 REDIRECT
*redirects
;
2082 int pipe_in
, pipe_out
, async
, old_last_command_subst_pid
;
2084 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
2086 /* We have a null command, but we really want a subshell to take
2087 care of it. Just fork, do piping and redirections, and exit. */
2088 if (make_child ((char *)NULL
, async
) == 0)
2090 /* Cancel traps, in trap.c. */
2091 restore_original_signals (); /* XXX */
2093 do_piping (pipe_in
, pipe_out
);
2095 subshell_environment
= SUBSHELL_ASYNC
;
2097 if (do_redirections (redirects
, 1, 0, 0) == 0)
2098 exit (EXECUTION_SUCCESS
);
2100 exit (EXECUTION_FAILURE
);
2104 close_pipes (pipe_in
, pipe_out
);
2105 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2106 unlink_fifo_list ();
2108 return (EXECUTION_SUCCESS
);
2113 /* Even if there aren't any command names, pretend to do the
2114 redirections that are specified. The user expects the side
2115 effects to take place. If the redirections fail, then return
2116 failure. Otherwise, if a command substitution took place while
2117 expanding the command or a redirection, return the value of that
2118 substitution. Otherwise, return EXECUTION_SUCCESS. */
2120 if (do_redirections (redirects
, 0, 0, 0) != 0)
2121 return (EXECUTION_FAILURE
);
2122 else if (old_last_command_subst_pid
!= last_command_subst_pid
)
2123 return (last_command_exit_value
);
2125 return (EXECUTION_SUCCESS
);
2129 /* This is a hack to suppress word splitting for assignment statements
2130 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2132 fix_assignment_words (words
)
2141 b
= builtin_address_internal (words
->word
->word
);
2142 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
2145 for (w
= words
; w
; w
= w
->next
)
2146 if (w
->word
->flags
& W_ASSIGNMENT
)
2147 w
->word
->flags
|= W_NOSPLIT
;
2150 /* The meaty part of all the executions. We have to start hacking the
2151 real execution of commands here. Fork a process, set things up,
2152 execute the command. */
2154 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
2155 SIMPLE_COM
*simple_command
;
2156 int pipe_in
, pipe_out
, async
;
2157 struct fd_bitmap
*fds_to_close
;
2159 WORD_LIST
*words
, *lastword
;
2160 char *command_line
, *lastarg
, *temp
;
2161 int first_word_quoted
, result
, builtin_is_special
;
2162 pid_t old_last_command_subst_pid
;
2166 result
= EXECUTION_SUCCESS
;
2167 special_builtin_failed
= builtin_is_special
= 0;
2169 /* If we're in a function, update the line number information. */
2170 if (variable_context
)
2171 line_number
= simple_command
->line
- function_line_number
;
2173 /* Remember what this command line looks like at invocation. */
2174 command_string_index
= 0;
2175 print_simple_command (simple_command
);
2176 command_line
= xmalloc (1 + strlen (the_printed_command
));
2177 strcpy (command_line
, the_printed_command
); /* XXX memory leak on errors */
2180 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
): 0;
2182 old_last_command_subst_pid
= last_command_subst_pid
;
2184 /* If we are re-running this as the result of executing the `command'
2185 builtin, do not expand the command words a second time. */
2186 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
2188 current_fds_to_close
= fds_to_close
;
2189 fix_assignment_words (simple_command
->words
);
2190 words
= expand_words (simple_command
->words
);
2191 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
2194 words
= copy_word_list (simple_command
->words
);
2196 /* It is possible for WORDS not to have anything left in it.
2197 Perhaps all the words consisted of `$foo', and there was
2198 no variable `$foo'. */
2201 result
= execute_null_command (simple_command
->redirects
,
2202 pipe_in
, pipe_out
, async
,
2203 old_last_command_subst_pid
);
2204 FREE (command_line
);
2205 bind_lastarg ((char *)NULL
);
2209 lastarg
= (char *)NULL
;
2211 begin_unwind_frame ("simple-command");
2213 if (echo_command_at_execute
)
2214 xtrace_print_word_list (words
);
2216 builtin
= (Function
*)NULL
;
2217 func
= (SHELL_VAR
*)NULL
;
2218 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
2220 /* Posix.2 says special builtins are found before functions. We
2221 don't set builtin_is_special anywhere other than here, because
2222 this path is followed only when the `command' builtin is *not*
2223 being used, and we don't want to exit the shell if a special
2224 builtin executed with `command builtin' fails. `command' is not
2225 a special builtin. */
2226 if (posixly_correct
)
2228 builtin
= find_special_builtin (words
->word
->word
);
2230 builtin_is_special
= 1;
2233 func
= find_function (words
->word
->word
);
2236 add_unwind_protect (dispose_words
, words
);
2239 /* Bind the last word in this command to "$_" after execution. */
2240 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
2242 lastarg
= lastword
->word
->word
;
2244 #if defined (JOB_CONTROL)
2245 /* Is this command a job control related thing? */
2246 if (words
->word
->word
[0] == '%')
2248 this_command_name
= async
? "bg" : "fg";
2249 last_shell_builtin
= this_shell_builtin
;
2250 this_shell_builtin
= builtin_address (this_command_name
);
2251 result
= (*this_shell_builtin
) (words
);
2255 /* One other possiblilty. The user may want to resume an existing job.
2256 If they do, find out whether this word is a candidate for a running
2258 if (job_control
&& async
== 0 &&
2259 !first_word_quoted
&&
2261 words
->word
->word
[0] &&
2262 !simple_command
->redirects
&&
2263 pipe_in
== NO_PIPE
&&
2264 pipe_out
== NO_PIPE
&&
2265 (temp
= get_string_value ("auto_resume")))
2269 int wl
, cl
, exact
, substring
, match
, started_status
;
2270 register PROCESS
*p
;
2272 word
= words
->word
->word
;
2273 exact
= STREQ (temp
, "exact");
2274 substring
= STREQ (temp
, "substring");
2276 for (i
= job_slots
- 1; i
> -1; i
--)
2278 if (jobs
[i
] == 0 || (JOBSTATE (i
) != JSTOPPED
))
2286 cl
= strlen (p
->command
);
2287 match
= STREQN (p
->command
, word
, cl
);
2290 match
= strindex (p
->command
, word
) != (char *)0;
2292 match
= STREQN (p
->command
, word
, wl
);
2300 run_unwind_frame ("simple-command");
2301 this_command_name
= "fg";
2302 last_shell_builtin
= this_shell_builtin
;
2303 this_shell_builtin
= builtin_address ("fg");
2305 started_status
= start_job (i
, 1);
2306 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
2308 while (p
!= jobs
[i
]->pipe
);
2311 #endif /* JOB_CONTROL */
2313 /* Remember the name of this command globally. */
2314 this_command_name
= words
->word
->word
;
2318 /* This command could be a shell builtin or a user-defined function.
2319 We have already found special builtins by this time, so we do not
2320 set builtin_is_special. If this is a function or builtin, and we
2321 have pipes, then fork a subshell in here. Otherwise, just execute
2322 the command directly. */
2323 if (func
== 0 && builtin
== 0)
2324 builtin
= find_shell_builtin (this_command_name
);
2326 last_shell_builtin
= this_shell_builtin
;
2327 this_shell_builtin
= builtin
;
2329 if (builtin
|| func
)
2331 if ((pipe_in
!= NO_PIPE
) || (pipe_out
!= NO_PIPE
) || async
)
2333 if (make_child (command_line
, async
) == 0)
2335 /* reset_terminating_signals (); */ /* XXX */
2336 /* Cancel traps, in trap.c. */
2337 restore_original_signals ();
2341 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
2342 pipe_in
== NO_PIPE
&&
2343 (stdin_redirects (simple_command
->redirects
) == 0))
2344 async_redirect_stdin ();
2345 setup_async_signals ();
2348 execute_subshell_builtin_or_function
2349 (words
, simple_command
->redirects
, builtin
, func
,
2350 pipe_in
, pipe_out
, async
, fds_to_close
,
2351 simple_command
->flags
);
2355 close_pipes (pipe_in
, pipe_out
);
2356 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2357 unlink_fifo_list ();
2359 command_line
= (char *)NULL
; /* don't free this. */
2365 result
= execute_builtin_or_function
2366 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
2367 simple_command
->flags
);
2370 if (result
> EX_SHERRBASE
)
2372 result
= builtin_status (result
);
2373 if (builtin_is_special
)
2374 special_builtin_failed
= 1;
2376 /* In POSIX mode, if there are assignment statements preceding
2377 a special builtin, they persist after the builtin
2379 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
2380 merge_temporary_env ();
2384 if (result
== EX_USAGE
)
2385 result
= EX_BADUSAGE
;
2386 else if (result
> EX_SHERRBASE
)
2387 result
= EXECUTION_FAILURE
;
2394 execute_disk_command (words
, simple_command
->redirects
, command_line
,
2395 pipe_in
, pipe_out
, async
, fds_to_close
,
2396 simple_command
->flags
);
2399 bind_lastarg (lastarg
);
2400 FREE (command_line
);
2401 run_unwind_frame ("simple-command");
2405 /* Translate the special builtin exit statuses. We don't really need a
2406 function for this; it's a placeholder for future work. */
2408 builtin_status (result
)
2422 r
= EXECUTION_FAILURE
;
2425 r
= EXECUTION_SUCCESS
;
2432 execute_builtin (builtin
, words
, flags
, subshell
)
2435 int flags
, subshell
;
2437 int old_e_flag
, result
, eval_unwind
;
2439 old_e_flag
= exit_immediately_on_error
;
2440 /* The eval builtin calls parse_and_execute, which does not know about
2441 the setting of flags, and always calls the execution functions with
2442 flags that will exit the shell on an error if -e is set. If the
2443 eval builtin is being called, and we're supposed to ignore the exit
2444 value of the command, we turn the -e flag off ourselves, then
2445 restore it when the command completes. */
2446 if (subshell
== 0 && builtin
== eval_builtin
&& (flags
& CMD_IGNORE_RETURN
))
2448 begin_unwind_frame ("eval_builtin");
2449 unwind_protect_int (exit_immediately_on_error
);
2450 exit_immediately_on_error
= 0;
2456 /* The temporary environment for a builtin is supposed to apply to
2457 all commands executed by that builtin. Currently, this is a
2458 problem only with the `source' and `eval' builtins. */
2459 if (builtin
== source_builtin
|| builtin
== eval_builtin
)
2462 begin_unwind_frame ("builtin_env");
2466 builtin_env
= copy_array (temporary_env
);
2468 add_unwind_protect (dispose_builtin_env
, (char *)NULL
);
2469 dispose_used_env_vars ();
2473 builtin_env
= (char **)NULL
;
2477 result
= ((*builtin
) (words
->next
));
2479 if (subshell
== 0 && (builtin
== source_builtin
|| builtin
== eval_builtin
))
2481 /* In POSIX mode, if any variable assignments precede the `.' or
2482 `eval' builtin, they persist after the builtin completes, since `.'
2483 and `eval' are special builtins. */
2484 if (posixly_correct
&& builtin_env
)
2485 merge_builtin_env ();
2486 dispose_builtin_env ();
2487 discard_unwind_frame ("builtin_env");
2492 exit_immediately_on_error
+= old_e_flag
;
2493 discard_unwind_frame ("eval_builtin");
2500 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
2503 int flags
, subshell
, async
;
2504 struct fd_bitmap
*fds_to_close
;
2506 int return_val
, result
;
2510 tc
= (COMMAND
*)copy_command (function_cell (var
));
2511 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
2512 tc
->flags
|= CMD_IGNORE_RETURN
;
2516 begin_unwind_frame ("function_calling");
2518 add_unwind_protect (pop_context
, (char *)NULL
);
2519 unwind_protect_int (line_number
);
2520 unwind_protect_int (return_catch_flag
);
2521 unwind_protect_jmp_buf (return_catch
);
2522 add_unwind_protect (dispose_command
, (char *)tc
);
2523 unwind_protect_int (loop_level
);
2526 debug_trap
= (signal_is_trapped (DEBUG_TRAP
) && signal_is_ignored (DEBUG_TRAP
) == 0)
2527 ? trap_list
[DEBUG_TRAP
]
2533 debug_trap
= savestring (debug_trap
);
2534 add_unwind_protect (set_debug_trap
, debug_trap
);
2535 /* XXX - small memory leak here -- hard to fix */
2537 restore_default_signal (DEBUG_TRAP
);
2540 /* The temporary environment for a function is supposed to apply to
2541 all commands executed within the function body. */
2544 function_env
= copy_array (temporary_env
);
2546 add_unwind_protect (dispose_function_env
, (char *)NULL
);
2547 dispose_used_env_vars ();
2551 function_env
= (char **)NULL
;
2554 remember_args (words
->next
, 1);
2556 /* Number of the line on which the function body starts. */
2557 line_number
= function_line_number
= tc
->line
;
2561 #if defined (JOB_CONTROL)
2562 stop_pipeline (async
, (COMMAND
*)NULL
);
2564 fc
= (tc
->type
== cm_group
) ? tc
->value
.Group
->command
: tc
;
2566 if (fc
&& (flags
& CMD_IGNORE_RETURN
))
2567 fc
->flags
|= CMD_IGNORE_RETURN
;
2574 return_catch_flag
++;
2575 return_val
= setjmp (return_catch
);
2578 result
= return_catch_value
;
2580 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
2583 run_unwind_frame ("function_calling");
2588 /* Execute a shell builtin or function in a subshell environment. This
2589 routine does not return; it only calls exit(). If BUILTIN is non-null,
2590 it points to a function to call to execute a shell builtin; otherwise
2591 VAR points at the body of a function to execute. WORDS is the arguments
2592 to the command, REDIRECTS specifies redirections to perform before the
2593 command is executed. */
2595 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
2596 pipe_in
, pipe_out
, async
, fds_to_close
,
2599 REDIRECT
*redirects
;
2602 int pipe_in
, pipe_out
, async
;
2603 struct fd_bitmap
*fds_to_close
;
2608 /* A subshell is neither a login shell nor interactive. */
2609 login_shell
= interactive
= 0;
2611 subshell_environment
= SUBSHELL_ASYNC
;
2613 maybe_make_export_env (); /* XXX - is this needed? */
2615 #if defined (JOB_CONTROL)
2616 /* Eradicate all traces of job control after we fork the subshell, so
2617 all jobs begun by this subshell are in the same process group as
2618 the shell itself. */
2620 /* Allow the output of `jobs' to be piped. */
2621 if (builtin
== jobs_builtin
&& !async
&&
2622 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
))
2623 kill_current_pipeline ();
2625 without_job_control ();
2627 set_sigchld_handler ();
2628 #endif /* JOB_CONTROL */
2630 set_sigint_handler ();
2632 do_piping (pipe_in
, pipe_out
);
2635 close_fd_bitmap (fds_to_close
);
2637 if (do_redirections (redirects
, 1, 0, 0) != 0)
2638 exit (EXECUTION_FAILURE
);
2642 /* Give builtins a place to jump back to on failure,
2643 so we don't go back up to main(). */
2644 result
= setjmp (top_level
);
2646 if (result
== EXITPROG
)
2647 exit (last_command_exit_value
);
2649 exit (EXECUTION_FAILURE
);
2652 r
= execute_builtin (builtin
, words
, flags
, 1);
2659 exit (execute_function (var
, words
, flags
, fds_to_close
, async
, 1));
2662 /* Execute a builtin or function in the current shell context. If BUILTIN
2663 is non-null, it is the builtin command to execute, otherwise VAR points
2664 to the body of a function. WORDS are the command's arguments, REDIRECTS
2665 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2666 file descriptors to close.
2668 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2669 not undone before this function returns. */
2671 execute_builtin_or_function (words
, builtin
, var
, redirects
,
2672 fds_to_close
, flags
)
2676 REDIRECT
*redirects
;
2677 struct fd_bitmap
*fds_to_close
;
2681 REDIRECT
*saved_undo_list
;
2683 if (do_redirections (redirects
, 1, 1, 0) != 0)
2685 cleanup_redirects (redirection_undo_list
);
2686 redirection_undo_list
= (REDIRECT
*)NULL
;
2687 dispose_exec_redirects ();
2688 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
2691 saved_undo_list
= redirection_undo_list
;
2693 /* Calling the "exec" builtin changes redirections forever. */
2694 if (builtin
== exec_builtin
)
2696 dispose_redirects (saved_undo_list
);
2697 saved_undo_list
= exec_redirection_undo_list
;
2698 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
2701 dispose_exec_redirects ();
2703 if (saved_undo_list
)
2705 begin_unwind_frame ("saved redirects");
2706 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
2709 redirection_undo_list
= (REDIRECT
*)NULL
;
2712 result
= execute_builtin (builtin
, words
, flags
, 0);
2714 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
2716 if (saved_undo_list
)
2718 redirection_undo_list
= saved_undo_list
;
2719 discard_unwind_frame ("saved redirects");
2722 if (redirection_undo_list
)
2724 cleanup_redirects (redirection_undo_list
);
2725 redirection_undo_list
= (REDIRECT
*)NULL
;
2732 setup_async_signals ()
2734 #if defined (JOB_CONTROL)
2735 if (job_control
== 0)
2738 set_signal_handler (SIGINT
, SIG_IGN
);
2739 set_signal_ignored (SIGINT
);
2740 set_signal_handler (SIGQUIT
, SIG_IGN
);
2741 set_signal_ignored (SIGQUIT
);
2745 /* Execute a simple command that is hopefully defined in a disk file
2750 3) look up the command
2753 6) If the execve failed, see if the file has executable mode set.
2754 If so, and it isn't a directory, then execute its contents as
2757 Note that the filename hashing stuff has to take place up here,
2758 in the parent. This is probably why the Bourne style shells
2759 don't handle it, since that would require them to go through
2760 this gnarly hair, for no good reason. */
2762 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
2763 async
, fds_to_close
, cmdflags
)
2765 REDIRECT
*redirects
;
2767 int pipe_in
, pipe_out
, async
;
2768 struct fd_bitmap
*fds_to_close
;
2771 char *pathname
, *command
, **args
;
2775 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
2776 pathname
= words
->word
->word
;
2778 #if defined (RESTRICTED_SHELL)
2779 if (restricted
&& strchr (pathname
, '/'))
2781 internal_error ("%s: restricted: cannot specify `/' in command names",
2783 last_command_exit_value
= EXECUTION_FAILURE
;
2786 #endif /* RESTRICTED_SHELL */
2788 command
= search_for_command (pathname
);
2792 maybe_make_export_env ();
2793 put_command_name_into_env (command
);
2796 /* We have to make the child before we check for the non-existance
2797 of COMMAND, since we want the error messages to be redirected. */
2798 /* If we can get away without forking and there are no pipes to deal with,
2799 don't bother to fork, just directly exec the command. */
2800 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
2803 pid
= make_child (savestring (command_line
), async
);
2807 int old_interactive
;
2810 /* This has been disabled for the time being. */
2811 #if !defined (ARG_MAX) || ARG_MAX >= 10240
2812 if (posixly_correct
== 0)
2813 put_gnu_argv_flags_into_env ((int)getpid (), glob_argv_flags
);
2817 /* Cancel traps, in trap.c. */
2818 restore_original_signals ();
2820 /* restore_original_signals may have undone the work done
2821 by make_child to ensure that SIGINT and SIGQUIT are ignored
2822 in asynchronous children. */
2825 if ((cmdflags
& CMD_STDIN_REDIR
) &&
2826 pipe_in
== NO_PIPE
&&
2827 (stdin_redirects (redirects
) == 0))
2828 async_redirect_stdin ();
2829 setup_async_signals ();
2832 do_piping (pipe_in
, pipe_out
);
2836 old_interactive
= interactive
;
2840 subshell_environment
= SUBSHELL_FORK
;
2842 /* This functionality is now provided by close-on-exec of the
2843 file descriptors manipulated by redirection and piping.
2844 Some file descriptors still need to be closed in all children
2845 because of the way bash does pipes; fds_to_close is a
2846 bitmap of all such file descriptors. */
2848 close_fd_bitmap (fds_to_close
);
2850 if (redirects
&& (do_redirections (redirects
, 1, 0, 0) != 0))
2852 #if defined (PROCESS_SUBSTITUTION)
2853 /* Try to remove named pipes that may have been created as the
2854 result of redirections. */
2855 unlink_fifo_list ();
2856 #endif /* PROCESS_SUBSTITUTION */
2857 exit (EXECUTION_FAILURE
);
2861 interactive
= old_interactive
;
2865 internal_error ("%s: command not found", pathname
);
2866 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
2869 /* Execve expects the command name to be in args[0]. So we
2870 leave it there, in the same format that the user used to
2872 args
= word_list_to_argv (words
, 0, 0, (int *)NULL
);
2873 exit (shell_execve (command
, args
, export_env
));
2877 /* Make sure that the pipes are closed in the parent. */
2878 close_pipes (pipe_in
, pipe_out
);
2879 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2880 unlink_fifo_list ();
2886 #if !defined (HAVE_HASH_BANG_EXEC)
2887 /* If the operating system on which we're running does not handle
2888 the #! executable format, then help out. SAMPLE is the text read
2889 from the file, SAMPLE_LEN characters. COMMAND is the name of
2890 the script; it and ARGS, the arguments given by the user, will
2891 become arguments to the specified interpreter. ENV is the environment
2892 to pass to the interpreter.
2894 The word immediately following the #! is the interpreter to execute.
2895 A single argument to the interpreter is allowed. */
2897 execute_shell_script (sample
, sample_len
, command
, args
, env
)
2898 unsigned char *sample
;
2904 char *execname
, *firstarg
;
2905 int start
, size_increment
, larry
;
2907 /* Find the name of the interpreter to exec. */
2908 for (i
= 2; whitespace (sample
[i
]) && i
< sample_len
; i
++)
2912 !whitespace (sample
[i
]) && sample
[i
] != '\n' && i
< sample_len
;
2917 execname
= xmalloc (1 + larry
);
2918 strncpy (execname
, (char *)(sample
+ start
), larry
);
2919 execname
[larry
] = '\0';
2922 /* Now the argument, if any. */
2923 firstarg
= (char *)NULL
;
2925 whitespace (sample
[i
]) && sample
[i
] != '\n' && i
< sample_len
;
2929 /* If there is more text on the line, then it is an argument for the
2931 if (i
< sample_len
&& sample
[i
] != '\n' && !whitespace (sample
[i
]))
2934 !whitespace (sample
[i
]) && sample
[i
] != '\n' && i
< sample_len
;
2938 firstarg
= xmalloc (1 + larry
);
2939 strncpy (firstarg
, (char *)(sample
+ start
), larry
);
2940 firstarg
[larry
] = '\0';
2945 larry
= array_len (args
) + size_increment
;
2947 args
= (char **)xrealloc ((char *)args
, (1 + larry
) * sizeof (char *));
2949 for (i
= larry
- 1; i
; i
--)
2950 args
[i
] = args
[i
- size_increment
];
2961 args
[larry
] = (char *)NULL
;
2963 return (shell_execve (execname
, args
, env
));
2965 #endif /* !HAVE_HASH_BANG_EXEC */
2968 initialize_subshell ()
2971 /* Forget about any aliases that we knew of. We are in a subshell. */
2972 delete_all_aliases ();
2975 #if defined (HISTORY)
2976 /* Forget about the history lines we have read. This is a non-interactive
2978 history_lines_this_session
= 0;
2981 #if defined (JOB_CONTROL)
2982 /* Forget about the way job control was working. We are in a subshell. */
2983 without_job_control ();
2984 set_sigchld_handler ();
2985 #endif /* JOB_CONTROL */
2987 /* Reset the values of the shell flags and options. */
2988 reset_shell_flags ();
2989 reset_shell_options ();
2990 reset_shopt_options ();
2992 /* If we're not interactive, close the file descriptor from which we're
2993 reading the current shell script. */
2994 #if defined (BUFFERED_INPUT)
2995 if (interactive_shell
== 0 && default_buffered_input
>= 0)
2997 close_buffered_fd (default_buffered_input
);
2998 default_buffered_input
= bash_input
.location
.buffered_fd
= -1;
3001 if (interactive_shell
== 0 && default_input
)
3003 fclose (default_input
);
3004 default_input
= (FILE *)NULL
;
3009 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3010 # define SETOSTYPE(x) __setostype(x)
3012 # define SETOSTYPE(x)
3015 /* Call execve (), handling interpreting shell scripts, and handling
3018 shell_execve (command
, args
, env
)
3025 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3026 execve (command
, args
, env
);
3029 /* If we get to this point, then start checking out the file.
3030 Maybe it is something we can hack ourselves. */
3031 if (errno
!= ENOEXEC
)
3034 if ((stat (command
, &finfo
) == 0) && (S_ISDIR (finfo
.st_mode
)))
3035 internal_error ("%s: is a directory", command
);
3039 file_error (command
);
3041 return ((i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
); /* XXX Posix.2 says that exit status is 126 */
3044 /* This file is executable.
3045 If it begins with #!, then help out people with losing operating
3046 systems. Otherwise, check to see if it is a binary file by seeing
3047 if the first line (or up to 80 characters) are in the ASCII set.
3048 Execute the contents as shell commands. */
3049 fd
= open (command
, O_RDONLY
);
3052 unsigned char sample
[80];
3055 sample_len
= read (fd
, (char *)sample
, 80);
3058 if (sample_len
== 0)
3059 return (EXECUTION_SUCCESS
);
3061 /* Is this supposed to be an executable script?
3062 If so, the format of the line is "#! interpreter [argument]".
3063 A single argument is allowed. The BSD kernel restricts
3064 the length of the entire line to 32 characters (32 bytes
3065 being the size of the BSD exec header), but we allow 80
3069 #if !defined (HAVE_HASH_BANG_EXEC)
3070 if (sample
[0] == '#' && sample
[1] == '!')
3071 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
3074 if (check_binary_file (sample
, sample_len
))
3076 internal_error ("%s: cannot execute binary file", command
);
3077 return (EX_BINARY_FILE
);
3082 initialize_subshell ();
3084 set_sigint_handler ();
3086 /* Insert the name of this shell into the argument list. */
3087 larray
= array_len (args
) + 1;
3088 args
= (char **)xrealloc ((char *)args
, (1 + larray
) * sizeof (char *));
3090 for (i
= larray
- 1; i
; i
--)
3091 args
[i
] = args
[i
- 1];
3093 args
[0] = shell_name
;
3095 args
[larray
] = (char *)NULL
;
3097 if (args
[0][0] == '-')
3100 #if defined (RESTRICTED_SHELL)
3102 change_flag ('r', FLAG_OFF
);
3107 /* Can't free subshell_argv[0]; that is shell_name. */
3108 for (i
= 1; i
< subshell_argc
; i
++)
3109 free (subshell_argv
[i
]);
3110 free (subshell_argv
);
3113 dispose_command (currently_executing_command
); /* XXX */
3114 currently_executing_command
= (COMMAND
*)NULL
;
3116 subshell_argc
= larray
;
3117 subshell_argv
= args
;
3118 subshell_envp
= env
;
3120 unbind_args (); /* remove the positional parameters */
3122 longjmp (subshell_top_level
, 1);
3126 execute_intern_function (name
, function
)
3132 if (check_identifier (name
, posixly_correct
) == 0)
3134 if (posixly_correct
&& interactive_shell
== 0)
3136 last_command_exit_value
= EX_USAGE
;
3137 jump_to_top_level (EXITPROG
);
3139 return (EXECUTION_FAILURE
);
3142 var
= find_function (name
->word
);
3143 if (var
&& readonly_p (var
))
3145 internal_error ("%s: readonly function", var
->name
);
3146 return (EXECUTION_FAILURE
);
3149 bind_function (name
->word
, function
);
3150 return (EXECUTION_SUCCESS
);
3153 #if defined (INCLUDE_UNUSED)
3154 #if defined (PROCESS_SUBSTITUTION)
3158 register int i
, fd_table_size
;
3160 fd_table_size
= getdtablesize ();
3161 if (fd_table_size
> 256) /* clamp to a reasonable value */
3162 fd_table_size
= 256;
3164 for (i
= 3; i
< fd_table_size
; i
++)
3167 #endif /* PROCESS_SUBSTITUTION */
3171 close_pipes (in
, out
)
3180 /* Redirect input and output to be from and to the specified pipes.
3181 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3183 do_piping (pipe_in
, pipe_out
)
3184 int pipe_in
, pipe_out
;
3186 if (pipe_in
!= NO_PIPE
)
3188 if (dup2 (pipe_in
, 0) < 0)
3189 sys_error ("cannot duplicate fd %d to fd 0", pipe_in
);
3193 if (pipe_out
!= NO_PIPE
)
3195 if (pipe_out
!= REDIRECT_BOTH
)
3197 if (dup2 (pipe_out
, 1) < 0)
3198 sys_error ("cannot duplicate fd %d to fd 1", pipe_out
);
3199 if (pipe_out
== 0 || pipe_out
> 1)
3203 if (dup2 (1, 2) < 0)
3204 sys_error ("cannot duplicate fd 1 to fd 2");
3209 redirection_error (temp
, error
)
3215 if (expandable_redirection_filename (temp
))
3217 if (posixly_correct
&& !interactive_shell
)
3218 disallow_filename_globbing
++;
3219 filename
= redirection_expand (temp
->redirectee
.filename
);
3220 if (posixly_correct
&& !interactive_shell
)
3221 disallow_filename_globbing
--;
3223 filename
= savestring (temp
->redirectee
.filename
->word
);
3226 filename
= xmalloc (1);
3231 filename
= itos (temp
->redirectee
.dest
);
3235 case AMBIGUOUS_REDIRECT
:
3236 internal_error ("%s: ambiguous redirect", filename
);
3239 case NOCLOBBER_REDIRECT
:
3240 internal_error ("%s: cannot overwrite existing file", filename
);
3243 #if defined (RESTRICTED_SHELL)
3244 case RESTRICTED_REDIRECT
:
3245 internal_error ("%s: restricted: cannot redirect output", filename
);
3247 #endif /* RESTRICTED_SHELL */
3249 case HEREDOC_REDIRECT
:
3250 internal_error ("cannot create temp file for here document: %s", strerror (heredoc_errno
));
3254 internal_error ("%s: %s", filename
, strerror (error
));
3261 /* Perform the redirections on LIST. If FOR_REAL, then actually make
3262 input and output file descriptors, otherwise just do whatever is
3263 neccessary for side effecting. INTERNAL says to remember how to
3264 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
3265 file descriptors opened in do_redirection () have their close-on-exec
3268 do_redirections (list
, for_real
, internal
, set_clexec
)
3270 int for_real
, internal
, set_clexec
;
3277 if (redirection_undo_list
)
3279 dispose_redirects (redirection_undo_list
);
3280 redirection_undo_list
= (REDIRECT
*)NULL
;
3282 if (exec_redirection_undo_list
)
3283 dispose_exec_redirects ();
3286 for (temp
= list
; temp
; temp
= temp
->next
)
3288 error
= do_redirection_internal (temp
, for_real
, internal
, set_clexec
);
3291 redirection_error (temp
, error
);
3298 /* Return non-zero if the redirection pointed to by REDIRECT has a
3299 redirectee.filename that can be expanded. */
3301 expandable_redirection_filename (redirect
)
3304 switch (redirect
->instruction
)
3306 case r_output_direction
:
3307 case r_appending_to
:
3308 case r_input_direction
:
3309 case r_inputa_direction
:
3311 case r_input_output
:
3312 case r_output_force
:
3313 case r_duplicating_input_word
:
3314 case r_duplicating_output_word
:
3322 /* Expand the word in WORD returning a string. If WORD expands to
3323 multiple words (or no words), then return NULL. */
3325 redirection_expand (word
)
3329 WORD_LIST
*tlist1
, *tlist2
;
3331 tlist1
= make_word_list (copy_word (word
), (WORD_LIST
*)NULL
);
3332 tlist2
= expand_words_no_vars (tlist1
);
3333 dispose_words (tlist1
);
3335 if (!tlist2
|| tlist2
->next
)
3337 /* We expanded to no words, or to more than a single word.
3338 Dispose of the word list and return NULL. */
3340 dispose_words (tlist2
);
3341 return ((char *)NULL
);
3343 result
= string_list (tlist2
); /* XXX savestring (tlist2->word->word)? */
3344 dispose_words (tlist2
);
3348 /* Write the text of the here document pointed to by REDIRECTEE to the file
3349 descriptor FD, which is already open to a temp file. Return 0 if the
3350 write is successful, otherwise return errno. */
3352 write_here_document (fd
, redirectee
)
3354 WORD_DESC
*redirectee
;
3357 int document_len
, fd2
;
3359 register WORD_LIST
*t
, *tlist
;
3361 /* Expand the text if the word that was specified had
3362 no quoting. The text that we expand is treated
3363 exactly as if it were surrounded by double quotes. */
3365 if (redirectee
->flags
& W_QUOTED
)
3367 document
= redirectee
->word
;
3368 document_len
= strlen (document
);
3369 /* Set errno to something reasonable if the write fails. */
3370 if (write (fd
, document
, document_len
) < document_len
)
3380 tlist
= expand_string (redirectee
->word
, Q_HERE_DOCUMENT
);
3383 /* Try using buffered I/O (stdio) and writing a word
3384 at a time, letting stdio do the work of buffering
3385 for us rather than managing our own strings. Most
3386 stdios are not particularly fast, however -- this
3387 may need to be reconsidered later. */
3388 if ((fd2
= dup (fd
)) < 0 || (fp
= fdopen (fd2
, "w")) == NULL
)
3395 for (t
= tlist
; t
; t
= t
->next
)
3397 /* This is essentially the body of
3398 string_list_internal expanded inline. */
3399 document
= t
->word
->word
;
3400 document_len
= strlen (document
);
3402 putc (' ', fp
); /* separator */
3403 fwrite (document
, document_len
, 1, fp
);
3410 dispose_words (tlist
);
3415 dispose_words (tlist
);
3420 /* Create a temporary file holding the text of the here document pointed to
3421 by REDIRECTEE, and return a file descriptor open for reading to the temp
3422 file. Return -1 on any error, and make sure errno is set appropriately. */
3424 here_document_to_fd (redirectee
)
3425 WORD_DESC
*redirectee
;
3430 /* Make the filename for the temp file. */
3431 sprintf (filename
, "/tmp/t%d-sh", (int)time ((time_t *) 0) + (int)getpid ());
3433 /* Make sure we open it exclusively. */
3434 fd
= open (filename
, O_TRUNC
| O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
3438 errno
= r
= 0; /* XXX */
3439 /* write_here_document returns 0 on success, errno on failure. */
3440 if (redirectee
->word
)
3441 r
= write_here_document (fd
, redirectee
);
3451 /* XXX - this is raceable */
3452 /* Make the document really temporary. Also make it the input. */
3453 fd
= open (filename
, O_RDONLY
, 0600);
3463 if (unlink (filename
) < 0)
3474 /* Open FILENAME with FLAGS in noclobber mode, hopefully avoiding most
3475 race conditions and avoiding the problem where the file is replaced
3476 between the stat(2) and open(2). */
3478 noclobber_open (filename
, flags
, ri
)
3481 enum r_instruction ri
;
3484 struct stat finfo
, finfo2
;
3486 /* If the file exists and is a regular file, return an error
3488 r
= stat (filename
, &finfo
);
3489 if (r
== 0 && (S_ISREG (finfo
.st_mode
)))
3490 return (NOCLOBBER_REDIRECT
);
3492 /* If the file was not present (r != 0), make sure we open it
3493 exclusively so that if it is created before we open it, our open
3494 will fail. Make sure that we do not truncate an existing file.
3495 Note that we don't turn on O_EXCL unless the stat failed -- if
3496 the file was not a regular file, we leave O_EXCL off. */
3500 fd
= open (filename
, flags
|O_EXCL
, 0666);
3501 return ((fd
< 0 && errno
== EEXIST
) ? NOCLOBBER_REDIRECT
: fd
);
3503 fd
= open (filename
, flags
, 0666);
3505 /* If the open failed, return the file descriptor right away. */
3507 return (errno
== EEXIST
? NOCLOBBER_REDIRECT
: fd
);
3509 /* OK, the open succeeded, but the file may have been changed from a
3510 non-regular file to a regular file between the stat and the open.
3511 We are assuming that the O_EXCL open handles the case where FILENAME
3512 did not exist and is symlinked to an existing file between the stat
3515 /* If we can open it and fstat the file descriptor, and neither check
3516 revealed that it was a regular file, and the file has not been replaced,
3517 return the file descriptor. */
3518 if ((fstat (fd
, &finfo2
) == 0) && (S_ISREG (finfo2
.st_mode
) == 0) &&
3519 r
== 0 && (S_ISREG (finfo
.st_mode
) == 0) &&
3520 same_file (filename
, filename
, &finfo
, &finfo2
))
3523 /* The file has been replaced. badness. */
3526 return (NOCLOBBER_REDIRECT
);
3529 /* Do the specific redirection requested. Returns errno or one of the
3530 special redirection errors (*_REDIRECT) in case of error, 0 on success.
3531 If FOR_REAL is zero, then just do whatever is neccessary to produce the
3532 appropriate side effects. REMEMBERING, if non-zero, says to remember
3533 how to undo each redirection. If SET_CLEXEC is non-zero, then
3534 we set all file descriptors > 2 that we open to be close-on-exec. */
3536 do_redirection_internal (redirect
, for_real
, remembering
, set_clexec
)
3538 int for_real
, remembering
, set_clexec
;
3540 WORD_DESC
*redirectee
;
3541 int redir_fd
, fd
, redirector
, r
;
3542 char *redirectee_word
;
3543 enum r_instruction ri
;
3544 REDIRECT
*new_redirect
;
3546 redirectee
= redirect
->redirectee
.filename
;
3547 redir_fd
= redirect
->redirectee
.dest
;
3548 redirector
= redirect
->redirector
;
3549 ri
= redirect
->instruction
;
3551 if (ri
== r_duplicating_input_word
|| ri
== r_duplicating_output_word
)
3553 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
3554 the redirection into a new one and continue. */
3555 redirectee_word
= redirection_expand (redirectee
);
3557 if (redirectee_word
== 0)
3558 return (AMBIGUOUS_REDIRECT
);
3559 else if (redirectee_word
[0] == '-' && redirectee_word
[1] == '\0')
3562 new_redirect
= make_redirection (redirector
, r_close_this
, rd
);
3564 else if (all_digits (redirectee_word
))
3566 if (ri
== r_duplicating_input_word
)
3568 rd
.dest
= atol (redirectee_word
);
3569 new_redirect
= make_redirection (redirector
, r_duplicating_input
, rd
);
3573 rd
.dest
= atol (redirectee_word
);
3574 new_redirect
= make_redirection (redirector
, r_duplicating_output
, rd
);
3577 else if (ri
== r_duplicating_output_word
&& redirector
== 1)
3579 if (posixly_correct
== 0)
3581 rd
.filename
= make_bare_word (redirectee_word
);
3582 new_redirect
= make_redirection (1, r_err_and_out
, rd
);
3585 new_redirect
= copy_redirect (redirect
);
3589 free (redirectee_word
);
3590 return (AMBIGUOUS_REDIRECT
);
3593 free (redirectee_word
);
3595 /* Set up the variables needed by the rest of the function from the
3597 if (new_redirect
->instruction
== r_err_and_out
)
3601 /* Copy the word without allocating any memory that must be
3602 explicitly freed. */
3603 redirectee
= (WORD_DESC
*)alloca (sizeof (WORD_DESC
));
3604 xbcopy ((char *)new_redirect
->redirectee
.filename
,
3605 (char *)redirectee
, sizeof (WORD_DESC
));
3607 alloca_hack
= (char *)
3608 alloca (1 + strlen (new_redirect
->redirectee
.filename
->word
));
3609 redirectee
->word
= alloca_hack
;
3610 strcpy (redirectee
->word
, new_redirect
->redirectee
.filename
->word
);
3613 /* It's guaranteed to be an integer, and shouldn't be freed. */
3614 redirectee
= new_redirect
->redirectee
.filename
;
3616 redir_fd
= new_redirect
->redirectee
.dest
;
3617 redirector
= new_redirect
->redirector
;
3618 ri
= new_redirect
->instruction
;
3620 /* Overwrite the flags element of the old redirect with the new value. */
3621 redirect
->flags
= new_redirect
->flags
;
3622 dispose_redirects (new_redirect
);
3627 case r_output_direction
:
3628 case r_appending_to
:
3629 case r_input_direction
:
3630 case r_inputa_direction
:
3631 case r_err_and_out
: /* command &>filename */
3632 case r_input_output
:
3633 case r_output_force
:
3634 if (posixly_correct
&& !interactive_shell
)
3635 disallow_filename_globbing
++;
3636 redirectee_word
= redirection_expand (redirectee
);
3637 if (posixly_correct
&& !interactive_shell
)
3638 disallow_filename_globbing
--;
3640 if (redirectee_word
== 0)
3641 return (AMBIGUOUS_REDIRECT
);
3643 #if defined (RESTRICTED_SHELL)
3644 if (restricted
&& (WRITE_REDIRECT (ri
)))
3646 free (redirectee_word
);
3647 return (RESTRICTED_REDIRECT
);
3649 #endif /* RESTRICTED_SHELL */
3651 /* If we are in noclobber mode, you are not allowed to overwrite
3652 existing files. Check before opening. */
3653 if (noclobber
&& OUTPUT_REDIRECT (ri
))
3655 fd
= noclobber_open (redirectee_word
, redirect
->flags
, ri
);
3656 if (fd
== NOCLOBBER_REDIRECT
)
3658 free (redirectee_word
);
3659 return (NOCLOBBER_REDIRECT
);
3664 fd
= open (redirectee_word
, redirect
->flags
, 0666);
3666 if ((fd
< 0) && (errno
== EACCES
))
3667 fd
= open (redirectee_word
, redirect
->flags
& ~O_CREAT
, 0666);
3670 free (redirectee_word
);
3678 /* Only setup to undo it if the thing to undo is active. */
3679 if ((fd
!= redirector
) && (fcntl (redirector
, F_GETFD
, 0) != -1))
3680 add_undo_redirect (redirector
);
3682 add_undo_close_redirect (redirector
);
3684 #if defined (BUFFERED_INPUT)
3685 check_bash_input (redirector
);
3688 if ((fd
!= redirector
) && (dup2 (fd
, redirector
) < 0))
3691 #if defined (BUFFERED_INPUT)
3692 /* Do not change the buffered stream for an implicit redirection
3693 of /dev/null to fd 0 for asynchronous commands without job
3694 control (r_inputa_direction). */
3695 if (ri
== r_input_direction
|| ri
== r_input_output
)
3696 duplicate_buffered_stream (fd
, redirector
);
3697 #endif /* BUFFERED_INPUT */
3700 * If we're remembering, then this is the result of a while, for
3701 * or until loop with a loop redirection, or a function/builtin
3702 * executing in the parent shell with a redirection. In the
3703 * function/builtin case, we want to set all file descriptors > 2
3704 * to be close-on-exec to duplicate the effect of the old
3705 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
3706 * both sh and ksh leave the file descriptors open across execs.
3707 * The Posix standard mentions only the exec builtin.
3709 if (set_clexec
&& (redirector
> 2))
3710 SET_CLOSE_ON_EXEC (redirector
);
3713 if (fd
!= redirector
)
3715 #if defined (BUFFERED_INPUT)
3716 if (INPUT_REDIRECT (ri
))
3717 close_buffered_fd (fd
);
3719 #endif /* !BUFFERED_INPUT */
3720 close (fd
); /* Don't close what we just opened! */
3723 /* If we are hacking both stdout and stderr, do the stderr
3724 redirection here. */
3725 if (ri
== r_err_and_out
)
3730 add_undo_redirect (2);
3731 if (dup2 (1, 2) < 0)
3737 case r_reading_until
:
3738 case r_deblank_reading_until
:
3739 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
3740 the new input. Place it in a temporary file. */
3743 fd
= here_document_to_fd (redirectee
);
3747 heredoc_errno
= errno
;
3748 return (HEREDOC_REDIRECT
);
3754 /* Only setup to undo it if the thing to undo is active. */
3755 if ((fd
!= redirector
) && (fcntl (redirector
, F_GETFD
, 0) != -1))
3756 add_undo_redirect (redirector
);
3758 add_undo_close_redirect (redirector
);
3760 #if defined (BUFFERED_INPUT)
3761 check_bash_input (redirector
);
3763 if (fd
!= redirector
&& dup2 (fd
, redirector
) < 0)
3770 #if defined (BUFFERED_INPUT)
3771 duplicate_buffered_stream (fd
, redirector
);
3774 if (set_clexec
&& (redirector
> 2))
3775 SET_CLOSE_ON_EXEC (redirector
);
3778 #if defined (BUFFERED_INPUT)
3779 close_buffered_fd (fd
);
3786 case r_duplicating_input
:
3787 case r_duplicating_output
:
3788 if (for_real
&& (redir_fd
!= redirector
))
3791 /* Only setup to undo it if the thing to undo is active. */
3792 if (fcntl (redirector
, F_GETFD
, 0) != -1)
3793 add_undo_redirect (redirector
);
3795 add_undo_close_redirect (redirector
);
3797 #if defined (BUFFERED_INPUT)
3798 check_bash_input (redirector
);
3800 /* This is correct. 2>&1 means dup2 (1, 2); */
3801 if (dup2 (redir_fd
, redirector
) < 0)
3804 #if defined (BUFFERED_INPUT)
3805 if (ri
== r_duplicating_input
)
3806 duplicate_buffered_stream (redir_fd
, redirector
);
3807 #endif /* BUFFERED_INPUT */
3809 /* First duplicate the close-on-exec state of redirectee. dup2
3810 leaves the flag unset on the new descriptor, which means it
3811 stays open. Only set the close-on-exec bit for file descriptors
3812 greater than 2 in any case, since 0-2 should always be open
3813 unless closed by something like `exec 2<&-'. */
3814 /* if ((already_set || set_unconditionally) && (ok_to_set))
3816 if (((fcntl (redir_fd
, F_GETFD
, 0) == 1) || set_clexec
) &&
3818 SET_CLOSE_ON_EXEC (redirector
);
3825 if (remembering
&& (fcntl (redirector
, F_GETFD
, 0) != -1))
3826 add_undo_redirect (redirector
);
3828 #if defined (BUFFERED_INPUT)
3829 check_bash_input (redirector
);
3830 close_buffered_fd (redirector
);
3831 #else /* !BUFFERED_INPUT */
3833 #endif /* !BUFFERED_INPUT */
3837 case r_duplicating_input_word
:
3838 case r_duplicating_output_word
:
3844 #define SHELL_FD_BASE 10
3846 /* Remember the file descriptor associated with the slot FD,
3847 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
3848 before it is executed. Any redirections that need to be undone
3849 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
3850 are also saved on EXEC_REDIRECTION_UNDO_LIST. */
3852 add_undo_redirect (fd
)
3855 int new_fd
, clexec_flag
;
3856 REDIRECT
*new_redirect
, *closer
, *dummy_redirect
;
3858 new_fd
= fcntl (fd
, F_DUPFD
, SHELL_FD_BASE
);
3862 sys_error ("redirection error");
3866 clexec_flag
= fcntl (fd
, F_GETFD
, 0);
3869 closer
= make_redirection (new_fd
, r_close_this
, rd
);
3870 dummy_redirect
= copy_redirects (closer
);
3872 rd
.dest
= (long)new_fd
;
3873 new_redirect
= make_redirection (fd
, r_duplicating_output
, rd
);
3874 new_redirect
->next
= closer
;
3876 closer
->next
= redirection_undo_list
;
3877 redirection_undo_list
= new_redirect
;
3879 /* Save redirections that need to be undone even if the undo list
3880 is thrown away by the `exec' builtin. */
3881 add_exec_redirect (dummy_redirect
);
3883 /* File descriptors used only for saving others should always be
3884 marked close-on-exec. Unfortunately, we have to preserve the
3885 close-on-exec state of the file descriptor we are saving, since
3886 fcntl (F_DUPFD) sets the new file descriptor to remain open
3887 across execs. If, however, the file descriptor whose state we
3888 are saving is <= 2, we can just set the close-on-exec flag,
3889 because file descriptors 0-2 should always be open-on-exec,
3890 and the restore above in do_redirection() will take care of it. */
3891 if (clexec_flag
|| fd
< 3)
3892 SET_CLOSE_ON_EXEC (new_fd
);
3897 /* Set up to close FD when we are finished with the current command
3898 and its redirections. */
3900 add_undo_close_redirect (fd
)
3906 closer
= make_redirection (fd
, r_close_this
, rd
);
3907 closer
->next
= redirection_undo_list
;
3908 redirection_undo_list
= closer
;
3912 add_exec_redirect (dummy_redirect
)
3913 REDIRECT
*dummy_redirect
;
3915 dummy_redirect
->next
= exec_redirection_undo_list
;
3916 exec_redirection_undo_list
= dummy_redirect
;
3919 #define u_mode_bits(x) (((x) & 0000700) >> 6)
3920 #define g_mode_bits(x) (((x) & 0000070) >> 3)
3921 #define o_mode_bits(x) (((x) & 0000007) >> 0)
3922 #define X_BIT(x) ((x) & 1)
3924 /* Return some flags based on information about this file.
3925 The EXISTS bit is non-zero if the file is found.
3926 The EXECABLE bit is non-zero the file is executble.
3927 Zero is returned if the file is not found. */
3934 /* Determine whether this file exists or not. */
3935 if (stat (name
, &finfo
) < 0)
3938 /* If the file is a directory, then it is not "executable" in the
3939 sense of the shell. */
3940 if (S_ISDIR (finfo
.st_mode
))
3941 return (FS_EXISTS
|FS_DIRECTORY
);
3944 /* We have to use access(2) to determine access because AFS does not
3945 support Unix file system semantics. This may produce wrong
3946 answers for non-AFS files when ruid != euid. I hate AFS. */
3947 if (access (name
, X_OK
) == 0)
3948 return (FS_EXISTS
| FS_EXECABLE
);
3953 /* Find out if the file is actually executable. By definition, the
3954 only other criteria is that the file has an execute bit set that
3957 /* Root only requires execute permission for any of owner, group or
3958 others to be able to exec a file. */
3959 if (current_user
.euid
== (uid_t
)0)
3963 bits
= (u_mode_bits (finfo
.st_mode
) |
3964 g_mode_bits (finfo
.st_mode
) |
3965 o_mode_bits (finfo
.st_mode
));
3968 return (FS_EXISTS
| FS_EXECABLE
);
3971 /* If we are the owner of the file, the owner execute bit applies. */
3972 if (current_user
.euid
== finfo
.st_uid
&& X_BIT (u_mode_bits (finfo
.st_mode
)))
3973 return (FS_EXISTS
| FS_EXECABLE
);
3975 /* If we are in the owning group, the group permissions apply. */
3976 if (group_member (finfo
.st_gid
) && X_BIT (g_mode_bits (finfo
.st_mode
)))
3977 return (FS_EXISTS
| FS_EXECABLE
);
3979 /* If `others' have execute permission to the file, then so do we,
3980 since we are also `others'. */
3981 if (X_BIT (o_mode_bits (finfo
.st_mode
)))
3982 return (FS_EXISTS
| FS_EXECABLE
);
3988 /* Return non-zero if FILE exists and is executable.
3989 Note that this function is the definition of what an
3990 executable file is; do not change this unless YOU know
3991 what an executable file is. */
3993 executable_file (file
)
3998 s
= file_status (file
);
3999 return ((s
& FS_EXECABLE
) && ((s
& FS_DIRECTORY
) == 0));
4006 return (file_status (file
) & FS_DIRECTORY
);
4009 /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
4010 encounters a `.' as the directory pathname while scanning the
4011 list of possible pathnames; i.e., if `.' comes before the directory
4012 containing the file of interest. */
4013 int dot_found_in_search
= 0;
4015 /* Locate the executable file referenced by NAME, searching along
4016 the contents of the shell PATH variable. Return a new string
4017 which is the full pathname to the file, or NULL if the file
4018 couldn't be found. If a file is found that isn't executable,
4019 and that is the only match, then return that. */
4021 find_user_command (name
)
4024 return (find_user_command_internal (name
, FS_EXEC_PREFERRED
|FS_NODIRS
));
4027 /* Locate the file referenced by NAME, searching along the contents
4028 of the shell PATH variable. Return a new string which is the full
4029 pathname to the file, or NULL if the file couldn't be found. This
4030 returns the first file found. */
4032 find_path_file (name
)
4035 return (find_user_command_internal (name
, FS_EXISTS
));
4039 _find_user_command_internal (name
, flags
)
4046 /* Search for the value of PATH in both the temporary environment, and
4047 in the regular list of variables. */
4048 if (var
= find_variable_internal ("PATH", 1)) /* XXX could be array? */
4049 path_list
= value_cell (var
);
4051 path_list
= (char *)NULL
;
4053 if (path_list
== 0 || *path_list
== '\0')
4054 return (savestring (name
));
4056 return (find_user_command_in_path (name
, path_list
, flags
));
4060 find_user_command_internal (name
, flags
)
4067 dotexe
= xmalloc (strlen (name
) + 5);
4068 strcpy (dotexe
, name
);
4069 strcat (dotexe
, ".exe");
4070 res
= _find_user_command_internal (dotexe
, flags
);
4073 res
= _find_user_command_internal (name
, flags
);
4076 return (_find_user_command_internal (name
, flags
));
4080 /* Return the next element from PATH_LIST, a colon separated list of
4081 paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST;
4082 the index is modified by this function.
4083 Return the next element of PATH_LIST or NULL if there are no more. */
4085 get_next_path_element (path_list
, path_index_pointer
)
4087 int *path_index_pointer
;
4091 path
= extract_colon_unit (path_list
, path_index_pointer
);
4099 path
= savestring (".");
4105 /* Look for PATHNAME in $PATH. Returns either the hashed command
4106 corresponding to PATHNAME or the first instance of PATHNAME found
4107 in $PATH. Returns a newly-allocated string. */
4109 search_for_command (pathname
)
4112 char *hashed_file
, *command
;
4116 hashed_file
= command
= (char *)NULL
;
4118 /* If PATH is in the temporary environment for this command, don't use the
4119 hash table to search for the full pathname. */
4120 path
= find_tempenv_variable ("PATH");
4121 temp_path
= path
!= 0;
4123 /* Don't waste time trying to find hashed data for a pathname
4124 that is already completely specified or if we're using a command-
4125 specific value for PATH. */
4126 if (path
== 0 && absolute_program (pathname
) == 0)
4127 hashed_file
= find_hashed_filename (pathname
);
4129 /* If a command found in the hash table no longer exists, we need to
4130 look for it in $PATH. Thank you Posix.2. This forces us to stat
4131 every command found in the hash table. */
4133 if (hashed_file
&& (posixly_correct
|| check_hashed_filenames
))
4135 st
= file_status (hashed_file
);
4136 if ((st
^ (FS_EXISTS
| FS_EXECABLE
)) != 0)
4138 remove_hashed_filename (pathname
);
4140 hashed_file
= (char *)NULL
;
4145 command
= hashed_file
;
4146 else if (absolute_program (pathname
))
4147 /* A command containing a slash is not looked up in PATH or saved in
4149 command
= savestring (pathname
);
4152 /* If $PATH is in the temporary environment, we've already retrieved
4153 it, so don't bother trying again. */
4155 command
= find_user_command_in_path (pathname
, value_cell (path
),
4156 FS_EXEC_PREFERRED
|FS_NODIRS
);
4158 command
= find_user_command (pathname
);
4159 if (command
&& hashing_enabled
&& temp_path
== 0)
4160 remember_filename (pathname
, command
, dot_found_in_search
, 1);
4166 user_command_matches (name
, flags
, state
)
4171 int path_index
, name_len
;
4172 char *path_list
, *path_element
, *match
;
4173 struct stat dotinfo
;
4174 static char **match_list
= NULL
;
4175 static int match_list_size
= 0;
4176 static int match_index
= 0;
4180 /* Create the list of matches. */
4181 if (match_list
== 0)
4183 match_list_size
= 5;
4184 match_list
= (char **)xmalloc (match_list_size
* sizeof(char *));
4187 /* Clear out the old match list. */
4188 for (i
= 0; i
< match_list_size
; i
++)
4191 /* We haven't found any files yet. */
4194 if (absolute_program (name
))
4196 match_list
[0] = find_absolute_program (name
, flags
);
4197 match_list
[1] = (char *)NULL
;
4198 path_list
= (char *)NULL
;
4202 name_len
= strlen (name
);
4203 file_to_lose_on
= (char *)NULL
;
4204 dot_found_in_search
= 0;
4205 stat (".", &dotinfo
);
4206 path_list
= get_string_value ("PATH");
4210 while (path_list
&& path_list
[path_index
])
4212 path_element
= get_next_path_element (path_list
, &path_index
);
4214 if (path_element
== 0)
4217 match
= find_in_path_element (name
, path_element
, flags
, name_len
, &dotinfo
);
4219 free (path_element
);
4224 if (match_index
+ 1 == match_list_size
)
4226 match_list_size
+= 10;
4227 match_list
= (char **)xrealloc (match_list
, (match_list_size
+ 1) * sizeof (char *));
4230 match_list
[match_index
++] = match
;
4231 match_list
[match_index
] = (char *)NULL
;
4232 FREE (file_to_lose_on
);
4233 file_to_lose_on
= (char *)NULL
;
4236 /* We haven't returned any strings yet. */
4240 match
= match_list
[match_index
];
4248 /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
4249 This allocates new memory and returns it. */
4251 make_full_pathname (path
, name
, name_len
)
4258 path_len
= strlen (path
);
4259 full_path
= xmalloc (2 + path_len
+ name_len
);
4260 strcpy (full_path
, path
);
4261 full_path
[path_len
] = '/';
4262 strcpy (full_path
+ path_len
+ 1, name
);
4267 find_absolute_program (name
, flags
)
4273 st
= file_status (name
);
4275 /* If the file doesn't exist, quit now. */
4276 if ((st
& FS_EXISTS
) == 0)
4277 return ((char *)NULL
);
4279 /* If we only care about whether the file exists or not, return
4280 this filename. Otherwise, maybe we care about whether this
4281 file is executable. If it is, and that is what we want, return it. */
4282 if ((flags
& FS_EXISTS
) || ((flags
& FS_EXEC_ONLY
) && (st
& FS_EXECABLE
)))
4283 return (savestring (name
));
4285 return ((char *)NULL
);
4289 find_in_path_element (name
, path
, flags
, name_len
, dotinfop
)
4291 int flags
, name_len
;
4292 struct stat
*dotinfop
;
4295 char *full_path
, *xpath
;
4297 xpath
= (*path
== '~') ? bash_tilde_expand (path
) : path
;
4299 /* Remember the location of "." in the path, in all its forms
4300 (as long as they begin with a `.', e.g. `./.') */
4301 if (dot_found_in_search
== 0 && *xpath
== '.')
4302 dot_found_in_search
= same_file (".", xpath
, dotinfop
, (struct stat
*)NULL
);
4304 full_path
= make_full_pathname (xpath
, name
, name_len
);
4306 status
= file_status (full_path
);
4311 if ((status
& FS_EXISTS
) == 0)
4314 return ((char *)NULL
);
4317 /* The file exists. If the caller simply wants the first file, here it is. */
4318 if (flags
& FS_EXISTS
)
4321 /* If the file is executable, then it satisfies the cases of
4322 EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */
4323 if ((status
& FS_EXECABLE
) &&
4324 (((flags
& FS_NODIRS
) == 0) || ((status
& FS_DIRECTORY
) == 0)))
4326 FREE (file_to_lose_on
);
4327 file_to_lose_on
= (char *)NULL
;
4331 /* The file is not executable, but it does exist. If we prefer
4332 an executable, then remember this one if it is the first one
4334 if ((flags
& FS_EXEC_PREFERRED
) && file_to_lose_on
== 0)
4335 file_to_lose_on
= savestring (full_path
);
4337 /* If we want only executable files, or we don't want directories and
4338 this file is a directory, fail. */
4339 if ((flags
& FS_EXEC_ONLY
) || (flags
& FS_EXEC_PREFERRED
) ||
4340 ((flags
& FS_NODIRS
) && (status
& FS_DIRECTORY
)))
4343 return ((char *)NULL
);
4349 /* This does the dirty work for find_user_command_internal () and
4350 user_command_matches ().
4351 NAME is the name of the file to search for.
4352 PATH_LIST is a colon separated list of directories to search.
4353 FLAGS contains bit fields which control the files which are eligible.
4355 FS_EXEC_ONLY: The file must be an executable to be found.
4356 FS_EXEC_PREFERRED: If we can't find an executable, then the
4357 the first file matching NAME will do.
4358 FS_EXISTS: The first file found will do.
4359 FS_NODIRS: Don't find any directories.
4362 find_user_command_in_path (name
, path_list
, flags
)
4367 char *full_path
, *path
;
4368 int path_index
, name_len
;
4369 struct stat dotinfo
;
4371 /* We haven't started looking, so we certainly haven't seen
4372 a `.' as the directory path yet. */
4373 dot_found_in_search
= 0;
4375 if (absolute_program (name
))
4377 full_path
= find_absolute_program (name
, flags
);
4381 if (path_list
== 0 || *path_list
== '\0')
4382 return (savestring (name
)); /* XXX */
4384 file_to_lose_on
= (char *)NULL
;
4385 name_len
= strlen (name
);
4386 stat (".", &dotinfo
);
4389 while (path_list
[path_index
])
4391 /* Allow the user to interrupt out of a lengthy path search. */
4394 path
= get_next_path_element (path_list
, &path_index
);
4398 /* Side effects: sets dot_found_in_search, possibly sets
4400 full_path
= find_in_path_element (name
, path
, flags
, name_len
, &dotinfo
);
4403 /* This should really be in find_in_path_element, but there isn't the
4404 right combination of flags. */
4405 if (full_path
&& is_directory (full_path
))
4413 FREE (file_to_lose_on
);
4418 /* We didn't find exactly what the user was looking for. Return
4419 the contents of FILE_TO_LOSE_ON which is NULL when the search
4420 required an executable, or non-NULL if a file was found and the
4421 search would accept a non-executable as a last resort. */
4422 return (file_to_lose_on
);