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 we're timing the command, however, we cannot do this
593 if (user_subshell
&& command
->type
== cm_simple
)
595 if (user_subshell
&& command
->type
== cm_simple
&& (command
->flags
& CMD_TIME_PIPELINE
) == 0)
598 command
->flags
|= CMD_NO_FORK
;
599 command
->value
.Simple
->flags
|= CMD_NO_FORK
;
602 /* If we're inside a function while executing this subshell, we
603 need to handle a possible `return'. */
605 if (return_catch_flag
)
606 function_value
= setjmp (return_catch
);
609 return_code
= return_catch_value
;
611 return_code
= execute_command_internal
612 (command
, asynchronous
, NO_PIPE
, NO_PIPE
, fds_to_close
);
614 /* If we were explicitly placed in a subshell with (), we need
615 to do the `shell cleanup' things, such as running traps[0]. */
616 if (user_subshell
&& signal_is_trapped (0))
618 last_command_exit_value
= return_code
;
619 return_code
= run_exit_trap ();
626 close_pipes (pipe_in
, pipe_out
);
628 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
631 /* If we are part of a pipeline, and not the end of the pipeline,
632 then we should simply return and let the last command in the
633 pipe be waited for. If we are not in a pipeline, or are the
634 last command in the pipeline, then we wait for the subshell
635 and return its exit status as usual. */
636 if (pipe_out
!= NO_PIPE
)
637 return (EXECUTION_SUCCESS
);
639 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
641 if (asynchronous
== 0)
643 last_command_exit_value
= wait_for (paren_pid
);
645 /* If we have to, invert the return value. */
647 return ((last_command_exit_value
== EXECUTION_SUCCESS
)
649 : EXECUTION_SUCCESS
);
651 return (last_command_exit_value
);
655 DESCRIBE_PID (paren_pid
);
657 run_pending_traps ();
659 return (EXECUTION_SUCCESS
);
664 #if defined (COMMAND_TIMING)
665 if (command
->flags
& CMD_TIME_PIPELINE
)
669 command
->flags
|= CMD_FORCE_SUBSHELL
;
670 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
674 exec_result
= time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
675 if (running_trap
== 0)
676 currently_executing_command
= (COMMAND
*)NULL
;
678 return (exec_result
);
680 #endif /* COMMAND_TIMING */
682 if (shell_control_structure (command
->type
) && command
->redirects
)
683 stdin_redir
= stdin_redirects (command
->redirects
);
685 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
687 if (do_redirections (command
->redirects
, 1, 1, 0) != 0)
689 cleanup_redirects (redirection_undo_list
);
690 redirection_undo_list
= (REDIRECT
*)NULL
;
691 dispose_exec_redirects ();
692 return (EXECUTION_FAILURE
);
695 if (redirection_undo_list
)
697 my_undo_list
= (REDIRECT
*)copy_redirects (redirection_undo_list
);
698 dispose_redirects (redirection_undo_list
);
699 redirection_undo_list
= (REDIRECT
*)NULL
;
702 my_undo_list
= (REDIRECT
*)NULL
;
704 if (exec_redirection_undo_list
)
706 exec_undo_list
= (REDIRECT
*)copy_redirects (exec_redirection_undo_list
);
707 dispose_redirects (exec_redirection_undo_list
);
708 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
711 exec_undo_list
= (REDIRECT
*)NULL
;
713 if (my_undo_list
|| exec_undo_list
)
714 begin_unwind_frame ("loop_redirections");
717 add_unwind_protect ((Function
*)cleanup_redirects
, my_undo_list
);
720 add_unwind_protect ((Function
*)dispose_redirects
, exec_undo_list
);
722 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
726 switch (command
->type
)
730 /* We can't rely on this variable retaining its value across a
731 call to execute_simple_command if a longjmp occurs as the
732 result of a `return' builtin. This is true for sure with gcc. */
733 last_pid
= last_made_pid
;
734 was_debug_trap
= signal_is_trapped (DEBUG_TRAP
) && signal_is_ignored (DEBUG_TRAP
) == 0;
736 if (ignore_return
&& command
->value
.Simple
)
737 command
->value
.Simple
->flags
|= CMD_IGNORE_RETURN
;
738 if (command
->flags
& CMD_STDIN_REDIR
)
739 command
->value
.Simple
->flags
|= CMD_STDIN_REDIR
;
741 execute_simple_command (command
->value
.Simple
, pipe_in
, pipe_out
,
742 asynchronous
, fds_to_close
);
744 /* The temporary environment should be used for only the simple
745 command immediately following its definition. */
746 dispose_used_env_vars ();
748 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
749 /* Reclaim memory allocated with alloca () on machines which
750 may be using the alloca emulation code. */
752 #endif /* (ultrix && mips) || C_ALLOCA */
754 /* If we forked to do the command, then we must wait_for ()
757 /* XXX - this is something to watch out for if there are problems
758 when the shell is compiled without job control. */
759 if (already_making_children
&& pipe_out
== NO_PIPE
&&
760 last_pid
!= last_made_pid
)
762 stop_pipeline (asynchronous
, (COMMAND
*)NULL
);
766 DESCRIBE_PID (last_made_pid
);
769 #if !defined (JOB_CONTROL)
770 /* Do not wait for asynchronous processes started from
772 if (last_made_pid
!= last_asynchronous_pid
)
774 /* When executing a shell function that executes other
775 commands, this causes the last simple command in
776 the function to be waited for twice. */
777 exec_result
= wait_for (last_made_pid
);
784 if (ignore_return
== 0 && invert
== 0 &&
785 ((posixly_correct
&& interactive
== 0 && special_builtin_failed
) ||
786 (exit_immediately_on_error
&& (exec_result
!= EXECUTION_SUCCESS
))))
788 last_command_exit_value
= exec_result
;
789 run_pending_traps ();
790 jump_to_top_level (EXITPROG
);
797 command
->value
.For
->flags
|= CMD_IGNORE_RETURN
;
798 exec_result
= execute_for_command (command
->value
.For
);
801 #if defined (SELECT_COMMAND)
804 command
->value
.Select
->flags
|= CMD_IGNORE_RETURN
;
805 exec_result
= execute_select_command (command
->value
.Select
);
811 command
->value
.Case
->flags
|= CMD_IGNORE_RETURN
;
812 exec_result
= execute_case_command (command
->value
.Case
);
817 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
818 exec_result
= execute_while_command (command
->value
.While
);
823 command
->value
.While
->flags
|= CMD_IGNORE_RETURN
;
824 exec_result
= execute_until_command (command
->value
.While
);
829 command
->value
.If
->flags
|= CMD_IGNORE_RETURN
;
830 exec_result
= execute_if_command (command
->value
.If
);
835 /* This code can be executed from either of two paths: an explicit
836 '{}' command, or via a function call. If we are executed via a
837 function call, we have already taken care of the function being
838 executed in the background (down there in execute_simple_command ()),
839 and this command should *not* be marked as asynchronous. If we
840 are executing a regular '{}' group command, and asynchronous == 1,
841 we must want to execute the whole command in the background, so we
842 need a subshell, and we want the stuff executed in that subshell
843 (this group command) to be executed in the foreground of that
844 subshell (i.e. there will not be *another* subshell forked).
846 What we do is to force a subshell if asynchronous, and then call
847 execute_command_internal again with asynchronous still set to 1,
848 but with the original group command, so the printed command will
851 The code above that handles forking off subshells will note that
852 both subshell and async are on, and turn off async in the child
853 after forking the subshell (but leave async set in the parent, so
854 the normal call to describe_pid is made). This turning off
855 async is *crucial*; if it is not done, this will fall into an
856 infinite loop of executions through this spot in subshell after
857 subshell until the process limit is exhausted. */
861 command
->flags
|= CMD_FORCE_SUBSHELL
;
863 execute_command_internal (command
, 1, pipe_in
, pipe_out
,
868 if (ignore_return
&& command
->value
.Group
->command
)
869 command
->value
.Group
->command
->flags
|= CMD_IGNORE_RETURN
;
871 execute_command_internal (command
->value
.Group
->command
,
872 asynchronous
, pipe_in
, pipe_out
,
878 exec_result
= execute_connection (command
, asynchronous
,
879 pipe_in
, pipe_out
, fds_to_close
);
882 case cm_function_def
:
883 exec_result
= execute_intern_function (command
->value
.Function_def
->name
,
884 command
->value
.Function_def
->command
);
889 ("execute_command: bad command type `%d'", command
->type
);
894 do_redirections (my_undo_list
, 1, 0, 0);
895 dispose_redirects (my_undo_list
);
899 dispose_redirects (exec_undo_list
);
901 if (my_undo_list
|| exec_undo_list
)
902 discard_unwind_frame ("loop_redirections");
904 /* Invert the return value if we have to */
906 exec_result
= (exec_result
== EXECUTION_SUCCESS
)
910 last_command_exit_value
= exec_result
;
911 run_pending_traps ();
912 if (running_trap
== 0)
913 currently_executing_command
= (COMMAND
*)NULL
;
914 return (last_command_exit_value
);
917 #if defined (COMMAND_TIMING)
918 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
919 static struct timeval
*
920 difftimeval (d
, t1
, t2
)
921 struct timeval
*d
, *t1
, *t2
;
923 d
->tv_sec
= t2
->tv_sec
- t1
->tv_sec
;
924 d
->tv_usec
= t2
->tv_usec
- t1
->tv_usec
;
927 d
->tv_usec
+= 1000000;
929 if (d
->tv_sec
< 0) /* ??? -- BSD/OS does this */
935 static struct timeval
*
936 addtimeval (d
, t1
, t2
)
937 struct timeval
*d
, *t1
, *t2
;
939 d
->tv_sec
= t1
->tv_sec
+ t2
->tv_sec
;
940 d
->tv_usec
= t1
->tv_usec
+ t2
->tv_usec
;
941 if (d
->tv_usec
> 1000000)
943 d
->tv_usec
-= 1000000;
949 /* Do "cpu = ((user + sys) * 10000) / real;" with timevals.
950 Barely-tested code from Deven T. Corzine <deven@ties.org>. */
952 timeval_to_cpu (rt
, ut
, st
)
953 struct timeval
*rt
, *ut
, *st
; /* real, user, sys */
955 struct timeval t1
, t2
;
958 addtimeval (&t1
, ut
, st
);
959 t2
.tv_sec
= rt
->tv_sec
;
960 t2
.tv_usec
= rt
->tv_usec
;
962 for (i
= 0; i
< 6; i
++)
964 if ((t1
.tv_sec
> 99999999) || (t2
.tv_sec
> 99999999))
967 t1
.tv_sec
+= t1
.tv_usec
/ 100000;
969 t1
.tv_usec
%= 1000000;
971 t2
.tv_sec
+= t2
.tv_usec
/ 100000;
973 t2
.tv_usec
%= 1000000;
975 for (i
= 0; i
< 4; i
++)
977 if (t1
.tv_sec
< 100000000)
983 return ((t2
.tv_sec
== 0) ? 0 : t1
.tv_sec
/ t2
.tv_sec
);
985 #endif /* HAVE_GETRUSAGE && HAVE_GETTIMEOFDAY */
987 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
988 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
990 static int precs
[] = { 0, 100, 10, 1 };
992 /* Expand one `%'-prefixed escape sequence from a time format string. */
994 mkfmt (buf
, prec
, lng
, sec
, sec_fraction
)
1007 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1014 abuf
[aind
--] = (min
% 10) + '0';
1018 buf
[ind
++] = abuf
[aind
++];
1022 /* Now add the seconds. */
1025 abuf
[aind
--] = (sec
% 10) + '0';
1029 buf
[ind
++] = abuf
[aind
++];
1031 /* We want to add a decimal point and PREC places after it if PREC is
1032 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1037 for (aind
= 1; aind
<= prec
; aind
++)
1039 buf
[ind
++] = (sec_fraction
/ precs
[aind
]) + '0';
1040 sec_fraction
%= precs
[aind
];
1051 /* Interpret the format string FORMAT, interpolating the following escape
1055 where the optional `prec' is a precision, meaning the number of
1056 characters after the decimal point, the optional `l' means to format
1057 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1058 and the last character is one of
1060 R number of seconds of `real' time
1061 U number of seconds of `user' time
1062 S number of seconds of `system' time
1064 An occurrence of `%%' in the format string is translated to a `%'. The
1065 result is printed to FP, a pointer to a FILE. The other variables are
1066 the seconds and thousandths of a second of real, user, and system time,
1069 print_formatted_time (fp
, format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
)
1073 int rsf
, usf
, ssf
, cpu
;
1076 char *str
, *s
, ts
[32];
1081 len
= strlen (format
);
1082 ssize
= (len
+ 64) - (len
% 64);
1083 str
= xmalloc (ssize
);
1086 for (s
= format
; *s
; s
++)
1088 if (*s
!= '%' || s
[1] == '\0')
1090 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1093 else if (s
[1] == '%')
1096 RESIZE_MALLOCED_BUFFER (str
, sindex
, 1, ssize
, 64);
1099 else if (s
[1] == 'P')
1105 sum_frac
= (cpu
% 100) * 10;
1106 len
= mkfmt (ts
, 2, 0, sum
, sum_frac
);
1107 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1108 strcpy (str
+ sindex
, ts
);
1113 prec
= 3; /* default is three places past the decimal point. */
1114 lng
= 0; /* default is to not use minutes or append `s' */
1116 if (isdigit (*s
)) /* `precision' */
1119 if (prec
> 3) prec
= 3;
1121 if (*s
== 'l') /* `length extender' */
1126 if (*s
== 'R' || *s
== 'E')
1127 len
= mkfmt (ts
, prec
, lng
, rs
, rsf
);
1129 len
= mkfmt (ts
, prec
, lng
, us
, usf
);
1131 len
= mkfmt (ts
, prec
, lng
, ss
, ssf
);
1134 internal_error ("bad format character in time format: %c", *s
);
1138 RESIZE_MALLOCED_BUFFER (str
, sindex
, len
, ssize
, 64);
1139 strcpy (str
+ sindex
, ts
);
1145 fprintf (fp
, "%s\n", str
);
1152 time_command (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1154 int asynchronous
, pipe_in
, pipe_out
;
1155 struct fd_bitmap
*fds_to_close
;
1157 int rv
, posix_time
, old_flags
;
1163 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1164 struct timeval real
, user
, sys
;
1165 struct timeval before
, after
;
1166 struct timezone dtz
;
1167 struct rusage selfb
, selfa
, kidsb
, kidsa
; /* a = after, b = before */
1169 # if defined (HAVE_TIMES)
1170 clock_t tbefore
, tafter
, real
, user
, sys
;
1171 struct tms before
, after
;
1175 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1176 gettimeofday (&before
, &dtz
);
1177 getrusage (RUSAGE_SELF
, &selfb
);
1178 getrusage (RUSAGE_CHILDREN
, &kidsb
);
1180 # if defined (HAVE_TIMES)
1181 tbefore
= times (&before
);
1185 posix_time
= (command
->flags
& CMD_TIME_POSIX
);
1187 old_flags
= command
->flags
;
1188 command
->flags
&= ~(CMD_TIME_PIPELINE
|CMD_TIME_POSIX
);
1189 rv
= execute_command_internal (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1190 command
->flags
= old_flags
;
1192 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1193 gettimeofday (&after
, &dtz
);
1194 getrusage (RUSAGE_SELF
, &selfa
);
1195 getrusage (RUSAGE_CHILDREN
, &kidsa
);
1197 difftimeval (&real
, &before
, &after
);
1198 timeval_to_secs (&real
, &rs
, &rsf
);
1200 addtimeval (&user
, difftimeval(&after
, &selfb
.ru_utime
, &selfa
.ru_utime
),
1201 difftimeval(&before
, &kidsb
.ru_utime
, &kidsa
.ru_utime
));
1202 timeval_to_secs (&user
, &us
, &usf
);
1204 addtimeval (&sys
, difftimeval(&after
, &selfb
.ru_stime
, &selfa
.ru_stime
),
1205 difftimeval(&before
, &kidsb
.ru_stime
, &kidsa
.ru_stime
));
1206 timeval_to_secs (&sys
, &ss
, &ssf
);
1208 cpu
= timeval_to_cpu (&real
, &user
, &sys
);
1210 # if defined (HAVE_TIMES)
1211 tafter
= times (&after
);
1213 real
= tafter
- tbefore
;
1214 clock_t_to_secs (real
, &rs
, &rsf
);
1216 user
= (after
.tms_utime
- before
.tms_utime
) + (after
.tms_cutime
- before
.tms_cutime
);
1217 clock_t_to_secs (user
, &us
, &usf
);
1219 sys
= (after
.tms_stime
- before
.tms_stime
) + (after
.tms_cstime
- before
.tms_cstime
);
1220 clock_t_to_secs (sys
, &ss
, &ssf
);
1222 cpu
= (real
== 0) ? 0 : ((user
+ sys
) * 10000) / real
;
1226 rsf
= usf
= ssf
= cpu
= 0;
1231 time_format
= POSIX_TIMEFORMAT
;
1232 else if ((time_format
= get_string_value ("TIMEFORMAT")) == 0)
1233 time_format
= BASH_TIMEFORMAT
;
1235 if (time_format
&& *time_format
)
1236 print_formatted_time (stderr
, time_format
, rs
, rsf
, us
, usf
, ss
, ssf
, cpu
);
1240 #endif /* COMMAND_TIMING */
1243 execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1245 int asynchronous
, pipe_in
, pipe_out
;
1246 struct fd_bitmap
*fds_to_close
;
1248 int prev
, fildes
[2], new_bitmap_size
, dummyfd
, ignore_return
, exec_result
;
1250 struct fd_bitmap
*fd_bitmap
;
1252 #if defined (JOB_CONTROL)
1254 BLOCK_CHILD (set
, oset
);
1255 #endif /* JOB_CONTROL */
1257 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1262 while (cmd
&& cmd
->type
== cm_connection
&&
1263 cmd
->value
.Connection
&& cmd
->value
.Connection
->connector
== '|')
1265 /* Make a pipeline between the two commands. */
1266 if (pipe (fildes
) < 0)
1268 sys_error ("pipe error");
1269 #if defined (JOB_CONTROL)
1270 terminate_current_pipeline ();
1271 kill_current_pipeline ();
1272 #endif /* JOB_CONTROL */
1273 last_command_exit_value
= EXECUTION_FAILURE
;
1274 /* The unwind-protects installed below will take care
1275 of closing all of the open file descriptors. */
1276 throw_to_top_level ();
1277 return (EXECUTION_FAILURE
); /* XXX */
1280 /* Here is a problem: with the new file close-on-exec
1281 code, the read end of the pipe (fildes[0]) stays open
1282 in the first process, so that process will never get a
1283 SIGPIPE. There is no way to signal the first process
1284 that it should close fildes[0] after forking, so it
1285 remains open. No SIGPIPE is ever sent because there
1286 is still a file descriptor open for reading connected
1287 to the pipe. We take care of that here. This passes
1288 around a bitmap of file descriptors that must be
1289 closed after making a child process in execute_simple_command. */
1291 /* We need fd_bitmap to be at least as big as fildes[0].
1292 If fildes[0] is less than fds_to_close->size, then
1293 use fds_to_close->size. */
1294 new_bitmap_size
= (fildes
[0] < fds_to_close
->size
)
1295 ? fds_to_close
->size
1298 fd_bitmap
= new_fd_bitmap (new_bitmap_size
);
1300 /* Now copy the old information into the new bitmap. */
1301 xbcopy ((char *)fds_to_close
->bitmap
, (char *)fd_bitmap
->bitmap
, fds_to_close
->size
);
1303 /* And mark the pipe file descriptors to be closed. */
1304 fd_bitmap
->bitmap
[fildes
[0]] = 1;
1306 /* In case there are pipe or out-of-processes errors, we
1307 want all these file descriptors to be closed when
1308 unwind-protects are run, and the storage used for the
1309 bitmaps freed up. */
1310 begin_unwind_frame ("pipe-file-descriptors");
1311 add_unwind_protect (dispose_fd_bitmap
, fd_bitmap
);
1312 add_unwind_protect (close_fd_bitmap
, fd_bitmap
);
1314 add_unwind_protect (close
, prev
);
1315 dummyfd
= fildes
[1];
1316 add_unwind_protect (close
, dummyfd
);
1318 #if defined (JOB_CONTROL)
1319 add_unwind_protect (restore_signal_mask
, oset
);
1320 #endif /* JOB_CONTROL */
1322 if (ignore_return
&& cmd
->value
.Connection
->first
)
1323 cmd
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1324 execute_command_internal (cmd
->value
.Connection
->first
, asynchronous
,
1325 prev
, fildes
[1], fd_bitmap
);
1333 dispose_fd_bitmap (fd_bitmap
);
1334 discard_unwind_frame ("pipe-file-descriptors");
1336 cmd
= cmd
->value
.Connection
->second
;
1339 /* Now execute the rightmost command in the pipeline. */
1340 if (ignore_return
&& cmd
)
1341 cmd
->flags
|= CMD_IGNORE_RETURN
;
1342 exec_result
= execute_command_internal (cmd
, asynchronous
, prev
, pipe_out
, fds_to_close
);
1347 #if defined (JOB_CONTROL)
1348 UNBLOCK_CHILD (oset
);
1351 return (exec_result
);
1355 execute_connection (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
)
1357 int asynchronous
, pipe_in
, pipe_out
;
1358 struct fd_bitmap
*fds_to_close
;
1364 COMMAND
*tc
, *second
;
1365 int ignore_return
, exec_result
;
1367 ignore_return
= (command
->flags
& CMD_IGNORE_RETURN
) != 0;
1369 switch (command
->value
.Connection
->connector
)
1371 /* Do the first command asynchronously. */
1373 tc
= command
->value
.Connection
->first
;
1375 return (EXECUTION_SUCCESS
);
1380 tc
->flags
|= CMD_IGNORE_RETURN
;
1381 tc
->flags
|= CMD_AMPERSAND
;
1383 /* If this shell was compiled without job control support, if
1384 the shell is not running interactively, if we are currently
1385 in a subshell via `( xxx )', or if job control is not active
1386 then the standard input for an asynchronous command is
1387 forced to /dev/null. */
1388 #if defined (JOB_CONTROL)
1389 if ((!interactive_shell
|| subshell_environment
|| !job_control
) && !stdin_redir
)
1392 #endif /* JOB_CONTROL */
1395 rd
.filename
= make_bare_word ("/dev/null");
1396 tr
= make_redirection (0, r_inputa_direction
, rd
);
1397 tr
->next
= tc
->redirects
;
1400 tc
->flags
|= CMD_STDIN_REDIR
;
1403 exec_result
= execute_command_internal (tc
, 1, pipe_in
, pipe_out
, fds_to_close
);
1405 if (tc
->flags
& CMD_STDIN_REDIR
)
1408 /* Remove the redirection we added above. It matters,
1409 especially for loops, which call execute_command ()
1410 multiple times with the same command. */
1415 tc
->redirects
= tc
->redirects
->next
;
1417 while (tc
->redirects
&& tc
->redirects
!= rp
);
1419 tl
->next
= (REDIRECT
*)NULL
;
1420 dispose_redirects (tr
);
1422 tc
->flags
&= ~CMD_STDIN_REDIR
;
1425 second
= command
->value
.Connection
->second
;
1429 second
->flags
|= CMD_IGNORE_RETURN
;
1431 exec_result
= execute_command_internal (second
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1436 /* Just call execute command on both sides. */
1440 if (command
->value
.Connection
->first
)
1441 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1442 if (command
->value
.Connection
->second
)
1443 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
1446 execute_command (command
->value
.Connection
->first
);
1448 exec_result
= execute_command_internal (command
->value
.Connection
->second
,
1449 asynchronous
, pipe_in
, pipe_out
,
1454 exec_result
= execute_pipeline (command
, asynchronous
, pipe_in
, pipe_out
, fds_to_close
);
1461 /* If we have something like `a && b &' or `a || b &', run the
1462 && or || stuff in a subshell. Force a subshell and just call
1463 execute_command_internal again. Leave asynchronous on
1464 so that we get a report from the parent shell about the
1466 command
->flags
|= CMD_FORCE_SUBSHELL
;
1467 exec_result
= execute_command_internal (command
, 1, pipe_in
, pipe_out
, fds_to_close
);
1471 /* Execute the first command. If the result of that is successful
1472 and the connector is AND_AND, or the result is not successful
1473 and the connector is OR_OR, then execute the second command,
1474 otherwise return. */
1476 if (command
->value
.Connection
->first
)
1477 command
->value
.Connection
->first
->flags
|= CMD_IGNORE_RETURN
;
1479 exec_result
= execute_command (command
->value
.Connection
->first
);
1481 if (((command
->value
.Connection
->connector
== AND_AND
) &&
1482 (exec_result
== EXECUTION_SUCCESS
)) ||
1483 ((command
->value
.Connection
->connector
== OR_OR
) &&
1484 (exec_result
!= EXECUTION_SUCCESS
)))
1486 if (ignore_return
&& command
->value
.Connection
->second
)
1487 command
->value
.Connection
->second
->flags
|= CMD_IGNORE_RETURN
;
1489 exec_result
= execute_command (command
->value
.Connection
->second
);
1494 programming_error ("execute_connection: bad connector `%d'", command
->value
.Connection
->connector
);
1495 jump_to_top_level (DISCARD
);
1496 exec_result
= EXECUTION_FAILURE
;
1502 #if defined (JOB_CONTROL)
1506 if (!interactive_shell) \
1507 reap_dead_jobs (); \
1510 #else /* !JOB_CONTROL */
1514 if (!interactive_shell) \
1515 cleanup_dead_jobs (); \
1518 #endif /* !JOB_CONTROL */
1521 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1524 execute_for_command (for_command
)
1525 FOR_COM
*for_command
;
1527 register WORD_LIST
*releaser
, *list
;
1532 SHELL_VAR
*old_value
= (SHELL_VAR
*)NULL
; /* Remember the old value of x. */
1535 if (check_identifier (for_command
->name
, 1) == 0)
1537 if (posixly_correct
&& interactive_shell
== 0)
1539 last_command_exit_value
= EX_USAGE
;
1540 jump_to_top_level (EXITPROG
);
1542 return (EXECUTION_FAILURE
);
1546 identifier
= for_command
->name
->word
;
1548 list
= releaser
= expand_words_no_vars (for_command
->map_list
);
1550 begin_unwind_frame ("for");
1551 add_unwind_protect (dispose_words
, releaser
);
1554 if (lexical_scoping
)
1556 old_value
= copy_variable (find_variable (identifier
));
1558 add_unwind_protect (dispose_variable
, old_value
);
1562 if (for_command
->flags
& CMD_IGNORE_RETURN
)
1563 for_command
->action
->flags
|= CMD_IGNORE_RETURN
;
1565 for (retval
= EXECUTION_SUCCESS
; list
; list
= list
->next
)
1568 this_command_name
= (char *)NULL
;
1569 v
= bind_variable (identifier
, list
->word
->word
);
1572 if (interactive_shell
== 0 && posixly_correct
)
1574 last_command_exit_value
= EXECUTION_FAILURE
;
1575 jump_to_top_level (FORCE_EOF
);
1579 run_unwind_frame ("for");
1581 return (EXECUTION_FAILURE
);
1584 retval
= execute_command (for_command
->action
);
1605 if (lexical_scoping
)
1608 makunbound (identifier
, shell_variables
);
1611 SHELL_VAR
*new_value
;
1613 new_value
= bind_variable (identifier
, value_cell(old_value
));
1614 new_value
->attributes
= old_value
->attributes
;
1615 dispose_variable (old_value
);
1620 dispose_words (releaser
);
1621 discard_unwind_frame ("for");
1625 #if defined (SELECT_COMMAND)
1626 static int LINES
, COLS
, tabsize
;
1628 #define RP_SPACE ") "
1629 #define RP_SPACE_LEN 2
1631 /* XXX - does not handle numbers > 1000000 at all. */
1632 #define NUMBER_LEN(s) \
1636 : ((s < 10000) ? 4 \
1637 : ((s < 100000) ? 5 \
1641 print_index_and_element (len
, ind
, list
)
1645 register WORD_LIST
*l
;
1650 for (i
= ind
, l
= list
; l
&& --i
; l
= l
->next
)
1652 fprintf (stderr
, "%*d%s%s", len
, ind
, RP_SPACE
, l
->word
->word
);
1653 return (STRLEN (l
->word
->word
));
1662 if ((to
/ tabsize
) > (from
/ tabsize
))
1664 putc ('\t', stderr
);
1665 from
+= tabsize
- from
% tabsize
;
1676 print_select_list (list
, list_len
, max_elem_len
, indices_len
)
1678 int list_len
, max_elem_len
, indices_len
;
1680 int ind
, row
, elem_len
, pos
, cols
, rows
;
1681 int first_column_indices_len
, other_indices_len
;
1685 putc ('\n', stderr
);
1689 cols
= max_elem_len
? COLS
/ max_elem_len
: 1;
1692 rows
= list_len
? list_len
/ cols
+ (list_len
% cols
!= 0) : 1;
1693 cols
= list_len
? list_len
/ rows
+ (list_len
% rows
!= 0) : 1;
1701 first_column_indices_len
= NUMBER_LEN (rows
);
1702 other_indices_len
= indices_len
;
1704 for (row
= 0; row
< rows
; row
++)
1710 indices_len
= (pos
== 0) ? first_column_indices_len
: other_indices_len
;
1711 elem_len
= print_index_and_element (indices_len
, ind
+ 1, list
);
1712 elem_len
+= indices_len
+ RP_SPACE_LEN
;
1714 if (ind
>= list_len
)
1716 indent (pos
+ elem_len
, pos
+ max_elem_len
);
1717 pos
+= max_elem_len
;
1719 putc ('\n', stderr
);
1723 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1724 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1725 If the number is between 1 and LIST_LEN, return that selection. If EOF
1726 is read, return a null string. If a blank line is entered, or an invalid
1727 number is entered, the loop is executed again. */
1729 select_query (list
, list_len
, prompt
)
1734 int max_elem_len
, indices_len
, len
;
1737 char *repl_string
, *t
;
1739 t
= get_string_value ("LINES");
1740 LINES
= (t
&& *t
) ? atoi (t
) : 24;
1741 t
= get_string_value ("COLUMNS");
1742 COLS
= (t
&& *t
) ? atoi (t
) : 80;
1745 t
= get_string_value ("TABSIZE");
1746 tabsize
= (t
&& *t
) ? atoi (t
) : 8;
1754 for (l
= list
; l
; l
= l
->next
)
1756 len
= STRLEN (l
->word
->word
);
1757 if (len
> max_elem_len
)
1760 indices_len
= NUMBER_LEN (list_len
);
1761 max_elem_len
+= indices_len
+ RP_SPACE_LEN
+ 2;
1765 print_select_list (list
, list_len
, max_elem_len
, indices_len
);
1766 fprintf (stderr
, "%s", prompt
);
1770 if (read_builtin ((WORD_LIST
*)NULL
) == EXECUTION_FAILURE
)
1773 return ((char *)NULL
);
1775 repl_string
= get_string_value ("REPLY");
1776 if (*repl_string
== 0)
1778 if (legal_number (repl_string
, &reply
) == 0)
1780 if (reply
< 1 || reply
> list_len
)
1783 for (l
= list
; l
&& --reply
; l
= l
->next
)
1785 return (l
->word
->word
);
1789 /* Execute a SELECT command. The syntax is:
1790 SELECT word IN list DO command_list DONE
1791 Only `break' or `return' in command_list will terminate
1794 execute_select_command (select_command
)
1795 SELECT_COM
*select_command
;
1797 WORD_LIST
*releaser
, *list
;
1799 char *identifier
, *ps3_prompt
, *selection
;
1800 int retval
, list_len
, return_val
;
1802 if (check_identifier (select_command
->name
, 1) == 0)
1803 return (EXECUTION_FAILURE
);
1806 identifier
= select_command
->name
->word
;
1808 /* command and arithmetic substitution, parameter and variable expansion,
1809 word splitting, pathname expansion, and quote removal. */
1810 list
= releaser
= expand_words_no_vars (select_command
->map_list
);
1811 list_len
= list_length (list
);
1812 if (list
== 0 || list_len
== 0)
1815 dispose_words (list
);
1816 return (EXECUTION_SUCCESS
);
1819 begin_unwind_frame ("select");
1820 add_unwind_protect (dispose_words
, releaser
);
1822 if (select_command
->flags
& CMD_IGNORE_RETURN
)
1823 select_command
->action
->flags
|= CMD_IGNORE_RETURN
;
1825 retval
= EXECUTION_SUCCESS
;
1827 unwind_protect_int (return_catch_flag
);
1828 unwind_protect_jmp_buf (return_catch
);
1829 return_catch_flag
++;
1833 ps3_prompt
= get_string_value ("PS3");
1834 if (ps3_prompt
== 0)
1838 selection
= select_query (list
, list_len
, ps3_prompt
);
1843 v
= bind_variable (identifier
, selection
);
1846 if (interactive_shell
== 0 && posixly_correct
)
1848 last_command_exit_value
= EXECUTION_FAILURE
;
1849 jump_to_top_level (FORCE_EOF
);
1853 run_unwind_frame ("select");
1854 return (EXECUTION_FAILURE
);
1858 return_val
= setjmp (return_catch
);
1862 retval
= return_catch_value
;
1866 retval
= execute_command (select_command
->action
);
1880 run_unwind_frame ("select");
1883 #endif /* SELECT_COMMAND */
1885 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1886 The pattern_list is a linked list of pattern clauses; each clause contains
1887 some patterns to compare word_desc against, and an associated command to
1890 execute_case_command (case_command
)
1891 CASE_COM
*case_command
;
1893 register WORD_LIST
*list
;
1894 WORD_LIST
*wlist
, *es
;
1895 PATTERN_LIST
*clauses
;
1896 char *word
, *pattern
;
1897 int retval
, match
, ignore_return
;
1899 /* Posix.2 specifies that the WORD is tilde expanded. */
1900 if (member ('~', case_command
->word
->word
))
1902 word
= bash_tilde_expand (case_command
->word
->word
);
1903 free (case_command
->word
->word
);
1904 case_command
->word
->word
= word
;
1907 wlist
= expand_word_no_split (case_command
->word
, 0);
1908 word
= wlist
? string_list (wlist
) : savestring ("");
1909 dispose_words (wlist
);
1911 retval
= EXECUTION_SUCCESS
;
1912 ignore_return
= case_command
->flags
& CMD_IGNORE_RETURN
;
1914 begin_unwind_frame ("case");
1915 add_unwind_protect ((Function
*)xfree
, word
);
1917 #define EXIT_CASE() goto exit_case_command
1919 for (clauses
= case_command
->clauses
; clauses
; clauses
= clauses
->next
)
1922 for (list
= clauses
->patterns
; list
; list
= list
->next
)
1924 /* Posix.2 specifies to tilde expand each member of the pattern
1926 if (member ('~', list
->word
->word
))
1928 pattern
= bash_tilde_expand (list
->word
->word
);
1929 free (list
->word
->word
);
1930 list
->word
->word
= pattern
;
1933 es
= expand_word_leave_quoted (list
->word
, 0);
1935 if (es
&& es
->word
&& es
->word
->word
&& *(es
->word
->word
))
1936 pattern
= quote_string_for_globbing (es
->word
->word
, 1);
1939 pattern
= xmalloc (1);
1943 /* Since the pattern does not undergo quote removal (as per
1944 Posix.2, section 3.9.4.3), the fnmatch () call must be able
1945 to recognize backslashes as escape characters. */
1946 match
= fnmatch (pattern
, word
, 0) != FNM_NOMATCH
;
1953 if (clauses
->action
&& ignore_return
)
1954 clauses
->action
->flags
|= CMD_IGNORE_RETURN
;
1955 retval
= execute_command (clauses
->action
);
1965 discard_unwind_frame ("case");
1972 /* The WHILE command. Syntax: WHILE test DO action; DONE.
1973 Repeatedly execute action while executing test produces
1974 EXECUTION_SUCCESS. */
1976 execute_while_command (while_command
)
1977 WHILE_COM
*while_command
;
1979 return (execute_while_or_until (while_command
, CMD_WHILE
));
1982 /* UNTIL is just like WHILE except that the test result is negated. */
1984 execute_until_command (while_command
)
1985 WHILE_COM
*while_command
;
1987 return (execute_while_or_until (while_command
, CMD_UNTIL
));
1990 /* The body for both while and until. The only difference between the
1991 two is that the test value is treated differently. TYPE is
1992 CMD_WHILE or CMD_UNTIL. The return value for both commands should
1993 be EXECUTION_SUCCESS if no commands in the body are executed, and
1994 the status of the last command executed in the body otherwise. */
1996 execute_while_or_until (while_command
, type
)
1997 WHILE_COM
*while_command
;
2000 int return_value
, body_status
;
2002 body_status
= EXECUTION_SUCCESS
;
2005 while_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2006 if (while_command
->flags
& CMD_IGNORE_RETURN
)
2007 while_command
->action
->flags
|= CMD_IGNORE_RETURN
;
2011 return_value
= execute_command (while_command
->test
);
2014 if (type
== CMD_WHILE
&& return_value
!= EXECUTION_SUCCESS
)
2016 if (type
== CMD_UNTIL
&& return_value
== EXECUTION_SUCCESS
)
2020 body_status
= execute_command (while_command
->action
);
2038 return (body_status
);
2041 /* IF test THEN command [ELSE command].
2042 IF also allows ELIF in the place of ELSE IF, but
2043 the parser makes *that* stupidity transparent. */
2045 execute_if_command (if_command
)
2050 if_command
->test
->flags
|= CMD_IGNORE_RETURN
;
2051 return_value
= execute_command (if_command
->test
);
2053 if (return_value
== EXECUTION_SUCCESS
)
2057 if (if_command
->true_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2058 if_command
->true_case
->flags
|= CMD_IGNORE_RETURN
;
2060 return (execute_command (if_command
->true_case
));
2066 if (if_command
->false_case
&& (if_command
->flags
& CMD_IGNORE_RETURN
))
2067 if_command
->false_case
->flags
|= CMD_IGNORE_RETURN
;
2069 return (execute_command (if_command
->false_case
));
2081 var
= bind_variable ("_", arg
);
2082 var
->attributes
&= ~att_exported
;
2085 /* Execute a null command. Fork a subshell if the command uses pipes or is
2086 to be run asynchronously. This handles all the side effects that are
2087 supposed to take place. */
2089 execute_null_command (redirects
, pipe_in
, pipe_out
, async
, old_last_command_subst_pid
)
2090 REDIRECT
*redirects
;
2091 int pipe_in
, pipe_out
, async
, old_last_command_subst_pid
;
2093 if (pipe_in
!= NO_PIPE
|| pipe_out
!= NO_PIPE
|| async
)
2095 /* We have a null command, but we really want a subshell to take
2096 care of it. Just fork, do piping and redirections, and exit. */
2097 if (make_child ((char *)NULL
, async
) == 0)
2099 /* Cancel traps, in trap.c. */
2100 restore_original_signals (); /* XXX */
2102 do_piping (pipe_in
, pipe_out
);
2104 subshell_environment
= SUBSHELL_ASYNC
;
2106 if (do_redirections (redirects
, 1, 0, 0) == 0)
2107 exit (EXECUTION_SUCCESS
);
2109 exit (EXECUTION_FAILURE
);
2113 close_pipes (pipe_in
, pipe_out
);
2114 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2115 unlink_fifo_list ();
2117 return (EXECUTION_SUCCESS
);
2122 /* Even if there aren't any command names, pretend to do the
2123 redirections that are specified. The user expects the side
2124 effects to take place. If the redirections fail, then return
2125 failure. Otherwise, if a command substitution took place while
2126 expanding the command or a redirection, return the value of that
2127 substitution. Otherwise, return EXECUTION_SUCCESS. */
2129 if (do_redirections (redirects
, 0, 0, 0) != 0)
2130 return (EXECUTION_FAILURE
);
2131 else if (old_last_command_subst_pid
!= last_command_subst_pid
)
2132 return (last_command_exit_value
);
2134 return (EXECUTION_SUCCESS
);
2138 /* This is a hack to suppress word splitting for assignment statements
2139 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2141 fix_assignment_words (words
)
2150 b
= builtin_address_internal (words
->word
->word
, 0);
2151 if (b
== 0 || (b
->flags
& ASSIGNMENT_BUILTIN
) == 0)
2154 for (w
= words
; w
; w
= w
->next
)
2155 if (w
->word
->flags
& W_ASSIGNMENT
)
2156 w
->word
->flags
|= W_NOSPLIT
;
2159 /* The meaty part of all the executions. We have to start hacking the
2160 real execution of commands here. Fork a process, set things up,
2161 execute the command. */
2163 execute_simple_command (simple_command
, pipe_in
, pipe_out
, async
, fds_to_close
)
2164 SIMPLE_COM
*simple_command
;
2165 int pipe_in
, pipe_out
, async
;
2166 struct fd_bitmap
*fds_to_close
;
2168 WORD_LIST
*words
, *lastword
;
2169 char *command_line
, *lastarg
, *temp
;
2170 int first_word_quoted
, result
, builtin_is_special
;
2171 pid_t old_last_command_subst_pid
;
2175 result
= EXECUTION_SUCCESS
;
2176 special_builtin_failed
= builtin_is_special
= 0;
2178 /* If we're in a function, update the line number information. */
2179 if (variable_context
)
2180 line_number
= simple_command
->line
- function_line_number
;
2182 /* Remember what this command line looks like at invocation. */
2183 command_string_index
= 0;
2184 print_simple_command (simple_command
);
2185 command_line
= xmalloc (1 + strlen (the_printed_command
));
2186 strcpy (command_line
, the_printed_command
); /* XXX memory leak on errors */
2189 simple_command
->words
? (simple_command
->words
->word
->flags
& W_QUOTED
): 0;
2191 old_last_command_subst_pid
= last_command_subst_pid
;
2193 /* If we are re-running this as the result of executing the `command'
2194 builtin, do not expand the command words a second time. */
2195 if ((simple_command
->flags
& CMD_INHIBIT_EXPANSION
) == 0)
2197 current_fds_to_close
= fds_to_close
;
2198 fix_assignment_words (simple_command
->words
);
2199 words
= expand_words (simple_command
->words
);
2200 current_fds_to_close
= (struct fd_bitmap
*)NULL
;
2203 words
= copy_word_list (simple_command
->words
);
2205 /* It is possible for WORDS not to have anything left in it.
2206 Perhaps all the words consisted of `$foo', and there was
2207 no variable `$foo'. */
2210 result
= execute_null_command (simple_command
->redirects
,
2211 pipe_in
, pipe_out
, async
,
2212 old_last_command_subst_pid
);
2213 FREE (command_line
);
2214 bind_lastarg ((char *)NULL
);
2218 lastarg
= (char *)NULL
;
2220 begin_unwind_frame ("simple-command");
2222 if (echo_command_at_execute
)
2223 xtrace_print_word_list (words
);
2225 builtin
= (Function
*)NULL
;
2226 func
= (SHELL_VAR
*)NULL
;
2227 if ((simple_command
->flags
& CMD_NO_FUNCTIONS
) == 0)
2229 /* Posix.2 says special builtins are found before functions. We
2230 don't set builtin_is_special anywhere other than here, because
2231 this path is followed only when the `command' builtin is *not*
2232 being used, and we don't want to exit the shell if a special
2233 builtin executed with `command builtin' fails. `command' is not
2234 a special builtin. */
2235 if (posixly_correct
)
2237 builtin
= find_special_builtin (words
->word
->word
);
2239 builtin_is_special
= 1;
2242 func
= find_function (words
->word
->word
);
2245 add_unwind_protect (dispose_words
, words
);
2248 /* Bind the last word in this command to "$_" after execution. */
2249 for (lastword
= words
; lastword
->next
; lastword
= lastword
->next
)
2251 lastarg
= lastword
->word
->word
;
2253 #if defined (JOB_CONTROL)
2254 /* Is this command a job control related thing? */
2255 if (words
->word
->word
[0] == '%')
2257 this_command_name
= async
? "bg" : "fg";
2258 last_shell_builtin
= this_shell_builtin
;
2259 this_shell_builtin
= builtin_address (this_command_name
);
2260 result
= (*this_shell_builtin
) (words
);
2264 /* One other possiblilty. The user may want to resume an existing job.
2265 If they do, find out whether this word is a candidate for a running
2267 if (job_control
&& async
== 0 &&
2268 !first_word_quoted
&&
2270 words
->word
->word
[0] &&
2271 !simple_command
->redirects
&&
2272 pipe_in
== NO_PIPE
&&
2273 pipe_out
== NO_PIPE
&&
2274 (temp
= get_string_value ("auto_resume")))
2278 int wl
, cl
, exact
, substring
, match
, started_status
;
2279 register PROCESS
*p
;
2281 word
= words
->word
->word
;
2282 exact
= STREQ (temp
, "exact");
2283 substring
= STREQ (temp
, "substring");
2285 for (i
= job_slots
- 1; i
> -1; i
--)
2287 if (jobs
[i
] == 0 || (JOBSTATE (i
) != JSTOPPED
))
2295 cl
= strlen (p
->command
);
2296 match
= STREQN (p
->command
, word
, cl
);
2299 match
= strindex (p
->command
, word
) != (char *)0;
2301 match
= STREQN (p
->command
, word
, wl
);
2309 run_unwind_frame ("simple-command");
2310 this_command_name
= "fg";
2311 last_shell_builtin
= this_shell_builtin
;
2312 this_shell_builtin
= builtin_address ("fg");
2314 started_status
= start_job (i
, 1);
2315 return ((started_status
< 0) ? EXECUTION_FAILURE
: started_status
);
2317 while (p
!= jobs
[i
]->pipe
);
2320 #endif /* JOB_CONTROL */
2322 /* Remember the name of this command globally. */
2323 this_command_name
= words
->word
->word
;
2327 /* This command could be a shell builtin or a user-defined function.
2328 We have already found special builtins by this time, so we do not
2329 set builtin_is_special. If this is a function or builtin, and we
2330 have pipes, then fork a subshell in here. Otherwise, just execute
2331 the command directly. */
2332 if (func
== 0 && builtin
== 0)
2333 builtin
= find_shell_builtin (this_command_name
);
2335 last_shell_builtin
= this_shell_builtin
;
2336 this_shell_builtin
= builtin
;
2338 if (builtin
|| func
)
2340 if ((pipe_in
!= NO_PIPE
) || (pipe_out
!= NO_PIPE
) || async
)
2342 if (make_child (command_line
, async
) == 0)
2344 /* reset_terminating_signals (); */ /* XXX */
2345 /* Cancel traps, in trap.c. */
2346 restore_original_signals ();
2350 if ((simple_command
->flags
& CMD_STDIN_REDIR
) &&
2351 pipe_in
== NO_PIPE
&&
2352 (stdin_redirects (simple_command
->redirects
) == 0))
2353 async_redirect_stdin ();
2354 setup_async_signals ();
2357 execute_subshell_builtin_or_function
2358 (words
, simple_command
->redirects
, builtin
, func
,
2359 pipe_in
, pipe_out
, async
, fds_to_close
,
2360 simple_command
->flags
);
2364 close_pipes (pipe_in
, pipe_out
);
2365 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2366 unlink_fifo_list ();
2368 command_line
= (char *)NULL
; /* don't free this. */
2374 result
= execute_builtin_or_function
2375 (words
, builtin
, func
, simple_command
->redirects
, fds_to_close
,
2376 simple_command
->flags
);
2379 if (result
> EX_SHERRBASE
)
2381 result
= builtin_status (result
);
2382 if (builtin_is_special
)
2383 special_builtin_failed
= 1;
2385 /* In POSIX mode, if there are assignment statements preceding
2386 a special builtin, they persist after the builtin
2388 if (posixly_correct
&& builtin_is_special
&& temporary_env
)
2389 merge_temporary_env ();
2393 if (result
== EX_USAGE
)
2394 result
= EX_BADUSAGE
;
2395 else if (result
> EX_SHERRBASE
)
2396 result
= EXECUTION_FAILURE
;
2403 execute_disk_command (words
, simple_command
->redirects
, command_line
,
2404 pipe_in
, pipe_out
, async
, fds_to_close
,
2405 simple_command
->flags
);
2408 bind_lastarg (lastarg
);
2409 FREE (command_line
);
2410 run_unwind_frame ("simple-command");
2414 /* Translate the special builtin exit statuses. We don't really need a
2415 function for this; it's a placeholder for future work. */
2417 builtin_status (result
)
2431 r
= EXECUTION_FAILURE
;
2434 r
= EXECUTION_SUCCESS
;
2441 execute_builtin (builtin
, words
, flags
, subshell
)
2444 int flags
, subshell
;
2446 int old_e_flag
, result
, eval_unwind
;
2448 old_e_flag
= exit_immediately_on_error
;
2449 /* The eval builtin calls parse_and_execute, which does not know about
2450 the setting of flags, and always calls the execution functions with
2451 flags that will exit the shell on an error if -e is set. If the
2452 eval builtin is being called, and we're supposed to ignore the exit
2453 value of the command, we turn the -e flag off ourselves, then
2454 restore it when the command completes. */
2455 if (subshell
== 0 && builtin
== eval_builtin
&& (flags
& CMD_IGNORE_RETURN
))
2457 begin_unwind_frame ("eval_builtin");
2458 unwind_protect_int (exit_immediately_on_error
);
2459 exit_immediately_on_error
= 0;
2465 /* The temporary environment for a builtin is supposed to apply to
2466 all commands executed by that builtin. Currently, this is a
2467 problem only with the `source' and `eval' builtins. */
2468 if (builtin
== source_builtin
|| builtin
== eval_builtin
)
2471 begin_unwind_frame ("builtin_env");
2475 builtin_env
= copy_array (temporary_env
);
2477 add_unwind_protect (dispose_builtin_env
, (char *)NULL
);
2478 dispose_used_env_vars ();
2482 builtin_env
= (char **)NULL
;
2486 result
= ((*builtin
) (words
->next
));
2488 if (subshell
== 0 && (builtin
== source_builtin
|| builtin
== eval_builtin
))
2490 /* In POSIX mode, if any variable assignments precede the `.' or
2491 `eval' builtin, they persist after the builtin completes, since `.'
2492 and `eval' are special builtins. */
2493 if (posixly_correct
&& builtin_env
)
2494 merge_builtin_env ();
2495 dispose_builtin_env ();
2496 discard_unwind_frame ("builtin_env");
2501 exit_immediately_on_error
+= old_e_flag
;
2502 discard_unwind_frame ("eval_builtin");
2509 execute_function (var
, words
, flags
, fds_to_close
, async
, subshell
)
2512 int flags
, subshell
, async
;
2513 struct fd_bitmap
*fds_to_close
;
2515 int return_val
, result
;
2519 tc
= (COMMAND
*)copy_command (function_cell (var
));
2520 if (tc
&& (flags
& CMD_IGNORE_RETURN
))
2521 tc
->flags
|= CMD_IGNORE_RETURN
;
2525 begin_unwind_frame ("function_calling");
2527 add_unwind_protect (pop_context
, (char *)NULL
);
2528 unwind_protect_int (line_number
);
2529 unwind_protect_int (return_catch_flag
);
2530 unwind_protect_jmp_buf (return_catch
);
2531 add_unwind_protect (dispose_command
, (char *)tc
);
2532 unwind_protect_int (loop_level
);
2535 debug_trap
= (signal_is_trapped (DEBUG_TRAP
) && signal_is_ignored (DEBUG_TRAP
) == 0)
2536 ? trap_list
[DEBUG_TRAP
]
2542 debug_trap
= savestring (debug_trap
);
2543 add_unwind_protect (set_debug_trap
, debug_trap
);
2544 /* XXX - small memory leak here -- hard to fix */
2546 restore_default_signal (DEBUG_TRAP
);
2549 /* The temporary environment for a function is supposed to apply to
2550 all commands executed within the function body. */
2553 function_env
= copy_array (temporary_env
);
2555 add_unwind_protect (dispose_function_env
, (char *)NULL
);
2556 dispose_used_env_vars ();
2560 function_env
= (char **)NULL
;
2563 remember_args (words
->next
, 1);
2565 /* Number of the line on which the function body starts. */
2566 line_number
= function_line_number
= tc
->line
;
2570 #if defined (JOB_CONTROL)
2571 stop_pipeline (async
, (COMMAND
*)NULL
);
2573 fc
= (tc
->type
== cm_group
) ? tc
->value
.Group
->command
: tc
;
2575 if (fc
&& (flags
& CMD_IGNORE_RETURN
))
2576 fc
->flags
|= CMD_IGNORE_RETURN
;
2583 return_catch_flag
++;
2584 return_val
= setjmp (return_catch
);
2587 result
= return_catch_value
;
2589 result
= execute_command_internal (fc
, 0, NO_PIPE
, NO_PIPE
, fds_to_close
);
2592 run_unwind_frame ("function_calling");
2597 /* Execute a shell builtin or function in a subshell environment. This
2598 routine does not return; it only calls exit(). If BUILTIN is non-null,
2599 it points to a function to call to execute a shell builtin; otherwise
2600 VAR points at the body of a function to execute. WORDS is the arguments
2601 to the command, REDIRECTS specifies redirections to perform before the
2602 command is executed. */
2604 execute_subshell_builtin_or_function (words
, redirects
, builtin
, var
,
2605 pipe_in
, pipe_out
, async
, fds_to_close
,
2608 REDIRECT
*redirects
;
2611 int pipe_in
, pipe_out
, async
;
2612 struct fd_bitmap
*fds_to_close
;
2617 /* A subshell is neither a login shell nor interactive. */
2618 login_shell
= interactive
= 0;
2620 subshell_environment
= SUBSHELL_ASYNC
;
2622 maybe_make_export_env (); /* XXX - is this needed? */
2624 #if defined (JOB_CONTROL)
2625 /* Eradicate all traces of job control after we fork the subshell, so
2626 all jobs begun by this subshell are in the same process group as
2627 the shell itself. */
2629 /* Allow the output of `jobs' to be piped. */
2630 if (builtin
== jobs_builtin
&& !async
&&
2631 (pipe_out
!= NO_PIPE
|| pipe_in
!= NO_PIPE
))
2632 kill_current_pipeline ();
2634 without_job_control ();
2636 set_sigchld_handler ();
2637 #endif /* JOB_CONTROL */
2639 set_sigint_handler ();
2641 do_piping (pipe_in
, pipe_out
);
2644 close_fd_bitmap (fds_to_close
);
2646 if (do_redirections (redirects
, 1, 0, 0) != 0)
2647 exit (EXECUTION_FAILURE
);
2651 /* Give builtins a place to jump back to on failure,
2652 so we don't go back up to main(). */
2653 result
= setjmp (top_level
);
2655 if (result
== EXITPROG
)
2656 exit (last_command_exit_value
);
2658 exit (EXECUTION_FAILURE
);
2661 r
= execute_builtin (builtin
, words
, flags
, 1);
2668 exit (execute_function (var
, words
, flags
, fds_to_close
, async
, 1));
2671 /* Execute a builtin or function in the current shell context. If BUILTIN
2672 is non-null, it is the builtin command to execute, otherwise VAR points
2673 to the body of a function. WORDS are the command's arguments, REDIRECTS
2674 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2675 file descriptors to close.
2677 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2678 not undone before this function returns. */
2680 execute_builtin_or_function (words
, builtin
, var
, redirects
,
2681 fds_to_close
, flags
)
2685 REDIRECT
*redirects
;
2686 struct fd_bitmap
*fds_to_close
;
2690 REDIRECT
*saved_undo_list
;
2692 if (do_redirections (redirects
, 1, 1, 0) != 0)
2694 cleanup_redirects (redirection_undo_list
);
2695 redirection_undo_list
= (REDIRECT
*)NULL
;
2696 dispose_exec_redirects ();
2697 return (EX_REDIRFAIL
); /* was EXECUTION_FAILURE */
2700 saved_undo_list
= redirection_undo_list
;
2702 /* Calling the "exec" builtin changes redirections forever. */
2703 if (builtin
== exec_builtin
)
2705 dispose_redirects (saved_undo_list
);
2706 saved_undo_list
= exec_redirection_undo_list
;
2707 exec_redirection_undo_list
= (REDIRECT
*)NULL
;
2710 dispose_exec_redirects ();
2712 if (saved_undo_list
)
2714 begin_unwind_frame ("saved redirects");
2715 add_unwind_protect (cleanup_redirects
, (char *)saved_undo_list
);
2718 redirection_undo_list
= (REDIRECT
*)NULL
;
2721 result
= execute_builtin (builtin
, words
, flags
, 0);
2723 result
= execute_function (var
, words
, flags
, fds_to_close
, 0, 0);
2725 if (saved_undo_list
)
2727 redirection_undo_list
= saved_undo_list
;
2728 discard_unwind_frame ("saved redirects");
2731 if (redirection_undo_list
)
2733 cleanup_redirects (redirection_undo_list
);
2734 redirection_undo_list
= (REDIRECT
*)NULL
;
2741 setup_async_signals ()
2743 #if defined (JOB_CONTROL)
2744 if (job_control
== 0)
2747 set_signal_handler (SIGINT
, SIG_IGN
);
2748 set_signal_ignored (SIGINT
);
2749 set_signal_handler (SIGQUIT
, SIG_IGN
);
2750 set_signal_ignored (SIGQUIT
);
2754 /* Execute a simple command that is hopefully defined in a disk file
2759 3) look up the command
2762 6) If the execve failed, see if the file has executable mode set.
2763 If so, and it isn't a directory, then execute its contents as
2766 Note that the filename hashing stuff has to take place up here,
2767 in the parent. This is probably why the Bourne style shells
2768 don't handle it, since that would require them to go through
2769 this gnarly hair, for no good reason. */
2771 execute_disk_command (words
, redirects
, command_line
, pipe_in
, pipe_out
,
2772 async
, fds_to_close
, cmdflags
)
2774 REDIRECT
*redirects
;
2776 int pipe_in
, pipe_out
, async
;
2777 struct fd_bitmap
*fds_to_close
;
2780 char *pathname
, *command
, **args
;
2784 nofork
= (cmdflags
& CMD_NO_FORK
); /* Don't fork, just exec, if no pipes */
2785 pathname
= words
->word
->word
;
2787 #if defined (RESTRICTED_SHELL)
2788 if (restricted
&& strchr (pathname
, '/'))
2790 internal_error ("%s: restricted: cannot specify `/' in command names",
2792 last_command_exit_value
= EXECUTION_FAILURE
;
2795 #endif /* RESTRICTED_SHELL */
2797 command
= search_for_command (pathname
);
2801 maybe_make_export_env ();
2802 put_command_name_into_env (command
);
2805 /* We have to make the child before we check for the non-existance
2806 of COMMAND, since we want the error messages to be redirected. */
2807 /* If we can get away without forking and there are no pipes to deal with,
2808 don't bother to fork, just directly exec the command. */
2809 if (nofork
&& pipe_in
== NO_PIPE
&& pipe_out
== NO_PIPE
)
2812 pid
= make_child (savestring (command_line
), async
);
2816 int old_interactive
;
2819 /* This has been disabled for the time being. */
2820 #if !defined (ARG_MAX) || ARG_MAX >= 10240
2821 if (posixly_correct
== 0)
2822 put_gnu_argv_flags_into_env ((int)getpid (), glob_argv_flags
);
2826 /* Cancel traps, in trap.c. */
2827 restore_original_signals ();
2829 /* restore_original_signals may have undone the work done
2830 by make_child to ensure that SIGINT and SIGQUIT are ignored
2831 in asynchronous children. */
2834 if ((cmdflags
& CMD_STDIN_REDIR
) &&
2835 pipe_in
== NO_PIPE
&&
2836 (stdin_redirects (redirects
) == 0))
2837 async_redirect_stdin ();
2838 setup_async_signals ();
2841 do_piping (pipe_in
, pipe_out
);
2845 old_interactive
= interactive
;
2849 subshell_environment
= SUBSHELL_FORK
;
2851 /* This functionality is now provided by close-on-exec of the
2852 file descriptors manipulated by redirection and piping.
2853 Some file descriptors still need to be closed in all children
2854 because of the way bash does pipes; fds_to_close is a
2855 bitmap of all such file descriptors. */
2857 close_fd_bitmap (fds_to_close
);
2859 if (redirects
&& (do_redirections (redirects
, 1, 0, 0) != 0))
2861 #if defined (PROCESS_SUBSTITUTION)
2862 /* Try to remove named pipes that may have been created as the
2863 result of redirections. */
2864 unlink_fifo_list ();
2865 #endif /* PROCESS_SUBSTITUTION */
2866 exit (EXECUTION_FAILURE
);
2870 interactive
= old_interactive
;
2874 internal_error ("%s: command not found", pathname
);
2875 exit (EX_NOTFOUND
); /* Posix.2 says the exit status is 127 */
2878 /* Execve expects the command name to be in args[0]. So we
2879 leave it there, in the same format that the user used to
2881 args
= word_list_to_argv (words
, 0, 0, (int *)NULL
);
2882 exit (shell_execve (command
, args
, export_env
));
2886 /* Make sure that the pipes are closed in the parent. */
2887 close_pipes (pipe_in
, pipe_out
);
2888 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2889 unlink_fifo_list ();
2895 #if !defined (HAVE_HASH_BANG_EXEC)
2896 /* If the operating system on which we're running does not handle
2897 the #! executable format, then help out. SAMPLE is the text read
2898 from the file, SAMPLE_LEN characters. COMMAND is the name of
2899 the script; it and ARGS, the arguments given by the user, will
2900 become arguments to the specified interpreter. ENV is the environment
2901 to pass to the interpreter.
2903 The word immediately following the #! is the interpreter to execute.
2904 A single argument to the interpreter is allowed. */
2906 execute_shell_script (sample
, sample_len
, command
, args
, env
)
2907 unsigned char *sample
;
2913 char *execname
, *firstarg
;
2914 int start
, size_increment
, larry
;
2916 /* Find the name of the interpreter to exec. */
2917 for (i
= 2; whitespace (sample
[i
]) && i
< sample_len
; i
++)
2921 !whitespace (sample
[i
]) && sample
[i
] != '\n' && i
< sample_len
;
2926 execname
= xmalloc (1 + larry
);
2927 strncpy (execname
, (char *)(sample
+ start
), larry
);
2928 execname
[larry
] = '\0';
2931 /* Now the argument, if any. */
2932 firstarg
= (char *)NULL
;
2934 whitespace (sample
[i
]) && sample
[i
] != '\n' && i
< sample_len
;
2938 /* If there is more text on the line, then it is an argument for the
2940 if (i
< sample_len
&& sample
[i
] != '\n' && !whitespace (sample
[i
]))
2943 !whitespace (sample
[i
]) && sample
[i
] != '\n' && i
< sample_len
;
2947 firstarg
= xmalloc (1 + larry
);
2948 strncpy (firstarg
, (char *)(sample
+ start
), larry
);
2949 firstarg
[larry
] = '\0';
2954 larry
= array_len (args
) + size_increment
;
2956 args
= (char **)xrealloc ((char *)args
, (1 + larry
) * sizeof (char *));
2958 for (i
= larry
- 1; i
; i
--)
2959 args
[i
] = args
[i
- size_increment
];
2970 args
[larry
] = (char *)NULL
;
2972 return (shell_execve (execname
, args
, env
));
2974 #endif /* !HAVE_HASH_BANG_EXEC */
2977 initialize_subshell ()
2980 /* Forget about any aliases that we knew of. We are in a subshell. */
2981 delete_all_aliases ();
2984 #if defined (HISTORY)
2985 /* Forget about the history lines we have read. This is a non-interactive
2987 history_lines_this_session
= 0;
2990 #if defined (JOB_CONTROL)
2991 /* Forget about the way job control was working. We are in a subshell. */
2992 without_job_control ();
2993 set_sigchld_handler ();
2994 #endif /* JOB_CONTROL */
2996 /* Reset the values of the shell flags and options. */
2997 reset_shell_flags ();
2998 reset_shell_options ();
2999 reset_shopt_options ();
3001 /* If we're not interactive, close the file descriptor from which we're
3002 reading the current shell script. */
3003 #if defined (BUFFERED_INPUT)
3004 if (interactive_shell
== 0 && default_buffered_input
>= 0)
3006 close_buffered_fd (default_buffered_input
);
3007 default_buffered_input
= bash_input
.location
.buffered_fd
= -1;
3010 if (interactive_shell
== 0 && default_input
)
3012 fclose (default_input
);
3013 default_input
= (FILE *)NULL
;
3018 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3019 # define SETOSTYPE(x) __setostype(x)
3021 # define SETOSTYPE(x)
3024 /* Call execve (), handling interpreting shell scripts, and handling
3027 shell_execve (command
, args
, env
)
3034 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3035 execve (command
, args
, env
);
3038 /* If we get to this point, then start checking out the file.
3039 Maybe it is something we can hack ourselves. */
3040 if (errno
!= ENOEXEC
)
3043 if ((stat (command
, &finfo
) == 0) && (S_ISDIR (finfo
.st_mode
)))
3044 internal_error ("%s: is a directory", command
);
3048 file_error (command
);
3050 return ((i
== ENOENT
) ? EX_NOTFOUND
: EX_NOEXEC
); /* XXX Posix.2 says that exit status is 126 */
3053 /* This file is executable.
3054 If it begins with #!, then help out people with losing operating
3055 systems. Otherwise, check to see if it is a binary file by seeing
3056 if the first line (or up to 80 characters) are in the ASCII set.
3057 Execute the contents as shell commands. */
3058 fd
= open (command
, O_RDONLY
);
3061 unsigned char sample
[80];
3064 sample_len
= read (fd
, (char *)sample
, 80);
3067 if (sample_len
== 0)
3068 return (EXECUTION_SUCCESS
);
3070 /* Is this supposed to be an executable script?
3071 If so, the format of the line is "#! interpreter [argument]".
3072 A single argument is allowed. The BSD kernel restricts
3073 the length of the entire line to 32 characters (32 bytes
3074 being the size of the BSD exec header), but we allow 80
3078 #if !defined (HAVE_HASH_BANG_EXEC)
3079 if (sample
[0] == '#' && sample
[1] == '!')
3080 return (execute_shell_script (sample
, sample_len
, command
, args
, env
));
3083 if (check_binary_file (sample
, sample_len
))
3085 internal_error ("%s: cannot execute binary file", command
);
3086 return (EX_BINARY_FILE
);
3091 initialize_subshell ();
3093 set_sigint_handler ();
3095 /* Insert the name of this shell into the argument list. */
3096 larray
= array_len (args
) + 1;
3097 args
= (char **)xrealloc ((char *)args
, (1 + larray
) * sizeof (char *));
3099 for (i
= larray
- 1; i
; i
--)
3100 args
[i
] = args
[i
- 1];
3102 args
[0] = shell_name
;
3104 args
[larray
] = (char *)NULL
;
3106 if (args
[0][0] == '-')
3109 #if defined (RESTRICTED_SHELL)
3111 change_flag ('r', FLAG_OFF
);
3116 /* Can't free subshell_argv[0]; that is shell_name. */
3117 for (i
= 1; i
< subshell_argc
; i
++)
3118 free (subshell_argv
[i
]);
3119 free (subshell_argv
);
3122 dispose_command (currently_executing_command
); /* XXX */
3123 currently_executing_command
= (COMMAND
*)NULL
;
3125 subshell_argc
= larray
;
3126 subshell_argv
= args
;
3127 subshell_envp
= env
;
3129 unbind_args (); /* remove the positional parameters */
3131 longjmp (subshell_top_level
, 1);
3135 execute_intern_function (name
, function
)
3141 if (check_identifier (name
, posixly_correct
) == 0)
3143 if (posixly_correct
&& interactive_shell
== 0)
3145 last_command_exit_value
= EX_USAGE
;
3146 jump_to_top_level (EXITPROG
);
3148 return (EXECUTION_FAILURE
);
3151 var
= find_function (name
->word
);
3152 if (var
&& readonly_p (var
))
3154 internal_error ("%s: readonly function", var
->name
);
3155 return (EXECUTION_FAILURE
);
3158 bind_function (name
->word
, function
);
3159 return (EXECUTION_SUCCESS
);
3162 #if defined (INCLUDE_UNUSED)
3163 #if defined (PROCESS_SUBSTITUTION)
3167 register int i
, fd_table_size
;
3169 fd_table_size
= getdtablesize ();
3170 if (fd_table_size
> 256) /* clamp to a reasonable value */
3171 fd_table_size
= 256;
3173 for (i
= 3; i
< fd_table_size
; i
++)
3176 #endif /* PROCESS_SUBSTITUTION */
3180 close_pipes (in
, out
)
3189 /* Redirect input and output to be from and to the specified pipes.
3190 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3192 do_piping (pipe_in
, pipe_out
)
3193 int pipe_in
, pipe_out
;
3195 if (pipe_in
!= NO_PIPE
)
3197 if (dup2 (pipe_in
, 0) < 0)
3198 sys_error ("cannot duplicate fd %d to fd 0", pipe_in
);
3202 if (pipe_out
!= NO_PIPE
)
3204 if (pipe_out
!= REDIRECT_BOTH
)
3206 if (dup2 (pipe_out
, 1) < 0)
3207 sys_error ("cannot duplicate fd %d to fd 1", pipe_out
);
3208 if (pipe_out
== 0 || pipe_out
> 1)
3212 if (dup2 (1, 2) < 0)
3213 sys_error ("cannot duplicate fd 1 to fd 2");
3218 redirection_error (temp
, error
)
3224 if (expandable_redirection_filename (temp
))
3226 if (posixly_correct
&& !interactive_shell
)
3227 disallow_filename_globbing
++;
3228 filename
= redirection_expand (temp
->redirectee
.filename
);
3229 if (posixly_correct
&& !interactive_shell
)
3230 disallow_filename_globbing
--;
3232 filename
= savestring (temp
->redirectee
.filename
->word
);
3235 filename
= xmalloc (1);
3240 filename
= itos (temp
->redirectee
.dest
);
3244 case AMBIGUOUS_REDIRECT
:
3245 internal_error ("%s: ambiguous redirect", filename
);
3248 case NOCLOBBER_REDIRECT
:
3249 internal_error ("%s: cannot overwrite existing file", filename
);
3252 #if defined (RESTRICTED_SHELL)
3253 case RESTRICTED_REDIRECT
:
3254 internal_error ("%s: restricted: cannot redirect output", filename
);
3256 #endif /* RESTRICTED_SHELL */
3258 case HEREDOC_REDIRECT
:
3259 internal_error ("cannot create temp file for here document: %s", strerror (heredoc_errno
));
3263 internal_error ("%s: %s", filename
, strerror (error
));
3270 /* Perform the redirections on LIST. If FOR_REAL, then actually make
3271 input and output file descriptors, otherwise just do whatever is
3272 neccessary for side effecting. INTERNAL says to remember how to
3273 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
3274 file descriptors opened in do_redirection () have their close-on-exec
3277 do_redirections (list
, for_real
, internal
, set_clexec
)
3279 int for_real
, internal
, set_clexec
;
3286 if (redirection_undo_list
)
3288 dispose_redirects (redirection_undo_list
);
3289 redirection_undo_list
= (REDIRECT
*)NULL
;
3291 if (exec_redirection_undo_list
)
3292 dispose_exec_redirects ();
3295 for (temp
= list
; temp
; temp
= temp
->next
)
3297 error
= do_redirection_internal (temp
, for_real
, internal
, set_clexec
);
3300 redirection_error (temp
, error
);
3307 /* Return non-zero if the redirection pointed to by REDIRECT has a
3308 redirectee.filename that can be expanded. */
3310 expandable_redirection_filename (redirect
)
3313 switch (redirect
->instruction
)
3315 case r_output_direction
:
3316 case r_appending_to
:
3317 case r_input_direction
:
3318 case r_inputa_direction
:
3320 case r_input_output
:
3321 case r_output_force
:
3322 case r_duplicating_input_word
:
3323 case r_duplicating_output_word
:
3331 /* Expand the word in WORD returning a string. If WORD expands to
3332 multiple words (or no words), then return NULL. */
3334 redirection_expand (word
)
3338 WORD_LIST
*tlist1
, *tlist2
;
3340 tlist1
= make_word_list (copy_word (word
), (WORD_LIST
*)NULL
);
3341 tlist2
= expand_words_no_vars (tlist1
);
3342 dispose_words (tlist1
);
3344 if (!tlist2
|| tlist2
->next
)
3346 /* We expanded to no words, or to more than a single word.
3347 Dispose of the word list and return NULL. */
3349 dispose_words (tlist2
);
3350 return ((char *)NULL
);
3352 result
= string_list (tlist2
); /* XXX savestring (tlist2->word->word)? */
3353 dispose_words (tlist2
);
3357 /* Write the text of the here document pointed to by REDIRECTEE to the file
3358 descriptor FD, which is already open to a temp file. Return 0 if the
3359 write is successful, otherwise return errno. */
3361 write_here_document (fd
, redirectee
)
3363 WORD_DESC
*redirectee
;
3366 int document_len
, fd2
;
3368 register WORD_LIST
*t
, *tlist
;
3370 /* Expand the text if the word that was specified had
3371 no quoting. The text that we expand is treated
3372 exactly as if it were surrounded by double quotes. */
3374 if (redirectee
->flags
& W_QUOTED
)
3376 document
= redirectee
->word
;
3377 document_len
= strlen (document
);
3378 /* Set errno to something reasonable if the write fails. */
3379 if (write (fd
, document
, document_len
) < document_len
)
3389 tlist
= expand_string (redirectee
->word
, Q_HERE_DOCUMENT
);
3392 /* Try using buffered I/O (stdio) and writing a word
3393 at a time, letting stdio do the work of buffering
3394 for us rather than managing our own strings. Most
3395 stdios are not particularly fast, however -- this
3396 may need to be reconsidered later. */
3397 if ((fd2
= dup (fd
)) < 0 || (fp
= fdopen (fd2
, "w")) == NULL
)
3404 for (t
= tlist
; t
; t
= t
->next
)
3406 /* This is essentially the body of
3407 string_list_internal expanded inline. */
3408 document
= t
->word
->word
;
3409 document_len
= strlen (document
);
3411 putc (' ', fp
); /* separator */
3412 fwrite (document
, document_len
, 1, fp
);
3419 dispose_words (tlist
);
3424 dispose_words (tlist
);
3429 /* Create a temporary file holding the text of the here document pointed to
3430 by REDIRECTEE, and return a file descriptor open for reading to the temp
3431 file. Return -1 on any error, and make sure errno is set appropriately. */
3433 here_document_to_fd (redirectee
)
3434 WORD_DESC
*redirectee
;
3439 /* Make the filename for the temp file. */
3440 sprintf (filename
, "/tmp/t%d-sh", (int)time ((time_t *) 0) + (int)getpid ());
3442 /* Make sure we open it exclusively. */
3443 fd
= open (filename
, O_TRUNC
| O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
3447 errno
= r
= 0; /* XXX */
3448 /* write_here_document returns 0 on success, errno on failure. */
3449 if (redirectee
->word
)
3450 r
= write_here_document (fd
, redirectee
);
3460 /* XXX - this is raceable */
3461 /* Make the document really temporary. Also make it the input. */
3462 fd
= open (filename
, O_RDONLY
, 0600);
3472 if (unlink (filename
) < 0)
3483 /* Open FILENAME with FLAGS in noclobber mode, hopefully avoiding most
3484 race conditions and avoiding the problem where the file is replaced
3485 between the stat(2) and open(2). */
3487 noclobber_open (filename
, flags
, ri
)
3490 enum r_instruction ri
;
3493 struct stat finfo
, finfo2
;
3495 /* If the file exists and is a regular file, return an error
3497 r
= stat (filename
, &finfo
);
3498 if (r
== 0 && (S_ISREG (finfo
.st_mode
)))
3499 return (NOCLOBBER_REDIRECT
);
3501 /* If the file was not present (r != 0), make sure we open it
3502 exclusively so that if it is created before we open it, our open
3503 will fail. Make sure that we do not truncate an existing file.
3504 Note that we don't turn on O_EXCL unless the stat failed -- if
3505 the file was not a regular file, we leave O_EXCL off. */
3509 fd
= open (filename
, flags
|O_EXCL
, 0666);
3510 return ((fd
< 0 && errno
== EEXIST
) ? NOCLOBBER_REDIRECT
: fd
);
3512 fd
= open (filename
, flags
, 0666);
3514 /* If the open failed, return the file descriptor right away. */
3516 return (errno
== EEXIST
? NOCLOBBER_REDIRECT
: fd
);
3518 /* OK, the open succeeded, but the file may have been changed from a
3519 non-regular file to a regular file between the stat and the open.
3520 We are assuming that the O_EXCL open handles the case where FILENAME
3521 did not exist and is symlinked to an existing file between the stat
3524 /* If we can open it and fstat the file descriptor, and neither check
3525 revealed that it was a regular file, and the file has not been replaced,
3526 return the file descriptor. */
3527 if ((fstat (fd
, &finfo2
) == 0) && (S_ISREG (finfo2
.st_mode
) == 0) &&
3528 r
== 0 && (S_ISREG (finfo
.st_mode
) == 0) &&
3529 same_file (filename
, filename
, &finfo
, &finfo2
))
3532 /* The file has been replaced. badness. */
3535 return (NOCLOBBER_REDIRECT
);
3538 /* Do the specific redirection requested. Returns errno or one of the
3539 special redirection errors (*_REDIRECT) in case of error, 0 on success.
3540 If FOR_REAL is zero, then just do whatever is neccessary to produce the
3541 appropriate side effects. REMEMBERING, if non-zero, says to remember
3542 how to undo each redirection. If SET_CLEXEC is non-zero, then
3543 we set all file descriptors > 2 that we open to be close-on-exec. */
3545 do_redirection_internal (redirect
, for_real
, remembering
, set_clexec
)
3547 int for_real
, remembering
, set_clexec
;
3549 WORD_DESC
*redirectee
;
3550 int redir_fd
, fd
, redirector
, r
;
3551 char *redirectee_word
;
3552 enum r_instruction ri
;
3553 REDIRECT
*new_redirect
;
3555 redirectee
= redirect
->redirectee
.filename
;
3556 redir_fd
= redirect
->redirectee
.dest
;
3557 redirector
= redirect
->redirector
;
3558 ri
= redirect
->instruction
;
3560 if (ri
== r_duplicating_input_word
|| ri
== r_duplicating_output_word
)
3562 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
3563 the redirection into a new one and continue. */
3564 redirectee_word
= redirection_expand (redirectee
);
3566 if (redirectee_word
== 0)
3567 return (AMBIGUOUS_REDIRECT
);
3568 else if (redirectee_word
[0] == '-' && redirectee_word
[1] == '\0')
3571 new_redirect
= make_redirection (redirector
, r_close_this
, rd
);
3573 else if (all_digits (redirectee_word
))
3575 if (ri
== r_duplicating_input_word
)
3577 rd
.dest
= atol (redirectee_word
);
3578 new_redirect
= make_redirection (redirector
, r_duplicating_input
, rd
);
3582 rd
.dest
= atol (redirectee_word
);
3583 new_redirect
= make_redirection (redirector
, r_duplicating_output
, rd
);
3586 else if (ri
== r_duplicating_output_word
&& redirector
== 1)
3588 if (posixly_correct
== 0)
3590 rd
.filename
= make_bare_word (redirectee_word
);
3591 new_redirect
= make_redirection (1, r_err_and_out
, rd
);
3594 new_redirect
= copy_redirect (redirect
);
3598 free (redirectee_word
);
3599 return (AMBIGUOUS_REDIRECT
);
3602 free (redirectee_word
);
3604 /* Set up the variables needed by the rest of the function from the
3606 if (new_redirect
->instruction
== r_err_and_out
)
3610 /* Copy the word without allocating any memory that must be
3611 explicitly freed. */
3612 redirectee
= (WORD_DESC
*)alloca (sizeof (WORD_DESC
));
3613 xbcopy ((char *)new_redirect
->redirectee
.filename
,
3614 (char *)redirectee
, sizeof (WORD_DESC
));
3616 alloca_hack
= (char *)
3617 alloca (1 + strlen (new_redirect
->redirectee
.filename
->word
));
3618 redirectee
->word
= alloca_hack
;
3619 strcpy (redirectee
->word
, new_redirect
->redirectee
.filename
->word
);
3622 /* It's guaranteed to be an integer, and shouldn't be freed. */
3623 redirectee
= new_redirect
->redirectee
.filename
;
3625 redir_fd
= new_redirect
->redirectee
.dest
;
3626 redirector
= new_redirect
->redirector
;
3627 ri
= new_redirect
->instruction
;
3629 /* Overwrite the flags element of the old redirect with the new value. */
3630 redirect
->flags
= new_redirect
->flags
;
3631 dispose_redirects (new_redirect
);
3636 case r_output_direction
:
3637 case r_appending_to
:
3638 case r_input_direction
:
3639 case r_inputa_direction
:
3640 case r_err_and_out
: /* command &>filename */
3641 case r_input_output
:
3642 case r_output_force
:
3643 if (posixly_correct
&& !interactive_shell
)
3644 disallow_filename_globbing
++;
3645 redirectee_word
= redirection_expand (redirectee
);
3646 if (posixly_correct
&& !interactive_shell
)
3647 disallow_filename_globbing
--;
3649 if (redirectee_word
== 0)
3650 return (AMBIGUOUS_REDIRECT
);
3652 #if defined (RESTRICTED_SHELL)
3653 if (restricted
&& (WRITE_REDIRECT (ri
)))
3655 free (redirectee_word
);
3656 return (RESTRICTED_REDIRECT
);
3658 #endif /* RESTRICTED_SHELL */
3660 /* If we are in noclobber mode, you are not allowed to overwrite
3661 existing files. Check before opening. */
3662 if (noclobber
&& OUTPUT_REDIRECT (ri
))
3664 fd
= noclobber_open (redirectee_word
, redirect
->flags
, ri
);
3665 if (fd
== NOCLOBBER_REDIRECT
)
3667 free (redirectee_word
);
3668 return (NOCLOBBER_REDIRECT
);
3673 fd
= open (redirectee_word
, redirect
->flags
, 0666);
3675 if ((fd
< 0) && (errno
== EACCES
))
3676 fd
= open (redirectee_word
, redirect
->flags
& ~O_CREAT
, 0666);
3679 free (redirectee_word
);
3687 /* Only setup to undo it if the thing to undo is active. */
3688 if ((fd
!= redirector
) && (fcntl (redirector
, F_GETFD
, 0) != -1))
3689 add_undo_redirect (redirector
);
3691 add_undo_close_redirect (redirector
);
3693 #if defined (BUFFERED_INPUT)
3694 check_bash_input (redirector
);
3697 if ((fd
!= redirector
) && (dup2 (fd
, redirector
) < 0))
3700 #if defined (BUFFERED_INPUT)
3701 /* Do not change the buffered stream for an implicit redirection
3702 of /dev/null to fd 0 for asynchronous commands without job
3703 control (r_inputa_direction). */
3704 if (ri
== r_input_direction
|| ri
== r_input_output
)
3705 duplicate_buffered_stream (fd
, redirector
);
3706 #endif /* BUFFERED_INPUT */
3709 * If we're remembering, then this is the result of a while, for
3710 * or until loop with a loop redirection, or a function/builtin
3711 * executing in the parent shell with a redirection. In the
3712 * function/builtin case, we want to set all file descriptors > 2
3713 * to be close-on-exec to duplicate the effect of the old
3714 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
3715 * both sh and ksh leave the file descriptors open across execs.
3716 * The Posix standard mentions only the exec builtin.
3718 if (set_clexec
&& (redirector
> 2))
3719 SET_CLOSE_ON_EXEC (redirector
);
3722 if (fd
!= redirector
)
3724 #if defined (BUFFERED_INPUT)
3725 if (INPUT_REDIRECT (ri
))
3726 close_buffered_fd (fd
);
3728 #endif /* !BUFFERED_INPUT */
3729 close (fd
); /* Don't close what we just opened! */
3732 /* If we are hacking both stdout and stderr, do the stderr
3733 redirection here. */
3734 if (ri
== r_err_and_out
)
3739 add_undo_redirect (2);
3740 if (dup2 (1, 2) < 0)
3746 case r_reading_until
:
3747 case r_deblank_reading_until
:
3748 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
3749 the new input. Place it in a temporary file. */
3752 fd
= here_document_to_fd (redirectee
);
3756 heredoc_errno
= errno
;
3757 return (HEREDOC_REDIRECT
);
3763 /* Only setup to undo it if the thing to undo is active. */
3764 if ((fd
!= redirector
) && (fcntl (redirector
, F_GETFD
, 0) != -1))
3765 add_undo_redirect (redirector
);
3767 add_undo_close_redirect (redirector
);
3769 #if defined (BUFFERED_INPUT)
3770 check_bash_input (redirector
);
3772 if (fd
!= redirector
&& dup2 (fd
, redirector
) < 0)
3779 #if defined (BUFFERED_INPUT)
3780 duplicate_buffered_stream (fd
, redirector
);
3783 if (set_clexec
&& (redirector
> 2))
3784 SET_CLOSE_ON_EXEC (redirector
);
3787 #if defined (BUFFERED_INPUT)
3788 close_buffered_fd (fd
);
3795 case r_duplicating_input
:
3796 case r_duplicating_output
:
3797 if (for_real
&& (redir_fd
!= redirector
))
3800 /* Only setup to undo it if the thing to undo is active. */
3801 if (fcntl (redirector
, F_GETFD
, 0) != -1)
3802 add_undo_redirect (redirector
);
3804 add_undo_close_redirect (redirector
);
3806 #if defined (BUFFERED_INPUT)
3807 check_bash_input (redirector
);
3809 /* This is correct. 2>&1 means dup2 (1, 2); */
3810 if (dup2 (redir_fd
, redirector
) < 0)
3813 #if defined (BUFFERED_INPUT)
3814 if (ri
== r_duplicating_input
)
3815 duplicate_buffered_stream (redir_fd
, redirector
);
3816 #endif /* BUFFERED_INPUT */
3818 /* First duplicate the close-on-exec state of redirectee. dup2
3819 leaves the flag unset on the new descriptor, which means it
3820 stays open. Only set the close-on-exec bit for file descriptors
3821 greater than 2 in any case, since 0-2 should always be open
3822 unless closed by something like `exec 2<&-'. */
3823 /* if ((already_set || set_unconditionally) && (ok_to_set))
3825 if (((fcntl (redir_fd
, F_GETFD
, 0) == 1) || set_clexec
) &&
3827 SET_CLOSE_ON_EXEC (redirector
);
3834 if (remembering
&& (fcntl (redirector
, F_GETFD
, 0) != -1))
3835 add_undo_redirect (redirector
);
3837 #if defined (BUFFERED_INPUT)
3838 check_bash_input (redirector
);
3839 close_buffered_fd (redirector
);
3840 #else /* !BUFFERED_INPUT */
3842 #endif /* !BUFFERED_INPUT */
3846 case r_duplicating_input_word
:
3847 case r_duplicating_output_word
:
3853 #define SHELL_FD_BASE 10
3855 /* Remember the file descriptor associated with the slot FD,
3856 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
3857 before it is executed. Any redirections that need to be undone
3858 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
3859 are also saved on EXEC_REDIRECTION_UNDO_LIST. */
3861 add_undo_redirect (fd
)
3864 int new_fd
, clexec_flag
;
3865 REDIRECT
*new_redirect
, *closer
, *dummy_redirect
;
3867 new_fd
= fcntl (fd
, F_DUPFD
, SHELL_FD_BASE
);
3871 sys_error ("redirection error");
3875 clexec_flag
= fcntl (fd
, F_GETFD
, 0);
3878 closer
= make_redirection (new_fd
, r_close_this
, rd
);
3879 dummy_redirect
= copy_redirects (closer
);
3881 rd
.dest
= (long)new_fd
;
3882 new_redirect
= make_redirection (fd
, r_duplicating_output
, rd
);
3883 new_redirect
->next
= closer
;
3885 closer
->next
= redirection_undo_list
;
3886 redirection_undo_list
= new_redirect
;
3888 /* Save redirections that need to be undone even if the undo list
3889 is thrown away by the `exec' builtin. */
3890 add_exec_redirect (dummy_redirect
);
3892 /* File descriptors used only for saving others should always be
3893 marked close-on-exec. Unfortunately, we have to preserve the
3894 close-on-exec state of the file descriptor we are saving, since
3895 fcntl (F_DUPFD) sets the new file descriptor to remain open
3896 across execs. If, however, the file descriptor whose state we
3897 are saving is <= 2, we can just set the close-on-exec flag,
3898 because file descriptors 0-2 should always be open-on-exec,
3899 and the restore above in do_redirection() will take care of it. */
3900 if (clexec_flag
|| fd
< 3)
3901 SET_CLOSE_ON_EXEC (new_fd
);
3906 /* Set up to close FD when we are finished with the current command
3907 and its redirections. */
3909 add_undo_close_redirect (fd
)
3915 closer
= make_redirection (fd
, r_close_this
, rd
);
3916 closer
->next
= redirection_undo_list
;
3917 redirection_undo_list
= closer
;
3921 add_exec_redirect (dummy_redirect
)
3922 REDIRECT
*dummy_redirect
;
3924 dummy_redirect
->next
= exec_redirection_undo_list
;
3925 exec_redirection_undo_list
= dummy_redirect
;
3928 #define u_mode_bits(x) (((x) & 0000700) >> 6)
3929 #define g_mode_bits(x) (((x) & 0000070) >> 3)
3930 #define o_mode_bits(x) (((x) & 0000007) >> 0)
3931 #define X_BIT(x) ((x) & 1)
3933 /* Return some flags based on information about this file.
3934 The EXISTS bit is non-zero if the file is found.
3935 The EXECABLE bit is non-zero the file is executble.
3936 Zero is returned if the file is not found. */
3943 /* Determine whether this file exists or not. */
3944 if (stat (name
, &finfo
) < 0)
3947 /* If the file is a directory, then it is not "executable" in the
3948 sense of the shell. */
3949 if (S_ISDIR (finfo
.st_mode
))
3950 return (FS_EXISTS
|FS_DIRECTORY
);
3953 /* We have to use access(2) to determine access because AFS does not
3954 support Unix file system semantics. This may produce wrong
3955 answers for non-AFS files when ruid != euid. I hate AFS. */
3956 if (access (name
, X_OK
) == 0)
3957 return (FS_EXISTS
| FS_EXECABLE
);
3962 /* Find out if the file is actually executable. By definition, the
3963 only other criteria is that the file has an execute bit set that
3966 /* Root only requires execute permission for any of owner, group or
3967 others to be able to exec a file. */
3968 if (current_user
.euid
== (uid_t
)0)
3972 bits
= (u_mode_bits (finfo
.st_mode
) |
3973 g_mode_bits (finfo
.st_mode
) |
3974 o_mode_bits (finfo
.st_mode
));
3977 return (FS_EXISTS
| FS_EXECABLE
);
3980 /* If we are the owner of the file, the owner execute bit applies. */
3981 if (current_user
.euid
== finfo
.st_uid
&& X_BIT (u_mode_bits (finfo
.st_mode
)))
3982 return (FS_EXISTS
| FS_EXECABLE
);
3984 /* If we are in the owning group, the group permissions apply. */
3985 if (group_member (finfo
.st_gid
) && X_BIT (g_mode_bits (finfo
.st_mode
)))
3986 return (FS_EXISTS
| FS_EXECABLE
);
3988 /* If `others' have execute permission to the file, then so do we,
3989 since we are also `others'. */
3990 if (X_BIT (o_mode_bits (finfo
.st_mode
)))
3991 return (FS_EXISTS
| FS_EXECABLE
);
3997 /* Return non-zero if FILE exists and is executable.
3998 Note that this function is the definition of what an
3999 executable file is; do not change this unless YOU know
4000 what an executable file is. */
4002 executable_file (file
)
4007 s
= file_status (file
);
4008 return ((s
& FS_EXECABLE
) && ((s
& FS_DIRECTORY
) == 0));
4015 return (file_status (file
) & FS_DIRECTORY
);
4018 /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
4019 encounters a `.' as the directory pathname while scanning the
4020 list of possible pathnames; i.e., if `.' comes before the directory
4021 containing the file of interest. */
4022 int dot_found_in_search
= 0;
4024 /* Locate the executable file referenced by NAME, searching along
4025 the contents of the shell PATH variable. Return a new string
4026 which is the full pathname to the file, or NULL if the file
4027 couldn't be found. If a file is found that isn't executable,
4028 and that is the only match, then return that. */
4030 find_user_command (name
)
4033 return (find_user_command_internal (name
, FS_EXEC_PREFERRED
|FS_NODIRS
));
4036 /* Locate the file referenced by NAME, searching along the contents
4037 of the shell PATH variable. Return a new string which is the full
4038 pathname to the file, or NULL if the file couldn't be found. This
4039 returns the first file found. */
4041 find_path_file (name
)
4044 return (find_user_command_internal (name
, FS_EXISTS
));
4048 _find_user_command_internal (name
, flags
)
4055 /* Search for the value of PATH in both the temporary environment, and
4056 in the regular list of variables. */
4057 if (var
= find_variable_internal ("PATH", 1)) /* XXX could be array? */
4058 path_list
= value_cell (var
);
4060 path_list
= (char *)NULL
;
4062 if (path_list
== 0 || *path_list
== '\0')
4063 return (savestring (name
));
4065 return (find_user_command_in_path (name
, path_list
, flags
));
4069 find_user_command_internal (name
, flags
)
4076 dotexe
= xmalloc (strlen (name
) + 5);
4077 strcpy (dotexe
, name
);
4078 strcat (dotexe
, ".exe");
4079 res
= _find_user_command_internal (dotexe
, flags
);
4082 res
= _find_user_command_internal (name
, flags
);
4085 return (_find_user_command_internal (name
, flags
));
4089 /* Return the next element from PATH_LIST, a colon separated list of
4090 paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST;
4091 the index is modified by this function.
4092 Return the next element of PATH_LIST or NULL if there are no more. */
4094 get_next_path_element (path_list
, path_index_pointer
)
4096 int *path_index_pointer
;
4100 path
= extract_colon_unit (path_list
, path_index_pointer
);
4108 path
= savestring (".");
4114 /* Look for PATHNAME in $PATH. Returns either the hashed command
4115 corresponding to PATHNAME or the first instance of PATHNAME found
4116 in $PATH. Returns a newly-allocated string. */
4118 search_for_command (pathname
)
4121 char *hashed_file
, *command
;
4125 hashed_file
= command
= (char *)NULL
;
4127 /* If PATH is in the temporary environment for this command, don't use the
4128 hash table to search for the full pathname. */
4129 path
= find_tempenv_variable ("PATH");
4130 temp_path
= path
!= 0;
4132 /* Don't waste time trying to find hashed data for a pathname
4133 that is already completely specified or if we're using a command-
4134 specific value for PATH. */
4135 if (path
== 0 && absolute_program (pathname
) == 0)
4136 hashed_file
= find_hashed_filename (pathname
);
4138 /* If a command found in the hash table no longer exists, we need to
4139 look for it in $PATH. Thank you Posix.2. This forces us to stat
4140 every command found in the hash table. */
4142 if (hashed_file
&& (posixly_correct
|| check_hashed_filenames
))
4144 st
= file_status (hashed_file
);
4145 if ((st
^ (FS_EXISTS
| FS_EXECABLE
)) != 0)
4147 remove_hashed_filename (pathname
);
4149 hashed_file
= (char *)NULL
;
4154 command
= hashed_file
;
4155 else if (absolute_program (pathname
))
4156 /* A command containing a slash is not looked up in PATH or saved in
4158 command
= savestring (pathname
);
4161 /* If $PATH is in the temporary environment, we've already retrieved
4162 it, so don't bother trying again. */
4164 command
= find_user_command_in_path (pathname
, value_cell (path
),
4165 FS_EXEC_PREFERRED
|FS_NODIRS
);
4167 command
= find_user_command (pathname
);
4168 if (command
&& hashing_enabled
&& temp_path
== 0)
4169 remember_filename (pathname
, command
, dot_found_in_search
, 1);
4175 user_command_matches (name
, flags
, state
)
4180 int path_index
, name_len
;
4181 char *path_list
, *path_element
, *match
;
4182 struct stat dotinfo
;
4183 static char **match_list
= NULL
;
4184 static int match_list_size
= 0;
4185 static int match_index
= 0;
4189 /* Create the list of matches. */
4190 if (match_list
== 0)
4192 match_list_size
= 5;
4193 match_list
= (char **)xmalloc (match_list_size
* sizeof(char *));
4196 /* Clear out the old match list. */
4197 for (i
= 0; i
< match_list_size
; i
++)
4200 /* We haven't found any files yet. */
4203 if (absolute_program (name
))
4205 match_list
[0] = find_absolute_program (name
, flags
);
4206 match_list
[1] = (char *)NULL
;
4207 path_list
= (char *)NULL
;
4211 name_len
= strlen (name
);
4212 file_to_lose_on
= (char *)NULL
;
4213 dot_found_in_search
= 0;
4214 stat (".", &dotinfo
);
4215 path_list
= get_string_value ("PATH");
4219 while (path_list
&& path_list
[path_index
])
4221 path_element
= get_next_path_element (path_list
, &path_index
);
4223 if (path_element
== 0)
4226 match
= find_in_path_element (name
, path_element
, flags
, name_len
, &dotinfo
);
4228 free (path_element
);
4233 if (match_index
+ 1 == match_list_size
)
4235 match_list_size
+= 10;
4236 match_list
= (char **)xrealloc (match_list
, (match_list_size
+ 1) * sizeof (char *));
4239 match_list
[match_index
++] = match
;
4240 match_list
[match_index
] = (char *)NULL
;
4241 FREE (file_to_lose_on
);
4242 file_to_lose_on
= (char *)NULL
;
4245 /* We haven't returned any strings yet. */
4249 match
= match_list
[match_index
];
4257 /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
4258 This allocates new memory and returns it. */
4260 make_full_pathname (path
, name
, name_len
)
4267 path_len
= strlen (path
);
4268 full_path
= xmalloc (2 + path_len
+ name_len
);
4269 strcpy (full_path
, path
);
4270 full_path
[path_len
] = '/';
4271 strcpy (full_path
+ path_len
+ 1, name
);
4276 find_absolute_program (name
, flags
)
4282 st
= file_status (name
);
4284 /* If the file doesn't exist, quit now. */
4285 if ((st
& FS_EXISTS
) == 0)
4286 return ((char *)NULL
);
4288 /* If we only care about whether the file exists or not, return
4289 this filename. Otherwise, maybe we care about whether this
4290 file is executable. If it is, and that is what we want, return it. */
4291 if ((flags
& FS_EXISTS
) || ((flags
& FS_EXEC_ONLY
) && (st
& FS_EXECABLE
)))
4292 return (savestring (name
));
4294 return ((char *)NULL
);
4298 find_in_path_element (name
, path
, flags
, name_len
, dotinfop
)
4300 int flags
, name_len
;
4301 struct stat
*dotinfop
;
4304 char *full_path
, *xpath
;
4306 xpath
= (*path
== '~') ? bash_tilde_expand (path
) : path
;
4308 /* Remember the location of "." in the path, in all its forms
4309 (as long as they begin with a `.', e.g. `./.') */
4310 if (dot_found_in_search
== 0 && *xpath
== '.')
4311 dot_found_in_search
= same_file (".", xpath
, dotinfop
, (struct stat
*)NULL
);
4313 full_path
= make_full_pathname (xpath
, name
, name_len
);
4315 status
= file_status (full_path
);
4320 if ((status
& FS_EXISTS
) == 0)
4323 return ((char *)NULL
);
4326 /* The file exists. If the caller simply wants the first file, here it is. */
4327 if (flags
& FS_EXISTS
)
4330 /* If the file is executable, then it satisfies the cases of
4331 EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */
4332 if ((status
& FS_EXECABLE
) &&
4333 (((flags
& FS_NODIRS
) == 0) || ((status
& FS_DIRECTORY
) == 0)))
4335 FREE (file_to_lose_on
);
4336 file_to_lose_on
= (char *)NULL
;
4340 /* The file is not executable, but it does exist. If we prefer
4341 an executable, then remember this one if it is the first one
4343 if ((flags
& FS_EXEC_PREFERRED
) && file_to_lose_on
== 0)
4344 file_to_lose_on
= savestring (full_path
);
4346 /* If we want only executable files, or we don't want directories and
4347 this file is a directory, fail. */
4348 if ((flags
& FS_EXEC_ONLY
) || (flags
& FS_EXEC_PREFERRED
) ||
4349 ((flags
& FS_NODIRS
) && (status
& FS_DIRECTORY
)))
4352 return ((char *)NULL
);
4358 /* This does the dirty work for find_user_command_internal () and
4359 user_command_matches ().
4360 NAME is the name of the file to search for.
4361 PATH_LIST is a colon separated list of directories to search.
4362 FLAGS contains bit fields which control the files which are eligible.
4364 FS_EXEC_ONLY: The file must be an executable to be found.
4365 FS_EXEC_PREFERRED: If we can't find an executable, then the
4366 the first file matching NAME will do.
4367 FS_EXISTS: The first file found will do.
4368 FS_NODIRS: Don't find any directories.
4371 find_user_command_in_path (name
, path_list
, flags
)
4376 char *full_path
, *path
;
4377 int path_index
, name_len
;
4378 struct stat dotinfo
;
4380 /* We haven't started looking, so we certainly haven't seen
4381 a `.' as the directory path yet. */
4382 dot_found_in_search
= 0;
4384 if (absolute_program (name
))
4386 full_path
= find_absolute_program (name
, flags
);
4390 if (path_list
== 0 || *path_list
== '\0')
4391 return (savestring (name
)); /* XXX */
4393 file_to_lose_on
= (char *)NULL
;
4394 name_len
= strlen (name
);
4395 stat (".", &dotinfo
);
4398 while (path_list
[path_index
])
4400 /* Allow the user to interrupt out of a lengthy path search. */
4403 path
= get_next_path_element (path_list
, &path_index
);
4407 /* Side effects: sets dot_found_in_search, possibly sets
4409 full_path
= find_in_path_element (name
, path
, flags
, name_len
, &dotinfo
);
4412 /* This should really be in find_in_path_element, but there isn't the
4413 right combination of flags. */
4414 if (full_path
&& is_directory (full_path
))
4422 FREE (file_to_lose_on
);
4427 /* We didn't find exactly what the user was looking for. Return
4428 the contents of FILE_TO_LOSE_ON which is NULL when the search
4429 required an executable, or non-NULL if a file was found and the
4430 search would accept a non-executable as a last resort. */
4431 return (file_to_lose_on
);