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 #if defined (HAVE_SYS_TIME_H)
44 # include <sys/time.h>
47 #if defined (HAVE_SYS_RESOURCE_H)
48 # include <sys/resource.h>
51 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
52 # include <sys/times.h>
70 #include "execute_cmd.h"
74 #include "builtins/common.h"
75 #include "builtins/builtext.h" /* list of builtins */
77 #include <glob/fnmatch.h>
78 #include <tilde/tilde.h>
80 #if defined (BUFFERED_INPUT)
89 # include "bashhist.h"
92 extern int posixly_correct;
93 extern int executing, breaking, continuing, loop_level;
94 extern int interactive, interactive_shell, login_shell, expand_aliases;
95 extern int parse_and_execute_level, running_trap;
96 extern int command_string_index, variable_context, line_number;
97 extern int dot_found_in_search;
98 extern int already_making_children;
99 extern char **temporary_env, **function_env, **builtin_env;
100 extern char *the_printed_command, *shell_name;
101 extern pid_t last_command_subst_pid;
102 extern Function *last_shell_builtin, *this_shell_builtin;
103 extern char **subshell_argv, **subshell_envp;
104 extern int subshell_argc;
105 extern char *glob_argv_flags;
107 extern int getdtablesize ();
110 /* Static functions defined and used in this file. */
111 static void close_pipes (), do_piping (), bind_lastarg ();
112 static void cleanup_redirects ();
113 static void add_undo_close_redirect (), add_exec_redirect ();
114 static int add_undo_redirect ();
115 static int do_redirection_internal (), do_redirections ();
116 static int expandable_redirection_filename ();
117 static char *find_user_command_internal (), *find_user_command_in_path ();
118 static char *find_in_path_element (), *find_absolute_program ();
120 static int execute_for_command ();
121 #if defined (SELECT_COMMAND)
122 static int execute_select_command ();
124 static int time_command ();
125 static int execute_case_command ();
126 static int execute_while_command (), execute_until_command ();
127 static int execute_while_or_until ();
128 static int execute_if_command ();
129 static int execute_simple_command ();
130 static int execute_builtin (), execute_function ();
131 static int execute_builtin_or_function ();
132 static int builtin_status ();
133 static void execute_subshell_builtin_or_function ();
134 static void execute_disk_command ();
135 static int execute_connection ();
136 static int execute_intern_function ();
138 /* The line number that the currently executing function starts on. */
139 static int function_line_number;
141 /* Set to 1 if fd 0 was the subject of redirection to a subshell. */
142 static int stdin_redir;
144 /* The name of the command that is currently being executed.
145 `test' needs this, for example. */
146 char *this_command_name;
148 static COMMAND *currently_executing_command;
150 struct stat SB; /* used for debugging */
152 static int special_builtin_failed;
153 static REDIRECTEE rd;
155 /* The file name which we would try to execute, except that it isn't
156 possible to execute it. This is the first file that matches the
157 name that we are looking for while we are searching $PATH for a
158 suitable one to execute. If we cannot find a suitable executable
159 file, then we use this one. */
160 static char *file_to_lose_on;
162 /* For catching RETURN in a function. */
163 int return_catch_flag;
164 int return_catch_value;
165 procenv_t return_catch;
167 /* The value returned by the last synchronous command. */
168 int last_command_exit_value;
170 /* The list of redirections to perform which will undo the redirections
171 that I made in the shell. */
172 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
174 /* The list of redirections to perform which will undo the internal
175 redirections performed by the `exec' builtin. These are redirections
176 that must be undone even when exec discards redirection_undo_list. */
177 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
179 /* Non-zero if we have just forked and are currently running in a subshell
181 int subshell_environment;
183 /* Non-zero if we should stat every command found in the hash table to
184 make sure it still exists. */
185 int check_hashed_filenames;
187 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
189 #define FD_BITMAP_DEFAULT_SIZE 32
190 /* Functions to allocate and deallocate the structures used to pass
191 information from the shell to its children about file descriptors
197 struct fd_bitmap *ret;
199 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
205 ret->bitmap = xmalloc (size);
206 bzero (ret->bitmap, size);
209 ret->bitmap = (char *)NULL;
214 dispose_fd_bitmap (fdbp)
215 struct fd_bitmap *fdbp;
222 close_fd_bitmap (fdbp)
223 struct fd_bitmap *fdbp;
229 for (i = 0; i < fdbp->size; i++)
238 /* Return the line number of the currently executing command. */
240 executing_line_number ()
242 if (executing && variable_context == 0 && currently_executing_command &&
243 currently_executing_command->type == cm_simple)
244 return currently_executing_command->value.Simple->line;
248 /* Execute the command passed in COMMAND. COMMAND is exactly what
249 read_command () places into GLOBAL_COMMAND. See "command.h" for the
250 details of the command structure.
252 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
253 return values. Executing a command with nothing in it returns
254 EXECUTION_SUCCESS. */
256 execute_command (command)
259 struct fd_bitmap *bitmap;
262 current_fds_to_close = (struct fd_bitmap *)NULL;
263 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
264 begin_unwind_frame ("execute-command");
265 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
267 /* Just do the command, but not asynchronously. */
268 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
270 dispose_fd_bitmap (bitmap);
271 discard_unwind_frame ("execute-command");
273 #if defined (PROCESS_SUBSTITUTION)
275 #endif /* PROCESS_SUBSTITUTION */
280 /* Return 1 if TYPE is a shell control structure type. */
282 shell_control_structure (type)
283 enum command_type type;
288 #if defined (SELECT_COMMAND)
303 /* A function to use to unwind_protect the redirection undo list
306 cleanup_redirects (list)
309 do_redirections (list, 1, 0, 0);
310 dispose_redirects (list);
314 /* Function to unwind_protect the redirections for functions and builtins. */
316 cleanup_func_redirects (list)
319 do_redirections (list, 1, 0, 0);
324 dispose_exec_redirects ()
326 if (exec_redirection_undo_list)
328 dispose_redirects (exec_redirection_undo_list);
329 exec_redirection_undo_list = (REDIRECT *)NULL;
333 #if defined (JOB_CONTROL)
334 /* A function to restore the signal mask to its proper value when the shell
335 is interrupted or errors occur while creating a pipeline. */
337 restore_signal_mask (set)
340 return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
342 #endif /* JOB_CONTROL */
344 /* A debugging function that can be called from gdb, for instance. */
349 int f, fd_table_size;
351 fd_table_size = getdtablesize ();
353 fprintf (stderr, "pid %d open files:", (int)getpid ());
354 for (i = 3; i < fd_table_size; i++)
356 if ((f = fcntl (i, F_GETFD, 0)) != -1)
357 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
359 fprintf (stderr, "\n");
362 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
364 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
365 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
366 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
367 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
368 from and where it goes. They can have the value of NO_PIPE, which means
370 FDS_TO_CLOSE is a list of file descriptors to close once the child has
371 been forked. This list often contains the unusable sides of pipes, etc.
373 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
374 return values. Executing a command with nothing in it returns
375 EXECUTION_SUCCESS. */
377 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
381 int pipe_in, pipe_out;
382 struct fd_bitmap *fds_to_close;
384 int exec_result, invert, ignore_return, was_debug_trap;
385 REDIRECT *my_undo_list, *exec_undo_list, *rp;
388 if (command == 0 || breaking || continuing || read_but_dont_execute)
389 return (EXECUTION_SUCCESS);
391 run_pending_traps ();
393 if (running_trap == 0)
394 currently_executing_command = command;
396 #if defined (COMMAND_TIMING)
397 if (command->flags & CMD_TIME_PIPELINE)
399 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
400 if (running_trap == 0)
401 currently_executing_command = (COMMAND *)NULL;
402 return (exec_result);
404 #endif /* COMMAND_TIMING */
406 invert = (command->flags & CMD_INVERT_RETURN) != 0;
407 exec_result = EXECUTION_SUCCESS;
409 /* If a command was being explicitly run in a subshell, or if it is
410 a shell control-structure, and it has a pipe, then we do the command
413 if ((command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
414 (shell_control_structure (command->type) &&
415 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
419 /* Fork a subshell, turn off the subshell bit, turn off job
420 control and call execute_command () on the command again. */
421 paren_pid = make_child (savestring (make_command_string (command)),
425 int user_subshell, return_code, function_value;
427 user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
428 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
430 /* If a command is asynchronous in a subshell (like ( foo ) & or
431 the special case of an asynchronous GROUP command where the
432 the subshell bit is turned on down in case cm_group: below),
433 turn off `asynchronous', so that two subshells aren't spawned.
435 This seems semantically correct to me. For example,
436 ( foo ) & seems to say ``do the command `foo' in a subshell
437 environment, but don't wait for that subshell to finish'',
438 and "{ foo ; bar } &" seems to me to be like functions or
439 builtins in the background, which executed in a subshell
440 environment. I just don't see the need to fork two subshells. */
442 /* Don't fork again, we are already in a subshell. A `doubly
443 async' shell is not interactive, however. */
446 #if defined (JOB_CONTROL)
447 /* If a construct like ( exec xxx yyy ) & is given while job
448 control is active, we want to prevent exec from putting the
449 subshell back into the original process group, carefully
450 undoing all the work we just did in make_child. */
452 #endif /* JOB_CONTROL */
453 interactive_shell = 0;
458 /* Subshells are neither login nor interactive. */
459 login_shell = interactive = 0;
461 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
463 reset_terminating_signals (); /* in shell.c */
464 /* Cancel traps, in trap.c. */
465 restore_original_signals ();
467 setup_async_signals ();
469 #if defined (JOB_CONTROL)
470 set_sigchld_handler ();
471 #endif /* JOB_CONTROL */
473 set_sigint_handler ();
475 #if defined (JOB_CONTROL)
476 /* Delete all traces that there were any jobs running. This is
477 only for subshells. */
478 without_job_control ();
479 #endif /* JOB_CONTROL */
480 do_piping (pipe_in, pipe_out);
482 /* If this is a user subshell, set a flag if stdin was redirected.
483 This is used later to decide whether to redirect fd 0 to
484 /dev/null for async commands in the subshell. This adds more
485 sh compatibility, but I'm not sure it's the right thing to do. */
488 for (rp = command->redirects; rp; rp = rp->next)
489 switch (rp->instruction)
491 case r_input_direction:
492 case r_inputa_direction:
494 case r_reading_until:
495 case r_deblank_reading_until:
498 case r_duplicating_input:
499 case r_duplicating_input_word:
501 stdin_redir += (rp->redirector == 0);
505 restore_default_signal (0);
509 close_fd_bitmap (fds_to_close);
511 /* Do redirections, then dispose of them before recursive call. */
512 if (command->redirects)
514 if (do_redirections (command->redirects, 1, 0, 0) != 0)
515 exit (EXECUTION_FAILURE);
517 dispose_redirects (command->redirects);
518 command->redirects = (REDIRECT *)NULL;
521 /* If this is a simple command, tell execute_disk_command that it
522 might be able to get away without forking and simply exec.
523 This means things like ( sleep 10 ) will only cause one fork. */
524 if (user_subshell && command->type == cm_simple)
526 command->flags |= CMD_NO_FORK;
527 command->value.Simple->flags |= CMD_NO_FORK;
530 /* If we're inside a function while executing this subshell, we
531 need to handle a possible `return'. */
533 if (return_catch_flag)
534 function_value = setjmp (return_catch);
537 return_code = return_catch_value;
539 return_code = execute_command_internal
540 (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
542 /* If we were explicitly placed in a subshell with (), we need
543 to do the `shell cleanup' things, such as running traps[0]. */
544 if (user_subshell && signal_is_trapped (0))
546 last_command_exit_value = return_code;
547 return_code = run_exit_trap ();
554 close_pipes (pipe_in, pipe_out);
556 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
559 /* If we are part of a pipeline, and not the end of the pipeline,
560 then we should simply return and let the last command in the
561 pipe be waited for. If we are not in a pipeline, or are the
562 last command in the pipeline, then we wait for the subshell
563 and return its exit status as usual. */
564 if (pipe_out != NO_PIPE)
565 return (EXECUTION_SUCCESS);
567 stop_pipeline (asynchronous, (COMMAND *)NULL);
569 if (asynchronous == 0)
571 last_command_exit_value = wait_for (paren_pid);
573 /* If we have to, invert the return value. */
575 return ((last_command_exit_value == EXECUTION_SUCCESS)
577 : EXECUTION_SUCCESS);
579 return (last_command_exit_value);
583 DESCRIBE_PID (paren_pid);
585 run_pending_traps ();
587 return (EXECUTION_SUCCESS);
592 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
594 if (do_redirections (command->redirects, 1, 1, 0) != 0)
596 cleanup_redirects (redirection_undo_list);
597 redirection_undo_list = (REDIRECT *)NULL;
598 dispose_exec_redirects ();
599 return (EXECUTION_FAILURE);
602 if (redirection_undo_list)
604 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
605 dispose_redirects (redirection_undo_list);
606 redirection_undo_list = (REDIRECT *)NULL;
609 my_undo_list = (REDIRECT *)NULL;
611 if (exec_redirection_undo_list)
613 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
614 dispose_redirects (exec_redirection_undo_list);
615 exec_redirection_undo_list = (REDIRECT *)NULL;
618 exec_undo_list = (REDIRECT *)NULL;
620 if (my_undo_list || exec_undo_list)
621 begin_unwind_frame ("loop_redirections");
624 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
627 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
629 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
633 switch (command->type)
637 /* We can't rely on this variable retaining its value across a
638 call to execute_simple_command if a longjmp occurs as the
639 result of a `return' builtin. This is true for sure with gcc. */
640 last_pid = last_made_pid;
641 was_debug_trap = signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0;
643 if (ignore_return && command->value.Simple)
644 command->value.Simple->flags |= CMD_IGNORE_RETURN;
646 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
647 asynchronous, fds_to_close);
649 /* The temporary environment should be used for only the simple
650 command immediately following its definition. */
651 dispose_used_env_vars ();
653 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
654 /* Reclaim memory allocated with alloca () on machines which
655 may be using the alloca emulation code. */
657 #endif /* (ultrix && mips) || C_ALLOCA */
659 /* If we forked to do the command, then we must wait_for ()
662 /* XXX - this is something to watch out for if there are problems
663 when the shell is compiled without job control. */
664 if (already_making_children && pipe_out == NO_PIPE &&
665 last_pid != last_made_pid)
667 stop_pipeline (asynchronous, (COMMAND *)NULL);
671 DESCRIBE_PID (last_made_pid);
674 #if !defined (JOB_CONTROL)
675 /* Do not wait for asynchronous processes started from
677 if (last_made_pid != last_asynchronous_pid)
679 /* When executing a shell function that executes other
680 commands, this causes the last simple command in
681 the function to be waited for twice. */
682 exec_result = wait_for (last_made_pid);
689 if (ignore_return == 0 && invert == 0 &&
690 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
691 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
693 last_command_exit_value = exec_result;
694 run_pending_traps ();
695 jump_to_top_level (EXITPROG);
702 command->value.For->flags |= CMD_IGNORE_RETURN;
703 exec_result = execute_for_command (command->value.For);
706 #if defined (SELECT_COMMAND)
709 command->value.Select->flags |= CMD_IGNORE_RETURN;
710 exec_result = execute_select_command (command->value.Select);
716 command->value.Case->flags |= CMD_IGNORE_RETURN;
717 exec_result = execute_case_command (command->value.Case);
722 command->value.While->flags |= CMD_IGNORE_RETURN;
723 exec_result = execute_while_command (command->value.While);
728 command->value.While->flags |= CMD_IGNORE_RETURN;
729 exec_result = execute_until_command (command->value.While);
734 command->value.If->flags |= CMD_IGNORE_RETURN;
735 exec_result = execute_if_command (command->value.If);
740 /* This code can be executed from either of two paths: an explicit
741 '{}' command, or via a function call. If we are executed via a
742 function call, we have already taken care of the function being
743 executed in the background (down there in execute_simple_command ()),
744 and this command should *not* be marked as asynchronous. If we
745 are executing a regular '{}' group command, and asynchronous == 1,
746 we must want to execute the whole command in the background, so we
747 need a subshell, and we want the stuff executed in that subshell
748 (this group command) to be executed in the foreground of that
749 subshell (i.e. there will not be *another* subshell forked).
751 What we do is to force a subshell if asynchronous, and then call
752 execute_command_internal again with asynchronous still set to 1,
753 but with the original group command, so the printed command will
756 The code above that handles forking off subshells will note that
757 both subshell and async are on, and turn off async in the child
758 after forking the subshell (but leave async set in the parent, so
759 the normal call to describe_pid is made). This turning off
760 async is *crucial*; if it is not done, this will fall into an
761 infinite loop of executions through this spot in subshell after
762 subshell until the process limit is exhausted. */
766 command->flags |= CMD_FORCE_SUBSHELL;
768 execute_command_internal (command, 1, pipe_in, pipe_out,
773 if (ignore_return && command->value.Group->command)
774 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
776 execute_command_internal (command->value.Group->command,
777 asynchronous, pipe_in, pipe_out,
783 exec_result = execute_connection (command, asynchronous,
784 pipe_in, pipe_out, fds_to_close);
787 case cm_function_def:
788 exec_result = execute_intern_function (command->value.Function_def->name,
789 command->value.Function_def->command);
794 ("execute_command: bad command type `%d'", command->type);
799 do_redirections (my_undo_list, 1, 0, 0);
800 dispose_redirects (my_undo_list);
804 dispose_redirects (exec_undo_list);
806 if (my_undo_list || exec_undo_list)
807 discard_unwind_frame ("loop_redirections");
809 /* Invert the return value if we have to */
811 exec_result = (exec_result == EXECUTION_SUCCESS)
815 last_command_exit_value = exec_result;
816 run_pending_traps ();
817 if (running_trap == 0)
818 currently_executing_command = (COMMAND *)NULL;
819 return (last_command_exit_value);
822 #if defined (COMMAND_TIMING)
823 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
824 static struct timeval *
825 difftimeval (d, t1, t2)
826 struct timeval *d, *t1, *t2;
828 d->tv_sec = t2->tv_sec - t1->tv_sec;
829 d->tv_usec = t2->tv_usec - t1->tv_usec;
832 d->tv_usec += 1000000;
834 if (d->tv_sec < 0) /* ??? -- BSD/OS does this */
840 static struct timeval *
841 addtimeval (d, t1, t2)
842 struct timeval *d, *t1, *t2;
844 d->tv_sec = t1->tv_sec + t2->tv_sec;
845 d->tv_usec = t1->tv_usec + t2->tv_usec;
846 if (d->tv_usec > 1000000)
848 d->tv_usec -= 1000000;
854 /* Do "cpu = ((user + sys) * 10000) / real;" with timevals.
855 Barely-tested code from Deven T. Corzine <deven@ties.org>. */
857 timeval_to_cpu (rt, ut, st)
858 struct timeval *rt, *ut, *st; /* real, user, sys */
860 struct timeval t1, t2;
863 addtimeval (&t1, ut, st);
864 t2.tv_sec = rt->tv_sec;
865 t2.tv_usec = rt->tv_usec;
867 for (i = 0; i < 6; i++)
869 if ((t1.tv_sec > 99999999) || (t2.tv_sec > 99999999))
872 t1.tv_sec += t1.tv_usec / 100000;
874 t1.tv_usec %= 1000000;
876 t2.tv_sec += t2.tv_usec / 100000;
878 t2.tv_usec %= 1000000;
880 for (i = 0; i < 4; i++)
882 if (t1.tv_sec < 100000000)
888 return (t1.tv_sec / t2.tv_sec);
890 #endif /* HAVE_GETRUSAGE && HAVE_GETTIMEOFDAY */
892 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
893 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
895 static int precs[] = { 0, 100, 10, 1 };
897 /* Expand one `%'-prefixed escape sequence from a time format string. */
899 mkfmt (buf, prec, lng, sec, sec_fraction)
912 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
919 abuf[aind--] = (min % 10) + '0';
923 buf[ind++] = abuf[aind++];
927 /* Now add the seconds. */
930 abuf[aind--] = (sec % 10) + '0';
934 buf[ind++] = abuf[aind++];
936 /* We want to add a decimal point and PREC places after it if PREC is
937 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
942 for (aind = 1; aind <= prec; aind++)
944 buf[ind++] = (sec_fraction / precs[aind]) + '0';
945 sec_fraction %= precs[aind];
956 /* Interpret the format string FORMAT, interpolating the following escape
960 where the optional `prec' is a precision, meaning the number of
961 characters after the decimal point, the optional `l' means to format
962 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
963 and the last character is one of
965 R number of seconds of `real' time
966 U number of seconds of `user' time
967 S number of seconds of `system' time
969 An occurrence of `%%' in the format string is translated to a `%'. The
970 result is printed to FP, a pointer to a FILE. The other variables are
971 the seconds and thousandths of a second of real, user, and system time,
974 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
978 int rsf, usf, ssf, cpu;
981 char *str, *s, ts[32];
985 len = strlen (format);
986 ssize = (len + 64) - (len % 64);
987 str = xmalloc (ssize);
990 for (s = format; *s; s++)
992 if (*s != '%' || s[1] == '\0')
994 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
997 else if (s[1] == '%')
1000 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1003 else if (s[1] == 'P')
1009 sum_frac = (cpu % 100) * 10;
1010 len = mkfmt (ts, 2, 0, sum, sum_frac);
1011 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1012 strcpy (str + sindex, ts);
1017 prec = 3; /* default is three places past the decimal point. */
1018 lng = 0; /* default is to not use minutes or append `s' */
1020 if (isdigit (*s)) /* `precision' */
1023 if (prec > 3) prec = 3;
1025 if (*s == 'l') /* `length extender' */
1030 if (*s == 'R' || *s == 'E')
1031 len = mkfmt (ts, prec, lng, rs, rsf);
1033 len = mkfmt (ts, prec, lng, us, usf);
1035 len = mkfmt (ts, prec, lng, ss, ssf);
1038 internal_error ("bad format character in time format: %c", *s);
1042 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1043 strcpy (str + sindex, ts);
1049 fprintf (fp, "%s\n", str);
1056 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1058 int asynchronous, pipe_in, pipe_out;
1059 struct fd_bitmap *fds_to_close;
1067 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1068 struct timeval real, user, sys;
1069 struct timeval before, after;
1070 struct timezone dtz;
1071 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1073 # if defined (HAVE_TIMES)
1074 clock_t tbefore, tafter, real, user, sys;
1075 struct tms before, after;
1079 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1080 gettimeofday (&before, &dtz);
1081 getrusage (RUSAGE_SELF, &selfb);
1082 getrusage (RUSAGE_CHILDREN, &kidsb);
1084 # if defined (HAVE_TIMES)
1085 tbefore = times (&before);
1089 posix_time = (command->flags & CMD_TIME_POSIX);
1091 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1092 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1094 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1095 gettimeofday (&after, &dtz);
1096 getrusage (RUSAGE_SELF, &selfa);
1097 getrusage (RUSAGE_CHILDREN, &kidsa);
1099 difftimeval (&real, &before, &after);
1100 timeval_to_secs (&real, &rs, &rsf);
1102 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1103 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1104 timeval_to_secs (&user, &us, &usf);
1106 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1107 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1108 timeval_to_secs (&sys, &ss, &ssf);
1110 cpu = timeval_to_cpu (&real, &user, &sys);
1112 # if defined (HAVE_TIMES)
1113 tafter = times (&after);
1115 real = tafter - tbefore;
1116 clock_t_to_secs (real, &rs, &rsf);
1118 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1119 clock_t_to_secs (user, &us, &usf);
1121 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1122 clock_t_to_secs (sys, &ss, &ssf);
1124 cpu = ((user + sys) * 10000) / real;
1128 rsf = usf = ssf = cpu = 0;
1133 time_format = POSIX_TIMEFORMAT;
1134 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1135 time_format = BASH_TIMEFORMAT;
1137 if (time_format && *time_format)
1138 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1142 #endif /* COMMAND_TIMING */
1145 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1147 int asynchronous, pipe_in, pipe_out;
1148 struct fd_bitmap *fds_to_close;
1150 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1152 struct fd_bitmap *fd_bitmap;
1154 #if defined (JOB_CONTROL)
1156 BLOCK_CHILD (set, oset);
1157 #endif /* JOB_CONTROL */
1159 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1164 while (cmd && cmd->type == cm_connection &&
1165 cmd->value.Connection && cmd->value.Connection->connector == '|')
1167 /* Make a pipeline between the two commands. */
1168 if (pipe (fildes) < 0)
1170 sys_error ("pipe error");
1171 #if defined (JOB_CONTROL)
1172 terminate_current_pipeline ();
1173 kill_current_pipeline ();
1174 #endif /* JOB_CONTROL */
1175 last_command_exit_value = EXECUTION_FAILURE;
1176 /* The unwind-protects installed below will take care
1177 of closing all of the open file descriptors. */
1178 throw_to_top_level ();
1179 return (EXECUTION_FAILURE); /* XXX */
1182 /* Here is a problem: with the new file close-on-exec
1183 code, the read end of the pipe (fildes[0]) stays open
1184 in the first process, so that process will never get a
1185 SIGPIPE. There is no way to signal the first process
1186 that it should close fildes[0] after forking, so it
1187 remains open. No SIGPIPE is ever sent because there
1188 is still a file descriptor open for reading connected
1189 to the pipe. We take care of that here. This passes
1190 around a bitmap of file descriptors that must be
1191 closed after making a child process in execute_simple_command. */
1193 /* We need fd_bitmap to be at least as big as fildes[0].
1194 If fildes[0] is less than fds_to_close->size, then
1195 use fds_to_close->size. */
1196 new_bitmap_size = (fildes[0] < fds_to_close->size)
1197 ? fds_to_close->size
1200 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1202 /* Now copy the old information into the new bitmap. */
1203 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1205 /* And mark the pipe file descriptors to be closed. */
1206 fd_bitmap->bitmap[fildes[0]] = 1;
1208 /* In case there are pipe or out-of-processes errors, we
1209 want all these file descriptors to be closed when
1210 unwind-protects are run, and the storage used for the
1211 bitmaps freed up. */
1212 begin_unwind_frame ("pipe-file-descriptors");
1213 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1214 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1216 add_unwind_protect (close, prev);
1217 dummyfd = fildes[1];
1218 add_unwind_protect (close, dummyfd);
1220 #if defined (JOB_CONTROL)
1221 add_unwind_protect (restore_signal_mask, oset);
1222 #endif /* JOB_CONTROL */
1224 if (ignore_return && cmd->value.Connection->first)
1225 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1226 execute_command_internal (cmd->value.Connection->first, asynchronous,
1227 prev, fildes[1], fd_bitmap);
1235 dispose_fd_bitmap (fd_bitmap);
1236 discard_unwind_frame ("pipe-file-descriptors");
1238 cmd = cmd->value.Connection->second;
1241 /* Now execute the rightmost command in the pipeline. */
1242 if (ignore_return && cmd)
1243 cmd->flags |= CMD_IGNORE_RETURN;
1244 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1249 #if defined (JOB_CONTROL)
1250 UNBLOCK_CHILD (oset);
1253 return (exec_result);
1257 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1259 int asynchronous, pipe_in, pipe_out;
1260 struct fd_bitmap *fds_to_close;
1262 REDIRECT *tr, *tl, *rp;
1263 COMMAND *tc, *second;
1264 int ignore_return, exec_result;
1266 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1268 switch (command->value.Connection->connector)
1270 /* Do the first command asynchronously. */
1272 tc = command->value.Connection->first;
1274 return (EXECUTION_SUCCESS);
1278 if (ignore_return && tc)
1279 tc->flags |= CMD_IGNORE_RETURN;
1281 /* If this shell was compiled without job control support, if
1282 the shell is not running interactively, if we are currently
1283 in a subshell via `( xxx )', or if job control is not active
1284 then the standard input for an asynchronous command is
1285 forced to /dev/null. */
1286 #if defined (JOB_CONTROL)
1287 if ((!interactive_shell || subshell_environment || !job_control) && !stdin_redir)
1290 #endif /* JOB_CONTROL */
1292 rd.filename = make_bare_word ("/dev/null");
1293 tr = make_redirection (0, r_inputa_direction, rd);
1294 tr->next = tc->redirects;
1298 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1300 #if defined (JOB_CONTROL)
1301 if ((!interactive_shell || subshell_environment || !job_control) && !stdin_redir)
1304 #endif /* JOB_CONTROL */
1306 /* Remove the redirection we added above. It matters,
1307 especially for loops, which call execute_command ()
1308 multiple times with the same command. */
1313 tc->redirects = tc->redirects->next;
1315 while (tc->redirects && tc->redirects != rp);
1317 tl->next = (REDIRECT *)NULL;
1318 dispose_redirects (tr);
1321 second = command->value.Connection->second;
1325 second->flags |= CMD_IGNORE_RETURN;
1327 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1332 /* Just call execute command on both sides. */
1336 if (command->value.Connection->first)
1337 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1338 if (command->value.Connection->second)
1339 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1342 execute_command (command->value.Connection->first);
1344 exec_result = execute_command_internal (command->value.Connection->second,
1345 asynchronous, pipe_in, pipe_out,
1350 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1357 /* If we have something like `a && b &' or `a || b &', run the
1358 && or || stuff in a subshell. Force a subshell and just call
1359 execute_command_internal again. Leave asynchronous on
1360 so that we get a report from the parent shell about the
1362 command->flags |= CMD_FORCE_SUBSHELL;
1363 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1367 /* Execute the first command. If the result of that is successful
1368 and the connector is AND_AND, or the result is not successful
1369 and the connector is OR_OR, then execute the second command,
1370 otherwise return. */
1372 if (command->value.Connection->first)
1373 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1375 exec_result = execute_command (command->value.Connection->first);
1377 if (((command->value.Connection->connector == AND_AND) &&
1378 (exec_result == EXECUTION_SUCCESS)) ||
1379 ((command->value.Connection->connector == OR_OR) &&
1380 (exec_result != EXECUTION_SUCCESS)))
1382 if (ignore_return && command->value.Connection->second)
1383 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1385 exec_result = execute_command (command->value.Connection->second);
1390 programming_error ("execute_connection: bad connector `%d'", command->value.Connection->connector);
1391 jump_to_top_level (DISCARD);
1392 exec_result = EXECUTION_FAILURE;
1398 #if defined (JOB_CONTROL)
1402 if (!interactive_shell) \
1403 reap_dead_jobs (); \
1406 #else /* !JOB_CONTROL */
1410 if (!interactive_shell) \
1411 cleanup_dead_jobs (); \
1414 #endif /* !JOB_CONTROL */
1417 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1420 execute_for_command (for_command)
1421 FOR_COM *for_command;
1423 register WORD_LIST *releaser, *list;
1428 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1431 if (check_identifier (for_command->name, 1) == 0)
1433 if (posixly_correct && interactive_shell == 0)
1435 last_command_exit_value = EX_USAGE;
1436 jump_to_top_level (EXITPROG);
1438 return (EXECUTION_FAILURE);
1442 identifier = for_command->name->word;
1444 list = releaser = expand_words_no_vars (for_command->map_list);
1446 begin_unwind_frame ("for");
1447 add_unwind_protect (dispose_words, releaser);
1450 if (lexical_scoping)
1452 old_value = copy_variable (find_variable (identifier));
1454 add_unwind_protect (dispose_variable, old_value);
1458 if (for_command->flags & CMD_IGNORE_RETURN)
1459 for_command->action->flags |= CMD_IGNORE_RETURN;
1461 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1464 this_command_name = (char *)NULL;
1465 v = bind_variable (identifier, list->word->word);
1468 if (interactive_shell == 0 && posixly_correct)
1470 last_command_exit_value = EXECUTION_FAILURE;
1471 jump_to_top_level (FORCE_EOF);
1475 run_unwind_frame ("for");
1476 return (EXECUTION_FAILURE);
1479 retval = execute_command (for_command->action);
1500 if (lexical_scoping)
1503 makunbound (identifier, shell_variables);
1506 SHELL_VAR *new_value;
1508 new_value = bind_variable (identifier, value_cell(old_value));
1509 new_value->attributes = old_value->attributes;
1510 dispose_variable (old_value);
1515 dispose_words (releaser);
1516 discard_unwind_frame ("for");
1520 #if defined (SELECT_COMMAND)
1521 static int LINES, COLS, tabsize;
1523 #define RP_SPACE ") "
1524 #define RP_SPACE_LEN 2
1526 /* XXX - does not handle numbers > 1000000 at all. */
1527 #define NUMBER_LEN(s) \
1531 : ((s < 10000) ? 4 \
1532 : ((s < 100000) ? 5 \
1536 print_index_and_element (len, ind, list)
1540 register WORD_LIST *l;
1545 for (i = ind, l = list; l && --i; l = l->next)
1547 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1548 return (STRLEN (l->word->word));
1557 if ((to / tabsize) > (from / tabsize))
1559 putc ('\t', stderr);
1560 from += tabsize - from % tabsize;
1571 print_select_list (list, list_len, max_elem_len, indices_len)
1573 int list_len, max_elem_len, indices_len;
1575 int ind, row, elem_len, pos, cols, rows;
1576 int first_column_indices_len, other_indices_len;
1580 putc ('\n', stderr);
1584 cols = max_elem_len ? COLS / max_elem_len : 1;
1587 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1588 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1596 first_column_indices_len = NUMBER_LEN (rows);
1597 other_indices_len = indices_len;
1599 for (row = 0; row < rows; row++)
1605 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1606 elem_len = print_index_and_element (indices_len, ind + 1, list);
1607 elem_len += indices_len + RP_SPACE_LEN;
1609 if (ind >= list_len)
1611 indent (pos + elem_len, pos + max_elem_len);
1612 pos += max_elem_len;
1614 putc ('\n', stderr);
1618 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1619 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1620 If the number is between 1 and LIST_LEN, return that selection. If EOF
1621 is read, return a null string. If a blank line is entered, the loop is
1624 select_query (list, list_len, prompt)
1629 int max_elem_len, indices_len, len, reply;
1631 char *repl_string, *t;
1633 t = get_string_value ("LINES");
1634 LINES = (t && *t) ? atoi (t) : 24;
1635 t = get_string_value ("COLUMNS");
1636 COLS = (t && *t) ? atoi (t) : 80;
1639 t = get_string_value ("TABSIZE");
1640 tabsize = (t && *t) ? atoi (t) : 8;
1648 for (l = list; l; l = l->next)
1650 len = STRLEN (l->word->word);
1651 if (len > max_elem_len)
1654 indices_len = NUMBER_LEN (list_len);
1655 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1659 print_select_list (list, list_len, max_elem_len, indices_len);
1660 fprintf (stderr, "%s", prompt);
1664 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1667 return ((char *)NULL);
1669 repl_string = get_string_value ("REPLY");
1670 if (*repl_string == 0)
1672 reply = atoi (repl_string);
1673 if (reply < 1 || reply > list_len)
1676 for (l = list; l && --reply; l = l->next)
1678 return (l->word->word);
1682 /* Execute a SELECT command. The syntax is:
1683 SELECT word IN list DO command_list DONE
1684 Only `break' or `return' in command_list will terminate
1687 execute_select_command (select_command)
1688 SELECT_COM *select_command;
1690 WORD_LIST *releaser, *list;
1692 char *identifier, *ps3_prompt, *selection;
1693 int retval, list_len, return_val;
1695 if (check_identifier (select_command->name, 1) == 0)
1696 return (EXECUTION_FAILURE);
1699 identifier = select_command->name->word;
1701 /* command and arithmetic substitution, parameter and variable expansion,
1702 word splitting, pathname expansion, and quote removal. */
1703 list = releaser = expand_words_no_vars (select_command->map_list);
1704 list_len = list_length (list);
1705 if (list == 0 || list_len == 0)
1708 dispose_words (list);
1709 return (EXECUTION_SUCCESS);
1712 begin_unwind_frame ("select");
1713 add_unwind_protect (dispose_words, releaser);
1715 if (select_command->flags & CMD_IGNORE_RETURN)
1716 select_command->action->flags |= CMD_IGNORE_RETURN;
1718 retval = EXECUTION_SUCCESS;
1720 unwind_protect_int (return_catch_flag);
1721 unwind_protect_jmp_buf (return_catch);
1722 return_catch_flag++;
1726 ps3_prompt = get_string_value ("PS3");
1727 if (ps3_prompt == 0)
1731 selection = select_query (list, list_len, ps3_prompt);
1736 v = bind_variable (identifier, selection);
1739 if (interactive_shell == 0 && posixly_correct)
1741 last_command_exit_value = EXECUTION_FAILURE;
1742 jump_to_top_level (FORCE_EOF);
1746 run_unwind_frame ("select");
1747 return (EXECUTION_FAILURE);
1751 return_val = setjmp (return_catch);
1755 retval = return_catch_value;
1759 retval = execute_command (select_command->action);
1773 run_unwind_frame ("select");
1776 #endif /* SELECT_COMMAND */
1778 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1779 The pattern_list is a linked list of pattern clauses; each clause contains
1780 some patterns to compare word_desc against, and an associated command to
1783 execute_case_command (case_command)
1784 CASE_COM *case_command;
1786 register WORD_LIST *list;
1787 WORD_LIST *wlist, *es;
1788 PATTERN_LIST *clauses;
1789 char *word, *pattern;
1790 int retval, match, ignore_return;
1792 /* Posix.2 specifies that the WORD is tilde expanded. */
1793 if (member ('~', case_command->word->word))
1795 word = bash_tilde_expand (case_command->word->word);
1796 free (case_command->word->word);
1797 case_command->word->word = word;
1800 wlist = expand_word_no_split (case_command->word, 0);
1801 word = wlist ? string_list (wlist) : savestring ("");
1802 dispose_words (wlist);
1804 retval = EXECUTION_SUCCESS;
1805 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
1807 begin_unwind_frame ("case");
1808 add_unwind_protect ((Function *)xfree, word);
1810 #define EXIT_CASE() goto exit_case_command
1812 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
1815 for (list = clauses->patterns; list; list = list->next)
1817 /* Posix.2 specifies to tilde expand each member of the pattern
1819 if (member ('~', list->word->word))
1821 pattern = bash_tilde_expand (list->word->word);
1822 free (list->word->word);
1823 list->word->word = pattern;
1826 es = expand_word_leave_quoted (list->word, 0);
1828 if (es && es->word && es->word->word && *(es->word->word))
1829 pattern = quote_string_for_globbing (es->word->word, 1);
1832 pattern = xmalloc (1);
1836 /* Since the pattern does not undergo quote removal (as per
1837 Posix.2, section 3.9.4.3), the fnmatch () call must be able
1838 to recognize backslashes as escape characters. */
1839 match = fnmatch (pattern, word, 0) != FNM_NOMATCH;
1846 if (clauses->action && ignore_return)
1847 clauses->action->flags |= CMD_IGNORE_RETURN;
1848 retval = execute_command (clauses->action);
1858 discard_unwind_frame ("case");
1865 /* The WHILE command. Syntax: WHILE test DO action; DONE.
1866 Repeatedly execute action while executing test produces
1867 EXECUTION_SUCCESS. */
1869 execute_while_command (while_command)
1870 WHILE_COM *while_command;
1872 return (execute_while_or_until (while_command, CMD_WHILE));
1875 /* UNTIL is just like WHILE except that the test result is negated. */
1877 execute_until_command (while_command)
1878 WHILE_COM *while_command;
1880 return (execute_while_or_until (while_command, CMD_UNTIL));
1883 /* The body for both while and until. The only difference between the
1884 two is that the test value is treated differently. TYPE is
1885 CMD_WHILE or CMD_UNTIL. The return value for both commands should
1886 be EXECUTION_SUCCESS if no commands in the body are executed, and
1887 the status of the last command executed in the body otherwise. */
1889 execute_while_or_until (while_command, type)
1890 WHILE_COM *while_command;
1893 int return_value, body_status;
1895 body_status = EXECUTION_SUCCESS;
1898 while_command->test->flags |= CMD_IGNORE_RETURN;
1899 if (while_command->flags & CMD_IGNORE_RETURN)
1900 while_command->action->flags |= CMD_IGNORE_RETURN;
1904 return_value = execute_command (while_command->test);
1907 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
1909 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
1913 body_status = execute_command (while_command->action);
1931 return (body_status);
1934 /* IF test THEN command [ELSE command].
1935 IF also allows ELIF in the place of ELSE IF, but
1936 the parser makes *that* stupidity transparent. */
1938 execute_if_command (if_command)
1943 if_command->test->flags |= CMD_IGNORE_RETURN;
1944 return_value = execute_command (if_command->test);
1946 if (return_value == EXECUTION_SUCCESS)
1950 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
1951 if_command->true_case->flags |= CMD_IGNORE_RETURN;
1953 return (execute_command (if_command->true_case));
1959 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
1960 if_command->false_case->flags |= CMD_IGNORE_RETURN;
1962 return (execute_command (if_command->false_case));
1974 var = bind_variable ("_", arg);
1975 var->attributes &= ~att_exported;
1978 /* Execute a null command. Fork a subshell if the command uses pipes or is
1979 to be run asynchronously. This handles all the side effects that are
1980 supposed to take place. */
1982 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
1983 REDIRECT *redirects;
1984 int pipe_in, pipe_out, async, old_last_command_subst_pid;
1986 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
1988 /* We have a null command, but we really want a subshell to take
1989 care of it. Just fork, do piping and redirections, and exit. */
1990 if (make_child ((char *)NULL, async) == 0)
1992 /* Cancel traps, in trap.c. */
1993 restore_original_signals (); /* XXX */
1995 do_piping (pipe_in, pipe_out);
1997 subshell_environment = SUBSHELL_ASYNC;
1999 if (do_redirections (redirects, 1, 0, 0) == 0)
2000 exit (EXECUTION_SUCCESS);
2002 exit (EXECUTION_FAILURE);
2006 close_pipes (pipe_in, pipe_out);
2007 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2008 unlink_fifo_list ();
2010 return (EXECUTION_SUCCESS);
2015 /* Even if there aren't any command names, pretend to do the
2016 redirections that are specified. The user expects the side
2017 effects to take place. If the redirections fail, then return
2018 failure. Otherwise, if a command substitution took place while
2019 expanding the command or a redirection, return the value of that
2020 substitution. Otherwise, return EXECUTION_SUCCESS. */
2022 if (do_redirections (redirects, 0, 0, 0) != 0)
2023 return (EXECUTION_FAILURE);
2024 else if (old_last_command_subst_pid != last_command_subst_pid)
2025 return (last_command_exit_value);
2027 return (EXECUTION_SUCCESS);
2031 /* This is a hack to suppress word splitting for assignment statements
2032 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2034 fix_assignment_words (words)
2043 b = builtin_address_internal (words->word->word);
2044 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2047 for (w = words; w; w = w->next)
2048 if (w->word->flags & W_ASSIGNMENT)
2049 w->word->flags |= W_NOSPLIT;
2052 /* The meaty part of all the executions. We have to start hacking the
2053 real execution of commands here. Fork a process, set things up,
2054 execute the command. */
2056 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2057 SIMPLE_COM *simple_command;
2058 int pipe_in, pipe_out, async;
2059 struct fd_bitmap *fds_to_close;
2061 WORD_LIST *words, *lastword;
2062 char *command_line, *lastarg, *temp;
2063 int first_word_quoted, result, builtin_is_special;
2064 pid_t old_last_command_subst_pid;
2068 result = EXECUTION_SUCCESS;
2069 special_builtin_failed = builtin_is_special = 0;
2071 /* If we're in a function, update the line number information. */
2072 if (variable_context)
2073 line_number = simple_command->line - function_line_number;
2075 /* Remember what this command line looks like at invocation. */
2076 command_string_index = 0;
2077 print_simple_command (simple_command);
2078 command_line = xmalloc (1 + strlen (the_printed_command));
2079 strcpy (command_line, the_printed_command);
2082 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2084 old_last_command_subst_pid = last_command_subst_pid;
2086 /* If we are re-running this as the result of executing the `command'
2087 builtin, do not expand the command words a second time. */
2088 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2090 current_fds_to_close = fds_to_close;
2091 fix_assignment_words (simple_command->words);
2092 words = expand_words (simple_command->words);
2093 current_fds_to_close = (struct fd_bitmap *)NULL;
2096 words = copy_word_list (simple_command->words);
2098 /* It is possible for WORDS not to have anything left in it.
2099 Perhaps all the words consisted of `$foo', and there was
2100 no variable `$foo'. */
2103 result = execute_null_command (simple_command->redirects,
2104 pipe_in, pipe_out, async,
2105 old_last_command_subst_pid);
2106 FREE (command_line);
2107 bind_lastarg ((char *)NULL);
2111 lastarg = (char *)NULL;
2113 begin_unwind_frame ("simple-command");
2115 if (echo_command_at_execute)
2116 xtrace_print_word_list (words);
2118 builtin = (Function *)NULL;
2119 func = (SHELL_VAR *)NULL;
2120 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2122 /* Posix.2 says special builtins are found before functions. We
2123 don't set builtin_is_special anywhere other than here, because
2124 this path is followed only when the `command' builtin is *not*
2125 being used, and we don't want to exit the shell if a special
2126 builtin executed with `command builtin' fails. `command' is not
2127 a special builtin. */
2128 if (posixly_correct)
2130 builtin = find_special_builtin (words->word->word);
2132 builtin_is_special = 1;
2135 func = find_function (words->word->word);
2138 add_unwind_protect (dispose_words, words);
2141 /* Bind the last word in this command to "$_" after execution. */
2142 for (lastword = words; lastword->next; lastword = lastword->next)
2144 lastarg = lastword->word->word;
2146 #if defined (JOB_CONTROL)
2147 /* Is this command a job control related thing? */
2148 if (words->word->word[0] == '%')
2150 this_command_name = async ? "bg" : "fg";
2151 last_shell_builtin = this_shell_builtin;
2152 this_shell_builtin = builtin_address (this_command_name);
2153 result = (*this_shell_builtin) (words);
2157 /* One other possiblilty. The user may want to resume an existing job.
2158 If they do, find out whether this word is a candidate for a running
2160 if (job_control && async == 0 &&
2161 !first_word_quoted &&
2163 words->word->word[0] &&
2164 !simple_command->redirects &&
2165 pipe_in == NO_PIPE &&
2166 pipe_out == NO_PIPE &&
2167 (temp = get_string_value ("auto_resume")))
2171 int wl, cl, exact, substring, match, started_status;
2172 register PROCESS *p;
2174 word = words->word->word;
2175 exact = STREQ (temp, "exact");
2176 substring = STREQ (temp, "substring");
2178 for (i = job_slots - 1; i > -1; i--)
2180 if (jobs[i] == 0 || (JOBSTATE (i) != JSTOPPED))
2188 cl = strlen (p->command);
2189 match = STREQN (p->command, word, cl);
2192 match = strindex (p->command, word) != (char *)0;
2194 match = STREQN (p->command, word, wl);
2202 run_unwind_frame ("simple-command");
2203 this_command_name = "fg";
2204 last_shell_builtin = this_shell_builtin;
2205 this_shell_builtin = builtin_address ("fg");
2207 started_status = start_job (i, 1);
2208 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2210 while (p != jobs[i]->pipe);
2213 #endif /* JOB_CONTROL */
2215 /* Remember the name of this command globally. */
2216 this_command_name = words->word->word;
2220 /* This command could be a shell builtin or a user-defined function.
2221 We have already found special builtins by this time, so we do not
2222 set builtin_is_special. If this is a function or builtin, and we
2223 have pipes, then fork a subshell in here. Otherwise, just execute
2224 the command directly. */
2225 if (func == 0 && builtin == 0)
2226 builtin = find_shell_builtin (this_command_name);
2228 last_shell_builtin = this_shell_builtin;
2229 this_shell_builtin = builtin;
2231 if (builtin || func)
2233 if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
2235 if (make_child (command_line, async) == 0)
2237 /* reset_terminating_signals (); */ /* XXX */
2238 /* Cancel traps, in trap.c. */
2239 restore_original_signals ();
2242 setup_async_signals ();
2244 execute_subshell_builtin_or_function
2245 (words, simple_command->redirects, builtin, func,
2246 pipe_in, pipe_out, async, fds_to_close,
2247 simple_command->flags);
2251 close_pipes (pipe_in, pipe_out);
2252 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2253 unlink_fifo_list ();
2255 command_line = (char *)NULL; /* don't free this. */
2261 result = execute_builtin_or_function
2262 (words, builtin, func, simple_command->redirects, fds_to_close,
2263 simple_command->flags);
2266 if (result > EX_SHERRBASE)
2268 result = builtin_status (result);
2269 if (builtin_is_special)
2270 special_builtin_failed = 1;
2272 /* In POSIX mode, if there are assignment statements preceding
2273 a special builtin, they persist after the builtin
2275 if (posixly_correct && builtin_is_special && temporary_env)
2276 merge_temporary_env ();
2280 if (result == EX_USAGE)
2281 result = EX_BADUSAGE;
2282 else if (result > EX_SHERRBASE)
2283 result = EXECUTION_FAILURE;
2290 execute_disk_command (words, simple_command->redirects, command_line,
2291 pipe_in, pipe_out, async, fds_to_close,
2292 (simple_command->flags & CMD_NO_FORK));
2295 bind_lastarg (lastarg);
2296 FREE (command_line);
2297 run_unwind_frame ("simple-command");
2301 /* Translate the special builtin exit statuses. We don't really need a
2302 function for this; it's a placeholder for future work. */
2304 builtin_status (result)
2318 r = EXECUTION_FAILURE;
2321 r = EXECUTION_SUCCESS;
2328 execute_builtin (builtin, words, flags, subshell)
2331 int flags, subshell;
2333 int old_e_flag, result;
2335 old_e_flag = exit_immediately_on_error;
2336 /* The eval builtin calls parse_and_execute, which does not know about
2337 the setting of flags, and always calls the execution functions with
2338 flags that will exit the shell on an error if -e is set. If the
2339 eval builtin is being called, and we're supposed to ignore the exit
2340 value of the command, we turn the -e flag off ourselves, then
2341 restore it when the command completes. */
2342 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2344 begin_unwind_frame ("eval_builtin");
2345 unwind_protect_int (exit_immediately_on_error);
2346 exit_immediately_on_error = 0;
2349 /* The temporary environment for a builtin is supposed to apply to
2350 all commands executed by that builtin. Currently, this is a
2351 problem only with the `source' builtin. */
2352 if (builtin == source_builtin)
2355 begin_unwind_frame ("builtin_env");
2359 builtin_env = copy_array (temporary_env);
2361 add_unwind_protect (dispose_builtin_env, (char *)NULL);
2362 dispose_used_env_vars ();
2366 builtin_env = (char **)NULL;
2370 result = ((*builtin) (words->next));
2372 if (subshell == 0 && builtin == source_builtin)
2374 /* In POSIX mode, if any variable assignments precede the `.' builtin,
2375 they persist after the builtin completes, since `.' is a special
2377 if (posixly_correct && builtin_env)
2378 merge_builtin_env ();
2379 dispose_builtin_env ();
2380 discard_unwind_frame ("builtin_env");
2383 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2385 exit_immediately_on_error += old_e_flag;
2386 discard_unwind_frame ("eval_builtin");
2393 execute_function (var, words, flags, fds_to_close, async, subshell)
2396 int flags, subshell, async;
2397 struct fd_bitmap *fds_to_close;
2399 int return_val, result;
2403 tc = (COMMAND *)copy_command (function_cell (var));
2404 if (tc && (flags & CMD_IGNORE_RETURN))
2405 tc->flags |= CMD_IGNORE_RETURN;
2409 begin_unwind_frame ("function_calling");
2411 add_unwind_protect (pop_context, (char *)NULL);
2412 unwind_protect_int (line_number);
2413 unwind_protect_int (return_catch_flag);
2414 unwind_protect_jmp_buf (return_catch);
2415 add_unwind_protect (dispose_command, (char *)tc);
2416 unwind_protect_int (loop_level);
2419 debug_trap = (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2420 ? trap_list[DEBUG_TRAP]
2426 debug_trap = savestring (debug_trap);
2427 add_unwind_protect (set_debug_trap, debug_trap);
2429 restore_default_signal (DEBUG_TRAP);
2432 /* The temporary environment for a function is supposed to apply to
2433 all commands executed within the function body. */
2436 function_env = copy_array (temporary_env);
2438 add_unwind_protect (dispose_function_env, (char *)NULL);
2439 dispose_used_env_vars ();
2443 function_env = (char **)NULL;
2446 remember_args (words->next, 1);
2448 /* Number of the line on which the function body starts. */
2449 line_number = function_line_number = tc->line;
2453 #if defined (JOB_CONTROL)
2454 stop_pipeline (async, (COMMAND *)NULL);
2456 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
2458 if (fc && (flags & CMD_IGNORE_RETURN))
2459 fc->flags |= CMD_IGNORE_RETURN;
2466 return_catch_flag++;
2467 return_val = setjmp (return_catch);
2470 result = return_catch_value;
2472 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2475 run_unwind_frame ("function_calling");
2480 /* Execute a shell builtin or function in a subshell environment. This
2481 routine does not return; it only calls exit(). If BUILTIN is non-null,
2482 it points to a function to call to execute a shell builtin; otherwise
2483 VAR points at the body of a function to execute. WORDS is the arguments
2484 to the command, REDIRECTS specifies redirections to perform before the
2485 command is executed. */
2487 execute_subshell_builtin_or_function (words, redirects, builtin, var,
2488 pipe_in, pipe_out, async, fds_to_close,
2491 REDIRECT *redirects;
2494 int pipe_in, pipe_out, async;
2495 struct fd_bitmap *fds_to_close;
2500 /* A subshell is neither a login shell nor interactive. */
2501 login_shell = interactive = 0;
2503 subshell_environment = SUBSHELL_ASYNC;
2505 maybe_make_export_env (); /* XXX - is this needed? */
2507 #if defined (JOB_CONTROL)
2508 /* Eradicate all traces of job control after we fork the subshell, so
2509 all jobs begun by this subshell are in the same process group as
2510 the shell itself. */
2512 /* Allow the output of `jobs' to be piped. */
2513 if (builtin == jobs_builtin && !async &&
2514 (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
2515 kill_current_pipeline ();
2517 without_job_control ();
2519 set_sigchld_handler ();
2520 #endif /* JOB_CONTROL */
2522 set_sigint_handler ();
2524 do_piping (pipe_in, pipe_out);
2527 close_fd_bitmap (fds_to_close);
2529 if (do_redirections (redirects, 1, 0, 0) != 0)
2530 exit (EXECUTION_FAILURE);
2534 /* Give builtins a place to jump back to on failure,
2535 so we don't go back up to main(). */
2536 result = setjmp (top_level);
2538 if (result == EXITPROG)
2539 exit (last_command_exit_value);
2541 exit (EXECUTION_FAILURE);
2544 r = execute_builtin (builtin, words, flags, 1);
2551 exit (execute_function (var, words, flags, fds_to_close, async, 1));
2554 /* Execute a builtin or function in the current shell context. If BUILTIN
2555 is non-null, it is the builtin command to execute, otherwise VAR points
2556 to the body of a function. WORDS are the command's arguments, REDIRECTS
2557 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2558 file descriptors to close.
2560 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2561 not undone before this function returns. */
2563 execute_builtin_or_function (words, builtin, var, redirects,
2564 fds_to_close, flags)
2568 REDIRECT *redirects;
2569 struct fd_bitmap *fds_to_close;
2573 REDIRECT *saved_undo_list;
2575 if (do_redirections (redirects, 1, 1, 0) != 0)
2577 cleanup_redirects (redirection_undo_list);
2578 redirection_undo_list = (REDIRECT *)NULL;
2579 dispose_exec_redirects ();
2580 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
2583 saved_undo_list = redirection_undo_list;
2585 /* Calling the "exec" builtin changes redirections forever. */
2586 if (builtin == exec_builtin)
2588 dispose_redirects (saved_undo_list);
2589 saved_undo_list = exec_redirection_undo_list;
2590 exec_redirection_undo_list = (REDIRECT *)NULL;
2593 dispose_exec_redirects ();
2595 if (saved_undo_list)
2597 begin_unwind_frame ("saved redirects");
2598 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
2601 redirection_undo_list = (REDIRECT *)NULL;
2604 result = execute_builtin (builtin, words, flags, 0);
2606 result = execute_function (var, words, flags, fds_to_close, 0, 0);
2608 if (saved_undo_list)
2610 redirection_undo_list = saved_undo_list;
2611 discard_unwind_frame ("saved redirects");
2614 if (redirection_undo_list)
2616 cleanup_redirects (redirection_undo_list);
2617 redirection_undo_list = (REDIRECT *)NULL;
2624 setup_async_signals ()
2626 #if defined (JOB_CONTROL)
2627 if (job_control == 0)
2630 set_signal_handler (SIGINT, SIG_IGN);
2631 set_signal_ignored (SIGINT);
2632 set_signal_handler (SIGQUIT, SIG_IGN);
2633 set_signal_ignored (SIGQUIT);
2637 /* Execute a simple command that is hopefully defined in a disk file
2642 3) look up the command
2645 6) If the execve failed, see if the file has executable mode set.
2646 If so, and it isn't a directory, then execute its contents as
2649 Note that the filename hashing stuff has to take place up here,
2650 in the parent. This is probably why the Bourne style shells
2651 don't handle it, since that would require them to go through
2652 this gnarly hair, for no good reason. */
2654 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
2655 async, fds_to_close, nofork)
2657 REDIRECT *redirects;
2659 int pipe_in, pipe_out, async;
2660 struct fd_bitmap *fds_to_close;
2661 int nofork; /* Don't fork, just exec, if no pipes */
2663 char *pathname, *command, **args;
2666 pathname = words->word->word;
2668 #if defined (RESTRICTED_SHELL)
2669 if (restricted && strchr (pathname, '/'))
2671 internal_error ("%s: restricted: cannot specify `/' in command names",
2673 last_command_exit_value = EXECUTION_FAILURE;
2676 #endif /* RESTRICTED_SHELL */
2678 command = search_for_command (pathname);
2682 maybe_make_export_env ();
2683 put_command_name_into_env (command);
2686 /* We have to make the child before we check for the non-existance
2687 of COMMAND, since we want the error messages to be redirected. */
2688 /* If we can get away without forking and there are no pipes to deal with,
2689 don't bother to fork, just directly exec the command. */
2690 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
2693 pid = make_child (savestring (command_line), async);
2697 int old_interactive;
2699 #if !defined (ARG_MAX) || ARG_MAX >= 10240
2700 if (posixly_correct == 0)
2701 put_gnu_argv_flags_into_env ((int)getpid (), glob_argv_flags);
2704 /* Cancel traps, in trap.c. */
2705 restore_original_signals ();
2707 /* restore_original_signals may have undone the work done
2708 by make_child to ensure that SIGINT and SIGQUIT are ignored
2709 in asynchronous children. */
2711 setup_async_signals ();
2713 do_piping (pipe_in, pipe_out);
2717 old_interactive = interactive;
2721 subshell_environment = SUBSHELL_FORK;
2723 /* This functionality is now provided by close-on-exec of the
2724 file descriptors manipulated by redirection and piping.
2725 Some file descriptors still need to be closed in all children
2726 because of the way bash does pipes; fds_to_close is a
2727 bitmap of all such file descriptors. */
2729 close_fd_bitmap (fds_to_close);
2731 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
2733 #if defined (PROCESS_SUBSTITUTION)
2734 /* Try to remove named pipes that may have been created as the
2735 result of redirections. */
2736 unlink_fifo_list ();
2737 #endif /* PROCESS_SUBSTITUTION */
2738 exit (EXECUTION_FAILURE);
2742 interactive = old_interactive;
2746 internal_error ("%s: command not found", pathname);
2747 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
2750 /* Execve expects the command name to be in args[0]. So we
2751 leave it there, in the same format that the user used to
2753 args = word_list_to_argv (words, 0, 0, (int *)NULL);
2754 exit (shell_execve (command, args, export_env));
2758 /* Make sure that the pipes are closed in the parent. */
2759 close_pipes (pipe_in, pipe_out);
2760 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2761 unlink_fifo_list ();
2767 #if !defined (HAVE_HASH_BANG_EXEC)
2768 /* If the operating system on which we're running does not handle
2769 the #! executable format, then help out. SAMPLE is the text read
2770 from the file, SAMPLE_LEN characters. COMMAND is the name of
2771 the script; it and ARGS, the arguments given by the user, will
2772 become arguments to the specified interpreter. ENV is the environment
2773 to pass to the interpreter.
2775 The word immediately following the #! is the interpreter to execute.
2776 A single argument to the interpreter is allowed. */
2778 execute_shell_script (sample, sample_len, command, args, env)
2779 unsigned char *sample;
2785 char *execname, *firstarg;
2786 int start, size_increment, larry;
2788 /* Find the name of the interpreter to exec. */
2789 for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
2793 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2798 execname = xmalloc (1 + larry);
2799 strncpy (execname, (char *)(sample + start), larry);
2800 execname[larry] = '\0';
2803 /* Now the argument, if any. */
2804 firstarg = (char *)NULL;
2806 whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2810 /* If there is more text on the line, then it is an argument for the
2812 if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
2815 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2819 firstarg = xmalloc (1 + larry);
2820 strncpy (firstarg, (char *)(sample + start), larry);
2821 firstarg[larry] = '\0';
2826 larry = array_len (args) + size_increment;
2828 args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
2830 for (i = larry - 1; i; i--)
2831 args[i] = args[i - size_increment];
2842 args[larry] = (char *)NULL;
2844 return (shell_execve (execname, args, env));
2846 #endif /* !HAVE_HASH_BANG_EXEC */
2848 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
2849 # define SETOSTYPE(x) __setostype(x)
2851 # define SETOSTYPE(x)
2854 /* Call execve (), handling interpreting shell scripts, and handling
2857 shell_execve (command, args, env)
2864 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
2865 execve (command, args, env);
2868 /* If we get to this point, then start checking out the file.
2869 Maybe it is something we can hack ourselves. */
2870 if (errno != ENOEXEC)
2873 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
2874 internal_error ("%s: is a directory", command);
2878 file_error (command);
2880 return (EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
2883 /* This file is executable.
2884 If it begins with #!, then help out people with losing operating
2885 systems. Otherwise, check to see if it is a binary file by seeing
2886 if the first line (or up to 80 characters) are in the ASCII set.
2887 Execute the contents as shell commands. */
2888 fd = open (command, O_RDONLY);
2891 unsigned char sample[80];
2894 sample_len = read (fd, (char *)sample, 80);
2897 if (sample_len == 0)
2898 return (EXECUTION_SUCCESS);
2900 /* Is this supposed to be an executable script?
2901 If so, the format of the line is "#! interpreter [argument]".
2902 A single argument is allowed. The BSD kernel restricts
2903 the length of the entire line to 32 characters (32 bytes
2904 being the size of the BSD exec header), but we allow 80
2908 #if !defined (HAVE_HASH_BANG_EXEC)
2909 if (sample[0] == '#' && sample[1] == '!')
2910 return (execute_shell_script (sample, sample_len, command, args, env));
2913 if (check_binary_file (sample, sample_len))
2915 internal_error ("%s: cannot execute binary file", command);
2916 return (EX_BINARY_FILE);
2921 larray = array_len (args) + 1;
2924 /* Forget about any aliases that we knew of. We are in a subshell. */
2925 delete_all_aliases ();
2928 #if defined (HISTORY)
2929 /* Forget about the history lines we have read. This is a non-interactive
2931 history_lines_this_session = 0;
2934 #if defined (JOB_CONTROL)
2935 /* Forget about the way job control was working. We are in a subshell. */
2936 without_job_control ();
2937 set_sigchld_handler ();
2938 #endif /* JOB_CONTROL */
2940 /* If we're not interactive, close the file descriptor from which we're
2941 reading the current shell script. */
2942 #if defined (BUFFERED_INPUT)
2943 if (interactive_shell == 0 && default_buffered_input >= 0)
2945 close_buffered_fd (default_buffered_input);
2946 default_buffered_input = bash_input.location.buffered_fd = -1;
2949 if (interactive_shell == 0 && default_input)
2951 fclose (default_input);
2952 default_input = (FILE *)NULL;
2956 set_sigint_handler ();
2958 /* Insert the name of this shell into the argument list. */
2959 args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
2961 for (i = larray - 1; i; i--)
2962 args[i] = args[i - 1];
2964 args[0] = shell_name;
2966 args[larray] = (char *)NULL;
2968 if (args[0][0] == '-')
2971 #if defined (RESTRICTED_SHELL)
2973 change_flag ('r', FLAG_OFF);
2978 /* Can't free subshell_argv[0]; that is shell_name. */
2979 for (i = 1; i < subshell_argc; i++)
2980 free (subshell_argv[i]);
2981 free (subshell_argv);
2984 dispose_command (currently_executing_command); /* XXX */
2985 currently_executing_command = (COMMAND *)NULL;
2987 subshell_argc = larray;
2988 subshell_argv = args;
2989 subshell_envp = env;
2991 unbind_args (); /* remove the positional parameters */
2993 longjmp (subshell_top_level, 1);
2997 execute_intern_function (name, function)
3003 if (check_identifier (name, posixly_correct) == 0)
3005 if (posixly_correct && interactive_shell == 0)
3007 last_command_exit_value = EX_USAGE;
3008 jump_to_top_level (EXITPROG);
3010 return (EXECUTION_FAILURE);
3013 var = find_function (name->word);
3014 if (var && readonly_p (var))
3016 internal_error ("%s: readonly function", var->name);
3017 return (EXECUTION_FAILURE);
3020 bind_function (name->word, function);
3021 return (EXECUTION_SUCCESS);
3024 #if defined (PROCESS_SUBSTITUTION)
3028 register int i, fd_table_size;
3030 fd_table_size = getdtablesize ();
3031 if (fd_table_size > 256) /* clamp to a reasonable value */
3032 fd_table_size = 256;
3034 for (i = 3; i < fd_table_size; i++)
3037 #endif /* PROCESS_SUBSTITUTION */
3040 close_pipes (in, out)
3049 /* Redirect input and output to be from and to the specified pipes.
3050 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3052 do_piping (pipe_in, pipe_out)
3053 int pipe_in, pipe_out;
3055 if (pipe_in != NO_PIPE)
3057 if (dup2 (pipe_in, 0) < 0)
3058 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
3062 if (pipe_out != NO_PIPE)
3064 if (pipe_out != REDIRECT_BOTH)
3066 if (dup2 (pipe_out, 1) < 0)
3067 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
3068 if (pipe_out == 0 || pipe_out > 1)
3072 if (dup2 (1, 2) < 0)
3073 sys_error ("cannot duplicate fd 1 to fd 2");
3078 redirection_error (temp, error)
3084 if (expandable_redirection_filename (temp))
3086 if (posixly_correct && !interactive_shell)
3087 disallow_filename_globbing++;
3088 filename = redirection_expand (temp->redirectee.filename);
3089 if (posixly_correct && !interactive_shell)
3090 disallow_filename_globbing--;
3092 filename = savestring (temp->redirectee.filename->word);
3095 filename = xmalloc (1);
3100 filename = itos (temp->redirectee.dest);
3104 case AMBIGUOUS_REDIRECT:
3105 internal_error ("%s: ambiguous redirect", filename);
3108 case NOCLOBBER_REDIRECT:
3109 internal_error ("%s: cannot overwrite existing file", filename);
3112 #if defined (RESTRICTED_SHELL)
3113 case RESTRICTED_REDIRECT:
3114 internal_error ("%s: restricted: cannot redirect output", filename);
3116 #endif /* RESTRICTED_SHELL */
3119 internal_error ("%s: %s", filename, strerror (error));
3126 /* Perform the redirections on LIST. If FOR_REAL, then actually make
3127 input and output file descriptors, otherwise just do whatever is
3128 neccessary for side effecting. INTERNAL says to remember how to
3129 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
3130 file descriptors opened in do_redirection () have their close-on-exec
3133 do_redirections (list, for_real, internal, set_clexec)
3135 int for_real, internal, set_clexec;
3142 if (redirection_undo_list)
3144 dispose_redirects (redirection_undo_list);
3145 redirection_undo_list = (REDIRECT *)NULL;
3147 if (exec_redirection_undo_list)
3148 dispose_exec_redirects ();
3151 for (temp = list; temp; temp = temp->next)
3153 error = do_redirection_internal (temp, for_real, internal, set_clexec);
3156 redirection_error (temp, error);
3163 /* Return non-zero if the redirection pointed to by REDIRECT has a
3164 redirectee.filename that can be expanded. */
3166 expandable_redirection_filename (redirect)
3169 switch (redirect->instruction)
3171 case r_output_direction:
3172 case r_appending_to:
3173 case r_input_direction:
3174 case r_inputa_direction:
3176 case r_input_output:
3177 case r_output_force:
3178 case r_duplicating_input_word:
3179 case r_duplicating_output_word:
3187 /* Expand the word in WORD returning a string. If WORD expands to
3188 multiple words (or no words), then return NULL. */
3190 redirection_expand (word)
3194 WORD_LIST *tlist1, *tlist2;
3196 tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
3197 tlist2 = expand_words_no_vars (tlist1);
3198 dispose_words (tlist1);
3200 if (!tlist2 || tlist2->next)
3202 /* We expanded to no words, or to more than a single word.
3203 Dispose of the word list and return NULL. */
3205 dispose_words (tlist2);
3206 return ((char *)NULL);
3208 result = string_list (tlist2); /* XXX savestring (tlist2->word->word)? */
3209 dispose_words (tlist2);
3214 write_here_document (fd, redirectee)
3216 WORD_DESC *redirectee;
3219 int document_len, fd2;
3221 register WORD_LIST *t, *tlist;
3223 /* Expand the text if the word that was specified had
3224 no quoting. The text that we expand is treated
3225 exactly as if it were surrounded by double quotes. */
3227 if (redirectee->flags & W_QUOTED)
3229 document = redirectee->word;
3230 document_len = strlen (document);
3231 /* Set errno to something reasonable if the write fails. */
3232 if (write (fd, document, document_len) < document_len)
3242 tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
3245 /* Try using buffered I/O (stdio) and writing a word
3246 at a time, letting stdio do the work of buffering
3247 for us rather than managing our own strings. Most
3248 stdios are not particularly fast, however -- this
3249 may need to be reconsidered later. */
3250 if ((fd2 = dup (fd)) < 0 || (fp = fdopen (fd2, "w")) == NULL)
3257 for (t = tlist; t; t = t->next)
3259 /* This is essentially the body of
3260 string_list_internal expanded inline. */
3261 document = t->word->word;
3262 document_len = strlen (document);
3264 putc (' ', fp); /* separator */
3265 fwrite (document, document_len, 1, fp);
3272 dispose_words (tlist);
3277 dispose_words (tlist);
3282 /* Do the specific redirection requested. Returns errno in case of error.
3283 If FOR_REAL is zero, then just do whatever is neccessary to produce the
3284 appropriate side effects. REMEMBERING, if non-zero, says to remember
3285 how to undo each redirection. If SET_CLEXEC is non-zero, then
3286 we set all file descriptors > 2 that we open to be close-on-exec. */
3288 do_redirection_internal (redirect, for_real, remembering, set_clexec)
3290 int for_real, remembering, set_clexec;
3292 WORD_DESC *redirectee;
3293 int redir_fd, fd, redirector, r;
3294 char *redirectee_word;
3295 enum r_instruction ri;
3296 REDIRECT *new_redirect;
3299 redirectee = redirect->redirectee.filename;
3300 redir_fd = redirect->redirectee.dest;
3301 redirector = redirect->redirector;
3302 ri = redirect->instruction;
3304 if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
3306 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
3307 the redirection into a new one and continue. */
3308 redirectee_word = redirection_expand (redirectee);
3310 if (redirectee_word == 0)
3311 return (AMBIGUOUS_REDIRECT);
3312 else if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
3315 new_redirect = make_redirection (redirector, r_close_this, rd);
3317 else if (all_digits (redirectee_word))
3319 if (ri == r_duplicating_input_word)
3321 rd.dest = atol (redirectee_word);
3322 new_redirect = make_redirection (redirector, r_duplicating_input, rd);
3326 rd.dest = atol (redirectee_word);
3327 new_redirect = make_redirection (redirector, r_duplicating_output, rd);
3330 else if (ri == r_duplicating_output_word && redirector == 1)
3332 if (posixly_correct == 0)
3334 rd.filename = make_bare_word (redirectee_word);
3335 new_redirect = make_redirection (1, r_err_and_out, rd);
3338 new_redirect = copy_redirect (redirect);
3342 free (redirectee_word);
3343 return (AMBIGUOUS_REDIRECT);
3346 free (redirectee_word);
3348 /* Set up the variables needed by the rest of the function from the
3350 if (new_redirect->instruction == r_err_and_out)
3354 /* Copy the word without allocating any memory that must be
3355 explicitly freed. */
3356 redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
3357 xbcopy ((char *)new_redirect->redirectee.filename,
3358 (char *)redirectee, sizeof (WORD_DESC));
3360 alloca_hack = (char *)
3361 alloca (1 + strlen (new_redirect->redirectee.filename->word));
3362 redirectee->word = alloca_hack;
3363 strcpy (redirectee->word, new_redirect->redirectee.filename->word);
3366 /* It's guaranteed to be an integer, and shouldn't be freed. */
3367 redirectee = new_redirect->redirectee.filename;
3369 redir_fd = new_redirect->redirectee.dest;
3370 redirector = new_redirect->redirector;
3371 ri = new_redirect->instruction;
3373 /* Overwrite the flags element of the old redirect with the new value. */
3374 redirect->flags = new_redirect->flags;
3375 dispose_redirects (new_redirect);
3380 case r_output_direction:
3381 case r_appending_to:
3382 case r_input_direction:
3383 case r_inputa_direction:
3384 case r_err_and_out: /* command &>filename */
3385 case r_input_output:
3386 case r_output_force:
3387 if (posixly_correct && !interactive_shell)
3388 disallow_filename_globbing++;
3389 redirectee_word = redirection_expand (redirectee);
3390 if (posixly_correct && !interactive_shell)
3391 disallow_filename_globbing--;
3393 if (redirectee_word == 0)
3394 return (AMBIGUOUS_REDIRECT);
3396 #if defined (RESTRICTED_SHELL)
3397 if (restricted && (WRITE_REDIRECT (ri)))
3399 free (redirectee_word);
3400 return (RESTRICTED_REDIRECT);
3402 #endif /* RESTRICTED_SHELL */
3404 /* If we are in noclobber mode, you are not allowed to overwrite
3405 existing files. Check first. */
3406 if (noclobber && OUTPUT_REDIRECT (ri))
3408 r = stat (redirectee_word, &finfo);
3410 if (r == 0 && (S_ISREG (finfo.st_mode)))
3412 free (redirectee_word);
3413 return (NOCLOBBER_REDIRECT);
3416 /* If the file was not present, make sure we open it exclusively
3417 so that if it is created before we open it, our open will fail. */
3419 redirect->flags |= O_EXCL;
3421 fd = open (redirectee_word, redirect->flags, 0666);
3423 if (fd < 0 && errno == EEXIST)
3425 free (redirectee_word);
3426 return (NOCLOBBER_REDIRECT);
3431 fd = open (redirectee_word, redirect->flags, 0666);
3433 if ((fd < 0) && (errno == EACCES))
3434 fd = open (redirectee_word, redirect->flags & ~O_CREAT, 0666);
3437 free (redirectee_word);
3445 /* Only setup to undo it if the thing to undo is active. */
3446 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
3447 add_undo_redirect (redirector);
3449 add_undo_close_redirect (redirector);
3451 #if defined (BUFFERED_INPUT)
3452 check_bash_input (redirector);
3455 if ((fd != redirector) && (dup2 (fd, redirector) < 0))
3458 #if defined (BUFFERED_INPUT)
3459 /* Do not change the buffered stream for an implicit redirection
3460 of /dev/null to fd 0 for asynchronous commands without job
3461 control (r_inputa_direction). */
3462 if (ri == r_input_direction || ri == r_input_output)
3463 duplicate_buffered_stream (fd, redirector);
3464 #endif /* BUFFERED_INPUT */
3467 * If we're remembering, then this is the result of a while, for
3468 * or until loop with a loop redirection, or a function/builtin
3469 * executing in the parent shell with a redirection. In the
3470 * function/builtin case, we want to set all file descriptors > 2
3471 * to be close-on-exec to duplicate the effect of the old
3472 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
3473 * both sh and ksh leave the file descriptors open across execs.
3474 * The Posix standard mentions only the exec builtin.
3476 if (set_clexec && (redirector > 2))
3477 SET_CLOSE_ON_EXEC (redirector);
3480 if (fd != redirector)
3482 #if defined (BUFFERED_INPUT)
3483 if (INPUT_REDIRECT (ri))
3484 close_buffered_fd (fd);
3486 #endif /* !BUFFERED_INPUT */
3487 close (fd); /* Don't close what we just opened! */
3490 /* If we are hacking both stdout and stderr, do the stderr
3491 redirection here. */
3492 if (ri == r_err_and_out)
3497 add_undo_redirect (2);
3498 if (dup2 (1, 2) < 0)
3504 case r_reading_until:
3505 case r_deblank_reading_until:
3506 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
3507 the new input. Place it in a temporary file. */
3512 /* Make the filename for the temp file. */
3513 sprintf (filename, "/tmp/t%d-sh", (int)getpid ());
3515 fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
3519 errno = r = 0; /* XXX */
3520 if (redirectee->word)
3521 r = write_here_document (fd, redirectee);
3527 /* Make the document really temporary. Also make it the input. */
3528 fd = open (filename, O_RDONLY, 0666);
3533 if (unlink (filename) < 0)
3543 /* Only setup to undo it if the thing to undo is active. */
3544 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
3545 add_undo_redirect (redirector);
3547 add_undo_close_redirect (redirector);
3549 #if defined (BUFFERED_INPUT)
3550 check_bash_input (redirector);
3552 if (fd != redirector && dup2 (fd, redirector) < 0)
3559 #if defined (BUFFERED_INPUT)
3560 duplicate_buffered_stream (fd, redirector);
3563 if (set_clexec && (redirector > 2))
3564 SET_CLOSE_ON_EXEC (redirector);
3567 #if defined (BUFFERED_INPUT)
3568 close_buffered_fd (fd);
3575 case r_duplicating_input:
3576 case r_duplicating_output:
3577 if (for_real && (redir_fd != redirector))
3580 /* Only setup to undo it if the thing to undo is active. */
3581 if (fcntl (redirector, F_GETFD, 0) != -1)
3582 add_undo_redirect (redirector);
3584 add_undo_close_redirect (redirector);
3586 #if defined (BUFFERED_INPUT)
3587 check_bash_input (redirector);
3589 /* This is correct. 2>&1 means dup2 (1, 2); */
3590 if (dup2 (redir_fd, redirector) < 0)
3593 #if defined (BUFFERED_INPUT)
3594 if (ri == r_duplicating_input)
3595 duplicate_buffered_stream (redir_fd, redirector);
3596 #endif /* BUFFERED_INPUT */
3598 /* First duplicate the close-on-exec state of redirectee. dup2
3599 leaves the flag unset on the new descriptor, which means it
3600 stays open. Only set the close-on-exec bit for file descriptors
3601 greater than 2 in any case, since 0-2 should always be open
3602 unless closed by something like `exec 2<&-'. */
3603 /* if ((already_set || set_unconditionally) && (ok_to_set))
3605 if (((fcntl (redir_fd, F_GETFD, 0) == 1) || set_clexec) &&
3607 SET_CLOSE_ON_EXEC (redirector);
3614 if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
3615 add_undo_redirect (redirector);
3617 #if defined (BUFFERED_INPUT)
3618 check_bash_input (redirector);
3619 close_buffered_fd (redirector);
3620 #else /* !BUFFERED_INPUT */
3622 #endif /* !BUFFERED_INPUT */
3629 #define SHELL_FD_BASE 10
3631 /* Remember the file descriptor associated with the slot FD,
3632 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
3633 before it is executed. Any redirections that need to be undone
3634 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
3635 are also saved on EXEC_REDIRECTION_UNDO_LIST. */
3637 add_undo_redirect (fd)
3640 int new_fd, clexec_flag;
3641 REDIRECT *new_redirect, *closer, *dummy_redirect;
3643 new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
3647 sys_error ("redirection error");
3651 clexec_flag = fcntl (fd, F_GETFD, 0);
3654 closer = make_redirection (new_fd, r_close_this, rd);
3655 dummy_redirect = copy_redirects (closer);
3657 rd.dest = (long)new_fd;
3658 new_redirect = make_redirection (fd, r_duplicating_output, rd);
3659 new_redirect->next = closer;
3661 closer->next = redirection_undo_list;
3662 redirection_undo_list = new_redirect;
3664 /* Save redirections that need to be undone even if the undo list
3665 is thrown away by the `exec' builtin. */
3666 add_exec_redirect (dummy_redirect);
3668 /* File descriptors used only for saving others should always be
3669 marked close-on-exec. Unfortunately, we have to preserve the
3670 close-on-exec state of the file descriptor we are saving, since
3671 fcntl (F_DUPFD) sets the new file descriptor to remain open
3672 across execs. If, however, the file descriptor whose state we
3673 are saving is <= 2, we can just set the close-on-exec flag,
3674 because file descriptors 0-2 should always be open-on-exec,
3675 and the restore above in do_redirection() will take care of it. */
3676 if (clexec_flag || fd < 3)
3677 SET_CLOSE_ON_EXEC (new_fd);
3682 /* Set up to close FD when we are finished with the current command
3683 and its redirections. */
3685 add_undo_close_redirect (fd)
3691 closer = make_redirection (fd, r_close_this, rd);
3692 closer->next = redirection_undo_list;
3693 redirection_undo_list = closer;
3697 add_exec_redirect (dummy_redirect)
3698 REDIRECT *dummy_redirect;
3700 dummy_redirect->next = exec_redirection_undo_list;
3701 exec_redirection_undo_list = dummy_redirect;
3704 #define u_mode_bits(x) (((x) & 0000700) >> 6)
3705 #define g_mode_bits(x) (((x) & 0000070) >> 3)
3706 #define o_mode_bits(x) (((x) & 0000007) >> 0)
3707 #define X_BIT(x) ((x) & 1)
3709 /* Return some flags based on information about this file.
3710 The EXISTS bit is non-zero if the file is found.
3711 The EXECABLE bit is non-zero the file is executble.
3712 Zero is returned if the file is not found. */
3718 static int user_id = -1;
3720 /* Determine whether this file exists or not. */
3721 if (stat (name, &finfo) < 0)
3724 /* If the file is a directory, then it is not "executable" in the
3725 sense of the shell. */
3726 if (S_ISDIR (finfo.st_mode))
3727 return (FS_EXISTS|FS_DIRECTORY);
3730 /* We have to use access(2) to determine access because AFS does not
3731 support Unix file system semantics. This may produce wrong
3732 answers for non-AFS files when ruid != euid. I hate AFS. */
3733 if (access (name, X_OK) == 0)
3734 return (FS_EXISTS | FS_EXECABLE);
3739 /* Find out if the file is actually executable. By definition, the
3740 only other criteria is that the file has an execute bit set that
3743 user_id = current_user.euid;
3745 /* Root only requires execute permission for any of owner, group or
3746 others to be able to exec a file. */
3751 bits = (u_mode_bits (finfo.st_mode) |
3752 g_mode_bits (finfo.st_mode) |
3753 o_mode_bits (finfo.st_mode));
3756 return (FS_EXISTS | FS_EXECABLE);
3759 /* If we are the owner of the file, the owner execute bit applies. */
3760 if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
3761 return (FS_EXISTS | FS_EXECABLE);
3763 /* If we are in the owning group, the group permissions apply. */
3764 if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
3765 return (FS_EXISTS | FS_EXECABLE);
3767 /* If `others' have execute permission to the file, then so do we,
3768 since we are also `others'. */
3769 if (X_BIT (o_mode_bits (finfo.st_mode)))
3770 return (FS_EXISTS | FS_EXECABLE);
3776 /* Return non-zero if FILE exists and is executable.
3777 Note that this function is the definition of what an
3778 executable file is; do not change this unless YOU know
3779 what an executable file is. */
3781 executable_file (file)
3786 s = file_status (file);
3787 return ((s & FS_EXECABLE) && ((s & FS_DIRECTORY) == 0));
3794 return (file_status (file) & FS_DIRECTORY);
3797 /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
3798 encounters a `.' as the directory pathname while scanning the
3799 list of possible pathnames; i.e., if `.' comes before the directory
3800 containing the file of interest. */
3801 int dot_found_in_search = 0;
3803 /* Locate the executable file referenced by NAME, searching along
3804 the contents of the shell PATH variable. Return a new string
3805 which is the full pathname to the file, or NULL if the file
3806 couldn't be found. If a file is found that isn't executable,
3807 and that is the only match, then return that. */
3809 find_user_command (name)
3812 return (find_user_command_internal (name, FS_EXEC_PREFERRED|FS_NODIRS));
3815 /* Locate the file referenced by NAME, searching along the contents
3816 of the shell PATH variable. Return a new string which is the full
3817 pathname to the file, or NULL if the file couldn't be found. This
3818 returns the first file found. */
3820 find_path_file (name)
3823 return (find_user_command_internal (name, FS_EXISTS));
3827 _find_user_command_internal (name, flags)
3834 /* Search for the value of PATH in both the temporary environment, and
3835 in the regular list of variables. */
3836 if (var = find_variable_internal ("PATH", 1)) /* XXX could be array? */
3837 path_list = value_cell (var);
3839 path_list = (char *)NULL;
3841 if (path_list == 0 || *path_list == '\0')
3842 return (savestring (name));
3844 return (find_user_command_in_path (name, path_list, flags));
3848 find_user_command_internal (name, flags)
3855 dotexe = xmalloc (strlen (name) + 5);
3856 strcpy (dotexe, name);
3857 strcat (dotexe, ".exe");
3858 res = _find_user_command_internal (dotexe, flags);
3861 res = _find_user_command_internal (name, flags);
3864 return (_find_user_command_internal (name, flags));
3868 /* Return the next element from PATH_LIST, a colon separated list of
3869 paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST;
3870 the index is modified by this function.
3871 Return the next element of PATH_LIST or NULL if there are no more. */
3873 get_next_path_element (path_list, path_index_pointer)
3875 int *path_index_pointer;
3879 path = extract_colon_unit (path_list, path_index_pointer);
3887 path = savestring (".");
3894 search_for_command (pathname)
3897 char *hashed_file, *command;
3901 hashed_file = command = (char *)NULL;
3903 /* If PATH is in the temporary environment for this command, don't use the
3904 hash table to search for the full pathname. */
3905 path = find_tempenv_variable ("PATH");
3906 temp_path = path != 0;
3908 /* Don't waste time trying to find hashed data for a pathname
3909 that is already completely specified or if we're using a command-
3910 specific value for PATH. */
3911 if (path == 0 && absolute_program (pathname) == 0)
3912 hashed_file = find_hashed_filename (pathname);
3914 /* If a command found in the hash table no longer exists, we need to
3915 look for it in $PATH. Thank you Posix.2. This forces us to stat
3916 every command found in the hash table. */
3918 if (hashed_file && (posixly_correct || check_hashed_filenames))
3920 st = file_status (hashed_file);
3921 if ((st ^ (FS_EXISTS | FS_EXECABLE)) != 0)
3923 remove_hashed_filename (pathname);
3924 hashed_file = (char *)NULL;
3929 command = savestring (hashed_file);
3930 else if (absolute_program (pathname))
3931 /* A command containing a slash is not looked up in PATH or saved in
3933 command = savestring (pathname);
3936 /* If $PATH is in the temporary environment, we've already retrieved
3937 it, so don't bother trying again. */
3939 command = find_user_command_in_path (pathname, value_cell (path),
3940 FS_EXEC_PREFERRED|FS_NODIRS);
3942 command = find_user_command (pathname);
3943 if (command && hashing_enabled && temp_path == 0)
3944 remember_filename (pathname, command, dot_found_in_search, 1);
3950 user_command_matches (name, flags, state)
3955 int path_index, name_len;
3956 char *path_list, *path_element, *match;
3957 struct stat dotinfo;
3958 static char **match_list = NULL;
3959 static int match_list_size = 0;
3960 static int match_index = 0;
3964 /* Create the list of matches. */
3965 if (match_list == 0)
3967 match_list_size = 5;
3968 match_list = (char **)xmalloc (match_list_size * sizeof(char *));
3971 /* Clear out the old match list. */
3972 for (i = 0; i < match_list_size; i++)
3975 /* We haven't found any files yet. */
3978 if (absolute_program (name))
3980 match_list[0] = find_absolute_program (name, flags);
3981 match_list[1] = (char *)NULL;
3982 path_list = (char *)NULL;
3986 name_len = strlen (name);
3987 file_to_lose_on = (char *)NULL;
3988 dot_found_in_search = 0;
3989 stat (".", &dotinfo);
3990 path_list = get_string_value ("PATH");
3994 while (path_list && path_list[path_index])
3996 path_element = get_next_path_element (path_list, &path_index);
3998 if (path_element == 0)
4001 match = find_in_path_element (name, path_element, flags, name_len, &dotinfo);
4003 free (path_element);
4008 if (match_index + 1 == match_list_size)
4010 match_list_size += 10;
4011 match_list = (char **)xrealloc (match_list, (match_list_size + 1) * sizeof (char *));
4014 match_list[match_index++] = match;
4015 match_list[match_index] = (char *)NULL;
4016 FREE (file_to_lose_on);
4017 file_to_lose_on = (char *)NULL;
4020 /* We haven't returned any strings yet. */
4024 match = match_list[match_index];
4032 /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
4033 This allocates new memory and returns it. */
4035 make_full_pathname (path, name, name_len)
4042 path_len = strlen (path);
4043 full_path = xmalloc (2 + path_len + name_len);
4044 strcpy (full_path, path);
4045 full_path[path_len] = '/';
4046 strcpy (full_path + path_len + 1, name);
4051 find_absolute_program (name, flags)
4057 st = file_status (name);
4059 /* If the file doesn't exist, quit now. */
4060 if ((st & FS_EXISTS) == 0)
4061 return ((char *)NULL);
4063 /* If we only care about whether the file exists or not, return
4064 this filename. Otherwise, maybe we care about whether this
4065 file is executable. If it is, and that is what we want, return it. */
4066 if ((flags & FS_EXISTS) || ((flags & FS_EXEC_ONLY) && (st & FS_EXECABLE)))
4067 return (savestring (name));
4069 return ((char *)NULL);
4073 find_in_path_element (name, path, flags, name_len, dotinfop)
4075 int flags, name_len;
4076 struct stat *dotinfop;
4079 char *full_path, *xpath;
4081 xpath = (*path == '~') ? bash_tilde_expand (path) : path;
4083 /* Remember the location of "." in the path, in all its forms
4084 (as long as they begin with a `.', e.g. `./.') */
4085 if (dot_found_in_search == 0 && *xpath == '.')
4086 dot_found_in_search = same_file (".", xpath, dotinfop, (struct stat *)NULL);
4088 full_path = make_full_pathname (xpath, name, name_len);
4090 status = file_status (full_path);
4095 if ((status & FS_EXISTS) == 0)
4098 return ((char *)NULL);
4101 /* The file exists. If the caller simply wants the first file, here it is. */
4102 if (flags & FS_EXISTS)
4105 /* If the file is executable, then it satisfies the cases of
4106 EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */
4107 if ((status & FS_EXECABLE) &&
4108 (((flags & FS_NODIRS) == 0) || ((status & FS_DIRECTORY) == 0)))
4110 FREE (file_to_lose_on);
4111 file_to_lose_on = (char *)NULL;
4115 /* The file is not executable, but it does exist. If we prefer
4116 an executable, then remember this one if it is the first one
4118 if ((flags & FS_EXEC_PREFERRED) && file_to_lose_on == 0)
4119 file_to_lose_on = savestring (full_path);
4121 /* If we want only executable files, or we don't want directories and
4122 this file is a directory, fail. */
4123 if ((flags & FS_EXEC_ONLY) || (flags & FS_EXEC_PREFERRED) ||
4124 ((flags & FS_NODIRS) && (status & FS_DIRECTORY)))
4127 return ((char *)NULL);
4133 /* This does the dirty work for find_user_command_internal () and
4134 user_command_matches ().
4135 NAME is the name of the file to search for.
4136 PATH_LIST is a colon separated list of directories to search.
4137 FLAGS contains bit fields which control the files which are eligible.
4139 FS_EXEC_ONLY: The file must be an executable to be found.
4140 FS_EXEC_PREFERRED: If we can't find an executable, then the
4141 the first file matching NAME will do.
4142 FS_EXISTS: The first file found will do.
4143 FS_NODIRS: Don't find any directories.
4146 find_user_command_in_path (name, path_list, flags)
4151 char *full_path, *path;
4152 int path_index, name_len;
4153 struct stat dotinfo;
4155 /* We haven't started looking, so we certainly haven't seen
4156 a `.' as the directory path yet. */
4157 dot_found_in_search = 0;
4159 if (absolute_program (name))
4161 full_path = find_absolute_program (name, flags);
4165 if (path_list == 0 || *path_list == '\0')
4166 return (savestring (name)); /* XXX */
4168 file_to_lose_on = (char *)NULL;
4169 name_len = strlen (name);
4170 stat (".", &dotinfo);
4173 while (path_list[path_index])
4175 /* Allow the user to interrupt out of a lengthy path search. */
4178 path = get_next_path_element (path_list, &path_index);
4182 /* Side effects: sets dot_found_in_search, possibly sets
4184 full_path = find_in_path_element (name, path, flags, name_len, &dotinfo);
4187 /* This should really be in find_in_path_element, but there isn't the
4188 right combination of flags. */
4189 if (full_path && is_directory (full_path))
4197 FREE (file_to_lose_on);
4202 /* We didn't find exactly what the user was looking for. Return
4203 the contents of FILE_TO_LOSE_ON which is NULL when the search
4204 required an executable, or non-NULL if a file was found and the
4205 search would accept a non-executable as a last resort. */
4206 return (file_to_lose_on);