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 2, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
28 #include "bashtypes.h"
30 # include <sys/file.h>
33 #include "posixstat.h"
36 # include <sys/param.h>
39 #if defined (HAVE_UNISTD_H)
43 #if defined (HAVE_LIMITS_H)
47 #include "posixtime.h"
49 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
50 # include <sys/resource.h>
53 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
54 # include <sys/times.h>
67 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
72 #include "execute_cmd.h"
79 #if defined (COND_COMMAND)
83 #include "builtins/common.h"
84 #include "builtins/builtext.h" /* list of builtins */
86 #include <glob/fnmatch.h>
87 #include <tilde/tilde.h>
89 #if defined (BUFFERED_INPUT)
98 # include "bashhist.h"
101 extern int posixly_correct;
102 extern int executing, breaking, continuing, loop_level;
103 extern int interactive, interactive_shell, login_shell, expand_aliases;
104 extern int parse_and_execute_level, running_trap, trap_line_number;
105 extern int command_string_index, variable_context, line_number;
106 extern int dot_found_in_search;
107 extern int already_making_children;
108 extern char **temporary_env, **function_env, **builtin_env;
109 extern char *the_printed_command, *shell_name;
110 extern pid_t last_command_subst_pid;
111 extern Function *last_shell_builtin, *this_shell_builtin;
112 extern char **subshell_argv, **subshell_envp;
113 extern int subshell_argc;
114 extern char *glob_argv_flags;
116 extern int getdtablesize ();
119 /* Static functions defined and used in this file. */
120 static void close_pipes (), do_piping (), bind_lastarg ();
121 static void cleanup_redirects ();
123 static int execute_for_command ();
124 #if defined (SELECT_COMMAND)
125 static int execute_select_command ();
127 #if defined (DPAREN_ARITHMETIC)
128 static int execute_arith_command ();
130 #if defined (COND_COMMAND)
131 static int execute_cond_command ();
133 #if defined (COMMAND_TIMING)
134 static int time_command ();
136 #if defined (ARITH_FOR_COMMAND)
137 static int execute_arith_for_command ();
139 static int execute_case_command ();
140 static int execute_while_command (), execute_until_command ();
141 static int execute_while_or_until ();
142 static int execute_if_command ();
143 static int execute_simple_command ();
144 static int execute_builtin (), execute_function ();
145 static int execute_builtin_or_function ();
146 static int builtin_status ();
147 static void execute_subshell_builtin_or_function ();
148 static void execute_disk_command ();
149 static int execute_connection ();
150 static int execute_intern_function ();
152 static int execute_in_subshell ();
154 /* The line number that the currently executing function starts on. */
155 static int function_line_number;
157 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
158 so that reader_loop can set it to zero before executing a command. */
161 /* The name of the command that is currently being executed.
162 `test' needs this, for example. */
163 char *this_command_name;
165 static COMMAND *currently_executing_command;
167 struct stat SB; /* used for debugging */
169 static int special_builtin_failed;
171 /* For catching RETURN in a function. */
172 int return_catch_flag;
173 int return_catch_value;
174 procenv_t return_catch;
176 /* The value returned by the last synchronous command. */
177 int last_command_exit_value;
179 /* The list of redirections to perform which will undo the redirections
180 that I made in the shell. */
181 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
183 /* The list of redirections to perform which will undo the internal
184 redirections performed by the `exec' builtin. These are redirections
185 that must be undone even when exec discards redirection_undo_list. */
186 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
188 /* Non-zero if we have just forked and are currently running in a subshell
190 int subshell_environment;
192 /* Currently-executing shell function. */
193 SHELL_VAR *this_shell_function;
195 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
197 #define FD_BITMAP_DEFAULT_SIZE 32L
199 /* Functions to allocate and deallocate the structures used to pass
200 information from the shell to its children about file descriptors
206 struct fd_bitmap *ret;
208 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
214 ret->bitmap = xmalloc (size);
215 bzero (ret->bitmap, size);
218 ret->bitmap = (char *)NULL;
223 dispose_fd_bitmap (fdbp)
224 struct fd_bitmap *fdbp;
231 close_fd_bitmap (fdbp)
232 struct fd_bitmap *fdbp;
238 for (i = 0; i < fdbp->size; i++)
247 /* Return the line number of the currently executing command. */
249 executing_line_number ()
251 if (executing && variable_context == 0 && currently_executing_command &&
252 currently_executing_command->type == cm_simple)
253 return currently_executing_command->value.Simple->line;
254 else if (running_trap)
255 return trap_line_number;
260 /* Execute the command passed in COMMAND. COMMAND is exactly what
261 read_command () places into GLOBAL_COMMAND. See "command.h" for the
262 details of the command structure.
264 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
265 return values. Executing a command with nothing in it returns
266 EXECUTION_SUCCESS. */
268 execute_command (command)
271 struct fd_bitmap *bitmap;
274 current_fds_to_close = (struct fd_bitmap *)NULL;
275 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
276 begin_unwind_frame ("execute-command");
277 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
279 /* Just do the command, but not asynchronously. */
280 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
282 dispose_fd_bitmap (bitmap);
283 discard_unwind_frame ("execute-command");
285 #if defined (PROCESS_SUBSTITUTION)
286 /* don't unlink fifos if we're in a shell function; wait until the function
288 if (variable_context == 0)
290 #endif /* PROCESS_SUBSTITUTION */
295 /* Return 1 if TYPE is a shell control structure type. */
297 shell_control_structure (type)
298 enum command_type type;
303 #if defined (ARITH_FOR_COMMAND)
306 #if defined (SELECT_COMMAND)
309 #if defined (DPAREN_ARITHMETIC)
312 #if defined (COND_COMMAND)
327 /* A function to use to unwind_protect the redirection undo list
330 cleanup_redirects (list)
333 do_redirections (list, 1, 0, 0);
334 dispose_redirects (list);
338 /* Function to unwind_protect the redirections for functions and builtins. */
340 cleanup_func_redirects (list)
343 do_redirections (list, 1, 0, 0);
348 dispose_exec_redirects ()
350 if (exec_redirection_undo_list)
352 dispose_redirects (exec_redirection_undo_list);
353 exec_redirection_undo_list = (REDIRECT *)NULL;
357 #if defined (JOB_CONTROL)
358 /* A function to restore the signal mask to its proper value when the shell
359 is interrupted or errors occur while creating a pipeline. */
361 restore_signal_mask (set)
364 return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
366 #endif /* JOB_CONTROL */
368 /* A debugging function that can be called from gdb, for instance. */
373 int f, fd_table_size;
375 fd_table_size = getdtablesize ();
377 fprintf (stderr, "pid %d open files:", (int)getpid ());
378 for (i = 3; i < fd_table_size; i++)
380 if ((f = fcntl (i, F_GETFD, 0)) != -1)
381 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
383 fprintf (stderr, "\n");
387 async_redirect_stdin ()
391 fd = open ("/dev/null", O_RDONLY);
398 internal_error ("cannot redirect standard input from /dev/null: %s", strerror (errno));
401 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
403 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
404 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
405 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
406 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
407 from and where it goes. They can have the value of NO_PIPE, which means
409 FDS_TO_CLOSE is a list of file descriptors to close once the child has
410 been forked. This list often contains the unusable sides of pipes, etc.
412 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
413 return values. Executing a command with nothing in it returns
414 EXECUTION_SUCCESS. */
416 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
420 int pipe_in, pipe_out;
421 struct fd_bitmap *fds_to_close;
423 int exec_result, invert, ignore_return, was_debug_trap;
424 REDIRECT *my_undo_list, *exec_undo_list;
425 volatile pid_t last_pid;
427 if (command == 0 || breaking || continuing || read_but_dont_execute)
428 return (EXECUTION_SUCCESS);
430 run_pending_traps ();
432 if (running_trap == 0)
433 currently_executing_command = command;
435 invert = (command->flags & CMD_INVERT_RETURN) != 0;
437 /* If we're inverting the return value and `set -e' has been executed,
438 we don't want a failing command to inadvertently cause the shell
440 if (exit_immediately_on_error && invert) /* XXX */
441 command->flags |= CMD_IGNORE_RETURN; /* XXX */
443 exec_result = EXECUTION_SUCCESS;
445 /* If a command was being explicitly run in a subshell, or if it is
446 a shell control-structure, and it has a pipe, then we do the command
448 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
449 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
451 if (command->type == cm_subshell ||
452 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
453 (shell_control_structure (command->type) &&
454 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
458 /* Fork a subshell, turn off the subshell bit, turn off job
459 control and call execute_command () on the command again. */
460 paren_pid = make_child (savestring (make_command_string (command)),
463 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
467 close_pipes (pipe_in, pipe_out);
469 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
472 /* If we are part of a pipeline, and not the end of the pipeline,
473 then we should simply return and let the last command in the
474 pipe be waited for. If we are not in a pipeline, or are the
475 last command in the pipeline, then we wait for the subshell
476 and return its exit status as usual. */
477 if (pipe_out != NO_PIPE)
478 return (EXECUTION_SUCCESS);
480 stop_pipeline (asynchronous, (COMMAND *)NULL);
482 if (asynchronous == 0)
484 last_command_exit_value = wait_for (paren_pid);
486 /* If we have to, invert the return value. */
488 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
490 : EXECUTION_SUCCESS);
492 exec_result = last_command_exit_value;
494 return (last_command_exit_value = exec_result);
498 DESCRIBE_PID (paren_pid);
500 run_pending_traps ();
502 return (EXECUTION_SUCCESS);
507 #if defined (COMMAND_TIMING)
508 if (command->flags & CMD_TIME_PIPELINE)
512 command->flags |= CMD_FORCE_SUBSHELL;
513 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
517 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
518 if (running_trap == 0)
519 currently_executing_command = (COMMAND *)NULL;
521 return (exec_result);
523 #endif /* COMMAND_TIMING */
525 if (shell_control_structure (command->type) && command->redirects)
526 stdin_redir = stdin_redirects (command->redirects);
528 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
530 if (do_redirections (command->redirects, 1, 1, 0) != 0)
532 cleanup_redirects (redirection_undo_list);
533 redirection_undo_list = (REDIRECT *)NULL;
534 dispose_exec_redirects ();
535 return (EXECUTION_FAILURE);
538 if (redirection_undo_list)
540 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
541 dispose_redirects (redirection_undo_list);
542 redirection_undo_list = (REDIRECT *)NULL;
545 my_undo_list = (REDIRECT *)NULL;
547 if (exec_redirection_undo_list)
549 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
550 dispose_redirects (exec_redirection_undo_list);
551 exec_redirection_undo_list = (REDIRECT *)NULL;
554 exec_undo_list = (REDIRECT *)NULL;
556 if (my_undo_list || exec_undo_list)
557 begin_unwind_frame ("loop_redirections");
560 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
563 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
565 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
569 switch (command->type)
573 /* We can't rely on this variable retaining its value across a
574 call to execute_simple_command if a longjmp occurs as the
575 result of a `return' builtin. This is true for sure with gcc. */
576 last_pid = last_made_pid;
577 was_debug_trap = signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0;
579 if (ignore_return && command->value.Simple)
580 command->value.Simple->flags |= CMD_IGNORE_RETURN;
581 if (command->flags & CMD_STDIN_REDIR)
582 command->value.Simple->flags |= CMD_STDIN_REDIR;
584 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
585 asynchronous, fds_to_close);
587 /* The temporary environment should be used for only the simple
588 command immediately following its definition. */
589 dispose_used_env_vars ();
591 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
592 /* Reclaim memory allocated with alloca () on machines which
593 may be using the alloca emulation code. */
595 #endif /* (ultrix && mips) || C_ALLOCA */
597 /* If we forked to do the command, then we must wait_for ()
600 /* XXX - this is something to watch out for if there are problems
601 when the shell is compiled without job control. */
602 if (already_making_children && pipe_out == NO_PIPE &&
603 last_pid != last_made_pid)
605 stop_pipeline (asynchronous, (COMMAND *)NULL);
609 DESCRIBE_PID (last_made_pid);
612 #if !defined (JOB_CONTROL)
613 /* Do not wait for asynchronous processes started from
615 if (last_made_pid != last_asynchronous_pid)
617 /* When executing a shell function that executes other
618 commands, this causes the last simple command in
619 the function to be waited for twice. */
620 exec_result = wait_for (last_made_pid);
621 #if defined (RECYCLES_PIDS)
622 /* LynxOS, for one, recycles pids very quickly -- so quickly
623 that a new process may have the same pid as the last one
624 created. This has been reported to fix the problem. */
625 if (exec_result == 0)
626 last_made_pid = NO_PID;
633 last_command_exit_value = exec_result;
637 if (ignore_return == 0 && invert == 0 &&
638 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
639 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
641 last_command_exit_value = exec_result;
642 run_pending_traps ();
643 jump_to_top_level (EXITPROG);
650 command->value.For->flags |= CMD_IGNORE_RETURN;
651 exec_result = execute_for_command (command->value.For);
654 #if defined (ARITH_FOR_COMMAND)
657 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
658 exec_result = execute_arith_for_command (command->value.ArithFor);
662 #if defined (SELECT_COMMAND)
665 command->value.Select->flags |= CMD_IGNORE_RETURN;
666 exec_result = execute_select_command (command->value.Select);
672 command->value.Case->flags |= CMD_IGNORE_RETURN;
673 exec_result = execute_case_command (command->value.Case);
678 command->value.While->flags |= CMD_IGNORE_RETURN;
679 exec_result = execute_while_command (command->value.While);
684 command->value.While->flags |= CMD_IGNORE_RETURN;
685 exec_result = execute_until_command (command->value.While);
690 command->value.If->flags |= CMD_IGNORE_RETURN;
691 exec_result = execute_if_command (command->value.If);
696 /* This code can be executed from either of two paths: an explicit
697 '{}' command, or via a function call. If we are executed via a
698 function call, we have already taken care of the function being
699 executed in the background (down there in execute_simple_command ()),
700 and this command should *not* be marked as asynchronous. If we
701 are executing a regular '{}' group command, and asynchronous == 1,
702 we must want to execute the whole command in the background, so we
703 need a subshell, and we want the stuff executed in that subshell
704 (this group command) to be executed in the foreground of that
705 subshell (i.e. there will not be *another* subshell forked).
707 What we do is to force a subshell if asynchronous, and then call
708 execute_command_internal again with asynchronous still set to 1,
709 but with the original group command, so the printed command will
712 The code above that handles forking off subshells will note that
713 both subshell and async are on, and turn off async in the child
714 after forking the subshell (but leave async set in the parent, so
715 the normal call to describe_pid is made). This turning off
716 async is *crucial*; if it is not done, this will fall into an
717 infinite loop of executions through this spot in subshell after
718 subshell until the process limit is exhausted. */
722 command->flags |= CMD_FORCE_SUBSHELL;
724 execute_command_internal (command, 1, pipe_in, pipe_out,
729 if (ignore_return && command->value.Group->command)
730 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
732 execute_command_internal (command->value.Group->command,
733 asynchronous, pipe_in, pipe_out,
739 exec_result = execute_connection (command, asynchronous,
740 pipe_in, pipe_out, fds_to_close);
743 #if defined (DPAREN_ARITHMETIC)
746 command->value.Arith->flags |= CMD_IGNORE_RETURN;
747 exec_result = execute_arith_command (command->value.Arith);
751 #if defined (COND_COMMAND)
754 command->value.Cond->flags |= CMD_IGNORE_RETURN;
755 exec_result = execute_cond_command (command->value.Cond);
759 case cm_function_def:
760 exec_result = execute_intern_function (command->value.Function_def->name,
761 command->value.Function_def->command);
765 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
770 do_redirections (my_undo_list, 1, 0, 0);
771 dispose_redirects (my_undo_list);
775 dispose_redirects (exec_undo_list);
777 if (my_undo_list || exec_undo_list)
778 discard_unwind_frame ("loop_redirections");
780 /* Invert the return value if we have to */
782 exec_result = (exec_result == EXECUTION_SUCCESS)
786 last_command_exit_value = exec_result;
787 run_pending_traps ();
788 if (running_trap == 0)
789 currently_executing_command = (COMMAND *)NULL;
790 return (last_command_exit_value);
793 #if defined (COMMAND_TIMING)
795 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
796 extern struct timeval *difftimeval();
797 extern struct timeval *addtimeval();
798 extern int timeval_to_cpu();
801 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
802 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
804 static int precs[] = { 0, 100, 10, 1 };
806 /* Expand one `%'-prefixed escape sequence from a time format string. */
808 mkfmt (buf, prec, lng, sec, sec_fraction)
821 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
828 abuf[aind--] = (min % 10) + '0';
832 buf[ind++] = abuf[aind++];
836 /* Now add the seconds. */
839 abuf[aind--] = (sec % 10) + '0';
843 buf[ind++] = abuf[aind++];
845 /* We want to add a decimal point and PREC places after it if PREC is
846 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
851 for (aind = 1; aind <= prec; aind++)
853 buf[ind++] = (sec_fraction / precs[aind]) + '0';
854 sec_fraction %= precs[aind];
865 /* Interpret the format string FORMAT, interpolating the following escape
869 where the optional `prec' is a precision, meaning the number of
870 characters after the decimal point, the optional `l' means to format
871 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
872 and the last character is one of
874 R number of seconds of `real' time
875 U number of seconds of `user' time
876 S number of seconds of `system' time
878 An occurrence of `%%' in the format string is translated to a `%'. The
879 result is printed to FP, a pointer to a FILE. The other variables are
880 the seconds and thousandths of a second of real, user, and system time,
883 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
887 int rsf, usf, ssf, cpu;
890 char *str, *s, ts[32];
895 len = strlen (format);
896 ssize = (len + 64) - (len % 64);
897 str = xmalloc (ssize);
900 for (s = format; *s; s++)
902 if (*s != '%' || s[1] == '\0')
904 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
907 else if (s[1] == '%')
910 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
913 else if (s[1] == 'P')
919 sum_frac = (cpu % 100) * 10;
920 len = mkfmt (ts, 2, 0, sum, sum_frac);
921 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
922 strcpy (str + sindex, ts);
927 prec = 3; /* default is three places past the decimal point. */
928 lng = 0; /* default is to not use minutes or append `s' */
930 if (isdigit (*s)) /* `precision' */
933 if (prec > 3) prec = 3;
935 if (*s == 'l') /* `length extender' */
940 if (*s == 'R' || *s == 'E')
941 len = mkfmt (ts, prec, lng, rs, rsf);
943 len = mkfmt (ts, prec, lng, us, usf);
945 len = mkfmt (ts, prec, lng, ss, ssf);
948 internal_error ("bad format character in time format: %c", *s);
952 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
953 strcpy (str + sindex, ts);
959 fprintf (fp, "%s\n", str);
966 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
968 int asynchronous, pipe_in, pipe_out;
969 struct fd_bitmap *fds_to_close;
971 int rv, posix_time, old_flags;
977 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
978 struct timeval real, user, sys;
979 struct timeval before, after;
981 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
983 # if defined (HAVE_TIMES)
984 clock_t tbefore, tafter, real, user, sys;
985 struct tms before, after;
989 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
990 gettimeofday (&before, &dtz);
991 getrusage (RUSAGE_SELF, &selfb);
992 getrusage (RUSAGE_CHILDREN, &kidsb);
994 # if defined (HAVE_TIMES)
995 tbefore = times (&before);
999 posix_time = (command->flags & CMD_TIME_POSIX);
1001 old_flags = command->flags;
1002 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1003 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1004 command->flags = old_flags;
1007 rsf = usf = ssf = cpu = 0;
1009 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1010 gettimeofday (&after, &dtz);
1011 getrusage (RUSAGE_SELF, &selfa);
1012 getrusage (RUSAGE_CHILDREN, &kidsa);
1014 difftimeval (&real, &before, &after);
1015 timeval_to_secs (&real, &rs, &rsf);
1017 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1018 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1019 timeval_to_secs (&user, &us, &usf);
1021 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1022 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1023 timeval_to_secs (&sys, &ss, &ssf);
1025 cpu = timeval_to_cpu (&real, &user, &sys);
1027 # if defined (HAVE_TIMES)
1028 tafter = times (&after);
1030 real = tafter - tbefore;
1031 clock_t_to_secs (real, &rs, &rsf);
1033 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1034 clock_t_to_secs (user, &us, &usf);
1036 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1037 clock_t_to_secs (sys, &ss, &ssf);
1039 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1043 rsf = usf = ssf = cpu = 0;
1048 time_format = POSIX_TIMEFORMAT;
1049 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1050 time_format = BASH_TIMEFORMAT;
1052 if (time_format && *time_format)
1053 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1057 #endif /* COMMAND_TIMING */
1059 /* Execute a command that's supposed to be in a subshell. This must be
1060 called after make_child and we must be running in the child process.
1061 The caller will return or exit() immediately with the value this returns. */
1063 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1066 int pipe_in, pipe_out;
1067 struct fd_bitmap *fds_to_close;
1069 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1073 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1074 pipe_in == NO_PIPE &&
1075 stdin_redirects (command->redirects) == 0);
1077 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1078 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1080 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1082 /* If a command is asynchronous in a subshell (like ( foo ) & or
1083 the special case of an asynchronous GROUP command where the
1084 the subshell bit is turned on down in case cm_group: below),
1085 turn off `asynchronous', so that two subshells aren't spawned.
1087 This seems semantically correct to me. For example,
1088 ( foo ) & seems to say ``do the command `foo' in a subshell
1089 environment, but don't wait for that subshell to finish'',
1090 and "{ foo ; bar ; } &" seems to me to be like functions or
1091 builtins in the background, which executed in a subshell
1092 environment. I just don't see the need to fork two subshells. */
1094 /* Don't fork again, we are already in a subshell. A `doubly
1095 async' shell is not interactive, however. */
1098 #if defined (JOB_CONTROL)
1099 /* If a construct like ( exec xxx yyy ) & is given while job
1100 control is active, we want to prevent exec from putting the
1101 subshell back into the original process group, carefully
1102 undoing all the work we just did in make_child. */
1104 #endif /* JOB_CONTROL */
1105 ois = interactive_shell;
1106 interactive_shell = 0;
1107 /* This test is to prevent alias expansion by interactive shells that
1108 run `(command) &' but to allow scripts that have enabled alias
1109 expansion with `shopt -s expand_alias' to continue to expand
1111 if (ois != interactive_shell)
1116 /* Subshells are neither login nor interactive. */
1117 login_shell = interactive = 0;
1119 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1121 reset_terminating_signals (); /* in sig.c */
1122 /* Cancel traps, in trap.c. */
1123 restore_original_signals ();
1125 setup_async_signals ();
1127 #if defined (JOB_CONTROL)
1128 set_sigchld_handler ();
1129 #endif /* JOB_CONTROL */
1131 set_sigint_handler ();
1133 #if defined (JOB_CONTROL)
1134 /* Delete all traces that there were any jobs running. This is
1135 only for subshells. */
1136 without_job_control ();
1137 #endif /* JOB_CONTROL */
1140 close_fd_bitmap (fds_to_close);
1142 do_piping (pipe_in, pipe_out);
1144 /* If this is a user subshell, set a flag if stdin was redirected.
1145 This is used later to decide whether to redirect fd 0 to
1146 /dev/null for async commands in the subshell. This adds more
1147 sh compatibility, but I'm not sure it's the right thing to do. */
1150 stdin_redir = stdin_redirects (command->redirects);
1151 restore_default_signal (0);
1154 /* If this is an asynchronous command (command &), we want to
1155 redirect the standard input from /dev/null in the absence of
1156 any specific redirection involving stdin. */
1157 if (should_redir_stdin && stdin_redir == 0)
1158 async_redirect_stdin ();
1160 /* Do redirections, then dispose of them before recursive call. */
1161 if (command->redirects)
1163 if (do_redirections (command->redirects, 1, 0, 0) != 0)
1164 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1166 dispose_redirects (command->redirects);
1167 command->redirects = (REDIRECT *)NULL;
1170 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1172 /* If this is a simple command, tell execute_disk_command that it
1173 might be able to get away without forking and simply exec.
1174 This means things like ( sleep 10 ) will only cause one fork.
1175 If we're timing the command or inverting its return value, however,
1176 we cannot do this optimization. */
1177 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1178 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1179 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1181 tcom->flags |= CMD_NO_FORK;
1182 if (tcom->type == cm_simple)
1183 tcom->value.Simple->flags |= CMD_NO_FORK;
1186 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1187 tcom->flags &= ~CMD_INVERT_RETURN;
1189 /* If we're inside a function while executing this subshell, we
1190 need to handle a possible `return'. */
1192 if (return_catch_flag)
1193 function_value = setjmp (return_catch);
1196 return_code = return_catch_value;
1198 return_code = execute_command_internal
1199 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1201 /* If we are asked to, invert the return value. */
1203 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1204 : EXECUTION_SUCCESS;
1206 /* If we were explicitly placed in a subshell with (), we need
1207 to do the `shell cleanup' things, such as running traps[0]. */
1208 if (user_subshell && signal_is_trapped (0))
1210 last_command_exit_value = return_code;
1211 return_code = run_exit_trap ();
1214 return (return_code);
1219 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1221 int asynchronous, pipe_in, pipe_out;
1222 struct fd_bitmap *fds_to_close;
1224 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1226 struct fd_bitmap *fd_bitmap;
1228 #if defined (JOB_CONTROL)
1230 BLOCK_CHILD (set, oset);
1231 #endif /* JOB_CONTROL */
1233 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1238 while (cmd && cmd->type == cm_connection &&
1239 cmd->value.Connection && cmd->value.Connection->connector == '|')
1241 /* Make a pipeline between the two commands. */
1242 if (pipe (fildes) < 0)
1244 sys_error ("pipe error");
1245 #if defined (JOB_CONTROL)
1246 terminate_current_pipeline ();
1247 kill_current_pipeline ();
1248 #endif /* JOB_CONTROL */
1249 last_command_exit_value = EXECUTION_FAILURE;
1250 /* The unwind-protects installed below will take care
1251 of closing all of the open file descriptors. */
1252 throw_to_top_level ();
1253 return (EXECUTION_FAILURE); /* XXX */
1256 /* Here is a problem: with the new file close-on-exec
1257 code, the read end of the pipe (fildes[0]) stays open
1258 in the first process, so that process will never get a
1259 SIGPIPE. There is no way to signal the first process
1260 that it should close fildes[0] after forking, so it
1261 remains open. No SIGPIPE is ever sent because there
1262 is still a file descriptor open for reading connected
1263 to the pipe. We take care of that here. This passes
1264 around a bitmap of file descriptors that must be
1265 closed after making a child process in execute_simple_command. */
1267 /* We need fd_bitmap to be at least as big as fildes[0].
1268 If fildes[0] is less than fds_to_close->size, then
1269 use fds_to_close->size. */
1270 new_bitmap_size = (fildes[0] < fds_to_close->size)
1271 ? fds_to_close->size
1274 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1276 /* Now copy the old information into the new bitmap. */
1277 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1279 /* And mark the pipe file descriptors to be closed. */
1280 fd_bitmap->bitmap[fildes[0]] = 1;
1282 /* In case there are pipe or out-of-processes errors, we
1283 want all these file descriptors to be closed when
1284 unwind-protects are run, and the storage used for the
1285 bitmaps freed up. */
1286 begin_unwind_frame ("pipe-file-descriptors");
1287 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1288 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1290 add_unwind_protect (close, prev);
1291 dummyfd = fildes[1];
1292 add_unwind_protect (close, dummyfd);
1294 #if defined (JOB_CONTROL)
1295 add_unwind_protect (restore_signal_mask, oset);
1296 #endif /* JOB_CONTROL */
1298 if (ignore_return && cmd->value.Connection->first)
1299 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1300 execute_command_internal (cmd->value.Connection->first, asynchronous,
1301 prev, fildes[1], fd_bitmap);
1309 dispose_fd_bitmap (fd_bitmap);
1310 discard_unwind_frame ("pipe-file-descriptors");
1312 cmd = cmd->value.Connection->second;
1315 /* Now execute the rightmost command in the pipeline. */
1316 if (ignore_return && cmd)
1317 cmd->flags |= CMD_IGNORE_RETURN;
1318 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1323 #if defined (JOB_CONTROL)
1324 UNBLOCK_CHILD (oset);
1327 return (exec_result);
1331 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1333 int asynchronous, pipe_in, pipe_out;
1334 struct fd_bitmap *fds_to_close;
1340 COMMAND *tc, *second;
1341 int ignore_return, exec_result;
1343 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1345 switch (command->value.Connection->connector)
1347 /* Do the first command asynchronously. */
1349 tc = command->value.Connection->first;
1351 return (EXECUTION_SUCCESS);
1356 tc->flags |= CMD_IGNORE_RETURN;
1357 tc->flags |= CMD_AMPERSAND;
1359 /* If this shell was compiled without job control support, if
1360 the shell is not running interactively, if we are currently
1361 in a subshell via `( xxx )', or if job control is not active
1362 then the standard input for an asynchronous command is
1363 forced to /dev/null. */
1364 #if defined (JOB_CONTROL)
1365 if ((!interactive_shell || subshell_environment || !job_control) && !stdin_redir)
1368 #endif /* JOB_CONTROL */
1371 rd.filename = make_bare_word ("/dev/null");
1372 tr = make_redirection (0, r_inputa_direction, rd);
1373 tr->next = tc->redirects;
1376 tc->flags |= CMD_STDIN_REDIR;
1379 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1381 if (tc->flags & CMD_STDIN_REDIR)
1384 /* Remove the redirection we added above. It matters,
1385 especially for loops, which call execute_command ()
1386 multiple times with the same command. */
1391 tc->redirects = tc->redirects->next;
1393 while (tc->redirects && tc->redirects != rp);
1395 tl->next = (REDIRECT *)NULL;
1396 dispose_redirects (tr);
1398 tc->flags &= ~CMD_STDIN_REDIR;
1401 second = command->value.Connection->second;
1405 second->flags |= CMD_IGNORE_RETURN;
1407 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1412 /* Just call execute command on both sides. */
1416 if (command->value.Connection->first)
1417 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1418 if (command->value.Connection->second)
1419 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1422 execute_command (command->value.Connection->first);
1424 exec_result = execute_command_internal (command->value.Connection->second,
1425 asynchronous, pipe_in, pipe_out,
1430 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1437 /* If we have something like `a && b &' or `a || b &', run the
1438 && or || stuff in a subshell. Force a subshell and just call
1439 execute_command_internal again. Leave asynchronous on
1440 so that we get a report from the parent shell about the
1442 command->flags |= CMD_FORCE_SUBSHELL;
1443 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1447 /* Execute the first command. If the result of that is successful
1448 and the connector is AND_AND, or the result is not successful
1449 and the connector is OR_OR, then execute the second command,
1450 otherwise return. */
1452 if (command->value.Connection->first)
1453 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1455 exec_result = execute_command (command->value.Connection->first);
1457 if (((command->value.Connection->connector == AND_AND) &&
1458 (exec_result == EXECUTION_SUCCESS)) ||
1459 ((command->value.Connection->connector == OR_OR) &&
1460 (exec_result != EXECUTION_SUCCESS)))
1462 if (ignore_return && command->value.Connection->second)
1463 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1465 exec_result = execute_command (command->value.Connection->second);
1470 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1471 jump_to_top_level (DISCARD);
1472 exec_result = EXECUTION_FAILURE;
1481 if (!interactive_shell) \
1482 reap_dead_jobs (); \
1486 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1489 execute_for_command (for_command)
1490 FOR_COM *for_command;
1492 register WORD_LIST *releaser, *list;
1497 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1500 if (check_identifier (for_command->name, 1) == 0)
1502 if (posixly_correct && interactive_shell == 0)
1504 last_command_exit_value = EX_USAGE;
1505 jump_to_top_level (EXITPROG);
1507 return (EXECUTION_FAILURE);
1511 identifier = for_command->name->word;
1513 list = releaser = expand_words_no_vars (for_command->map_list);
1515 begin_unwind_frame ("for");
1516 add_unwind_protect (dispose_words, releaser);
1519 if (lexical_scoping)
1521 old_value = copy_variable (find_variable (identifier));
1523 add_unwind_protect (dispose_variable, old_value);
1527 if (for_command->flags & CMD_IGNORE_RETURN)
1528 for_command->action->flags |= CMD_IGNORE_RETURN;
1530 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1533 this_command_name = (char *)NULL;
1534 v = bind_variable (identifier, list->word->word);
1535 if (readonly_p (v) || noassign_p (v))
1537 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1539 last_command_exit_value = EXECUTION_FAILURE;
1540 jump_to_top_level (FORCE_EOF);
1544 run_unwind_frame ("for");
1546 return (EXECUTION_FAILURE);
1549 retval = execute_command (for_command->action);
1570 if (lexical_scoping)
1573 makunbound (identifier, shell_variables);
1576 SHELL_VAR *new_value;
1578 new_value = bind_variable (identifier, value_cell(old_value));
1579 new_value->attributes = old_value->attributes;
1580 dispose_variable (old_value);
1585 dispose_words (releaser);
1586 discard_unwind_frame ("for");
1590 #if defined (ARITH_FOR_COMMAND)
1591 /* Execute an arithmetic for command. The syntax is
1593 for (( init ; step ; test ))
1598 The execution should be exactly equivalent to
1601 while eval \(\( test \)\) ; do
1607 eval_arith_for_expr (l, okp)
1614 new = expand_words_no_vars (l);
1615 if (echo_command_at_execute)
1616 xtrace_print_arith_cmd (new);
1617 expresult = evalexp (new->word->word, okp);
1618 dispose_words (new);
1623 execute_arith_for_command (arith_for_command)
1624 ARITH_FOR_COM *arith_for_command;
1627 int expok, result, body_status;
1629 body_status = EXECUTION_SUCCESS;
1632 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1633 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1635 this_command_name = "(("; /* )) for expression error messages */
1637 if (variable_context)
1638 line_number = arith_for_command->line - function_line_number;
1640 /* Evaluate the initialization expression. */
1641 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1643 return (EXECUTION_FAILURE);
1647 /* Evaluate the test expression. */
1648 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1651 body_status = EXECUTION_FAILURE;
1658 /* Execute the body of the arithmetic for command. */
1660 body_status = execute_command (arith_for_command->action);
1663 /* Handle any `break' or `continue' commands executed by the body. */
1677 /* Evaluate the step expression. */
1678 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1681 body_status = EXECUTION_FAILURE;
1687 return (body_status);
1691 #if defined (SELECT_COMMAND)
1692 static int LINES, COLS, tabsize;
1694 #define RP_SPACE ") "
1695 #define RP_SPACE_LEN 2
1697 /* XXX - does not handle numbers > 1000000 at all. */
1698 #define NUMBER_LEN(s) \
1702 : ((s < 10000) ? 4 \
1703 : ((s < 100000) ? 5 \
1707 print_index_and_element (len, ind, list)
1711 register WORD_LIST *l;
1716 for (i = ind, l = list; l && --i; l = l->next)
1718 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1719 return (STRLEN (l->word->word));
1728 if ((to / tabsize) > (from / tabsize))
1730 putc ('\t', stderr);
1731 from += tabsize - from % tabsize;
1742 print_select_list (list, list_len, max_elem_len, indices_len)
1744 int list_len, max_elem_len, indices_len;
1746 int ind, row, elem_len, pos, cols, rows;
1747 int first_column_indices_len, other_indices_len;
1751 putc ('\n', stderr);
1755 cols = max_elem_len ? COLS / max_elem_len : 1;
1758 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1759 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1767 first_column_indices_len = NUMBER_LEN (rows);
1768 other_indices_len = indices_len;
1770 for (row = 0; row < rows; row++)
1776 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1777 elem_len = print_index_and_element (indices_len, ind + 1, list);
1778 elem_len += indices_len + RP_SPACE_LEN;
1780 if (ind >= list_len)
1782 indent (pos + elem_len, pos + max_elem_len);
1783 pos += max_elem_len;
1785 putc ('\n', stderr);
1789 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1790 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1791 If the number is between 1 and LIST_LEN, return that selection. If EOF
1792 is read, return a null string. If a blank line is entered, or an invalid
1793 number is entered, the loop is executed again. */
1795 select_query (list, list_len, prompt)
1800 int max_elem_len, indices_len, len;
1803 char *repl_string, *t;
1805 t = get_string_value ("LINES");
1806 LINES = (t && *t) ? atoi (t) : 24;
1807 t = get_string_value ("COLUMNS");
1808 COLS = (t && *t) ? atoi (t) : 80;
1811 t = get_string_value ("TABSIZE");
1812 tabsize = (t && *t) ? atoi (t) : 8;
1820 for (l = list; l; l = l->next)
1822 len = STRLEN (l->word->word);
1823 if (len > max_elem_len)
1826 indices_len = NUMBER_LEN (list_len);
1827 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1831 print_select_list (list, list_len, max_elem_len, indices_len);
1832 fprintf (stderr, "%s", prompt);
1836 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1839 return ((char *)NULL);
1841 repl_string = get_string_value ("REPLY");
1842 if (*repl_string == 0)
1844 if (legal_number (repl_string, &reply) == 0)
1846 if (reply < 1 || reply > list_len)
1849 for (l = list; l && --reply; l = l->next)
1851 return (l->word->word);
1855 /* Execute a SELECT command. The syntax is:
1856 SELECT word IN list DO command_list DONE
1857 Only `break' or `return' in command_list will terminate
1860 execute_select_command (select_command)
1861 SELECT_COM *select_command;
1863 WORD_LIST *releaser, *list;
1865 char *identifier, *ps3_prompt, *selection;
1866 int retval, list_len, return_val;
1868 if (check_identifier (select_command->name, 1) == 0)
1869 return (EXECUTION_FAILURE);
1872 identifier = select_command->name->word;
1874 /* command and arithmetic substitution, parameter and variable expansion,
1875 word splitting, pathname expansion, and quote removal. */
1876 list = releaser = expand_words_no_vars (select_command->map_list);
1877 list_len = list_length (list);
1878 if (list == 0 || list_len == 0)
1881 dispose_words (list);
1882 return (EXECUTION_SUCCESS);
1885 begin_unwind_frame ("select");
1886 add_unwind_protect (dispose_words, releaser);
1888 if (select_command->flags & CMD_IGNORE_RETURN)
1889 select_command->action->flags |= CMD_IGNORE_RETURN;
1891 retval = EXECUTION_SUCCESS;
1893 unwind_protect_int (return_catch_flag);
1894 unwind_protect_jmp_buf (return_catch);
1895 return_catch_flag++;
1899 ps3_prompt = get_string_value ("PS3");
1900 if (ps3_prompt == 0)
1904 selection = select_query (list, list_len, ps3_prompt);
1909 v = bind_variable (identifier, selection);
1910 if (readonly_p (v) || noassign_p (v))
1912 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1914 last_command_exit_value = EXECUTION_FAILURE;
1915 jump_to_top_level (FORCE_EOF);
1919 run_unwind_frame ("select");
1920 return (EXECUTION_FAILURE);
1924 return_val = setjmp (return_catch);
1928 retval = return_catch_value;
1932 retval = execute_command (select_command->action);
1953 run_unwind_frame ("select");
1956 #endif /* SELECT_COMMAND */
1958 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1959 The pattern_list is a linked list of pattern clauses; each clause contains
1960 some patterns to compare word_desc against, and an associated command to
1963 execute_case_command (case_command)
1964 CASE_COM *case_command;
1966 register WORD_LIST *list;
1967 WORD_LIST *wlist, *es;
1968 PATTERN_LIST *clauses;
1969 char *word, *pattern;
1970 int retval, match, ignore_return;
1972 /* Posix.2 specifies that the WORD is tilde expanded. */
1973 if (member ('~', case_command->word->word))
1975 word = bash_tilde_expand (case_command->word->word);
1976 free (case_command->word->word);
1977 case_command->word->word = word;
1980 wlist = expand_word_unsplit (case_command->word, 0);
1981 word = wlist ? string_list (wlist) : savestring ("");
1982 dispose_words (wlist);
1984 retval = EXECUTION_SUCCESS;
1985 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
1987 begin_unwind_frame ("case");
1988 add_unwind_protect ((Function *)xfree, word);
1990 #define EXIT_CASE() goto exit_case_command
1992 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
1995 for (list = clauses->patterns; list; list = list->next)
1997 /* Posix.2 specifies to tilde expand each member of the pattern
1999 if (member ('~', list->word->word))
2001 pattern = bash_tilde_expand (list->word->word);
2002 free (list->word->word);
2003 list->word->word = pattern;
2006 es = expand_word_leave_quoted (list->word, 0);
2008 if (es && es->word && es->word->word && *(es->word->word))
2009 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2012 pattern = xmalloc (1);
2016 /* Since the pattern does not undergo quote removal (as per
2017 Posix.2, section 3.9.4.3), the fnmatch () call must be able
2018 to recognize backslashes as escape characters. */
2019 match = fnmatch (pattern, word, FNMATCH_EXTFLAG) != FNM_NOMATCH;
2026 if (clauses->action && ignore_return)
2027 clauses->action->flags |= CMD_IGNORE_RETURN;
2028 retval = execute_command (clauses->action);
2038 discard_unwind_frame ("case");
2045 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2046 Repeatedly execute action while executing test produces
2047 EXECUTION_SUCCESS. */
2049 execute_while_command (while_command)
2050 WHILE_COM *while_command;
2052 return (execute_while_or_until (while_command, CMD_WHILE));
2055 /* UNTIL is just like WHILE except that the test result is negated. */
2057 execute_until_command (while_command)
2058 WHILE_COM *while_command;
2060 return (execute_while_or_until (while_command, CMD_UNTIL));
2063 /* The body for both while and until. The only difference between the
2064 two is that the test value is treated differently. TYPE is
2065 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2066 be EXECUTION_SUCCESS if no commands in the body are executed, and
2067 the status of the last command executed in the body otherwise. */
2069 execute_while_or_until (while_command, type)
2070 WHILE_COM *while_command;
2073 int return_value, body_status;
2075 body_status = EXECUTION_SUCCESS;
2078 while_command->test->flags |= CMD_IGNORE_RETURN;
2079 if (while_command->flags & CMD_IGNORE_RETURN)
2080 while_command->action->flags |= CMD_IGNORE_RETURN;
2084 return_value = execute_command (while_command->test);
2087 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2089 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2093 body_status = execute_command (while_command->action);
2111 return (body_status);
2114 /* IF test THEN command [ELSE command].
2115 IF also allows ELIF in the place of ELSE IF, but
2116 the parser makes *that* stupidity transparent. */
2118 execute_if_command (if_command)
2123 if_command->test->flags |= CMD_IGNORE_RETURN;
2124 return_value = execute_command (if_command->test);
2126 if (return_value == EXECUTION_SUCCESS)
2130 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2131 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2133 return (execute_command (if_command->true_case));
2139 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2140 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2142 return (execute_command (if_command->false_case));
2146 #if defined (DPAREN_ARITHMETIC)
2148 execute_arith_command (arith_command)
2149 ARITH_COM *arith_command;
2151 int result, expok, expresult;
2152 WORD_LIST *new, *p, *printit;
2157 this_command_name = "(("; /* )) */
2158 /* If we're in a function, update the line number information. */
2159 if (variable_context)
2160 line_number = arith_command->line - function_line_number;
2162 new = expand_words (arith_command->exp);
2164 /* If we're tracing, make a new word list with `((' at the front and `))'
2165 at the back and print it. */
2166 if (echo_command_at_execute)
2167 xtrace_print_arith_cmd (new);
2169 result = evalexp (new->word->word, &expok);
2170 dispose_words (new);
2173 return (EXECUTION_FAILURE);
2175 return (result == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2177 #endif /* DPAREN_ARITHMETIC */
2179 #if defined (COND_COMMAND)
2181 static char *nullstr = "";
2184 execute_cond_node (cond)
2187 int result, invert, patmatch, flags;
2188 char *arg1, *arg2, *print2;
2190 invert = (cond->flags & CMD_INVERT_RETURN);
2192 if (cond->type == COND_EXPR)
2193 result = execute_cond_node (cond->left);
2194 else if (cond->type == COND_OR)
2196 result = execute_cond_node (cond->left);
2197 if (result != EXECUTION_SUCCESS)
2198 result = execute_cond_node (cond->right);
2200 else if (cond->type == COND_AND)
2202 result = execute_cond_node (cond->left);
2203 if (result == EXECUTION_SUCCESS)
2204 result = execute_cond_node (cond->right);
2206 else if (cond->type == COND_UNARY)
2208 arg1 = cond_expand_word (cond->left->op, 0);
2211 if (echo_command_at_execute)
2212 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2213 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2214 if (arg1 != nullstr)
2217 else if (cond->type == COND_BINARY)
2219 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2220 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2221 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2223 arg1 = cond_expand_word (cond->left->op, 0);
2226 arg2 = cond_expand_word (cond->right->op, patmatch);
2230 if (echo_command_at_execute)
2231 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2233 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2235 : EXECUTION_FAILURE;
2236 if (arg1 != nullstr)
2238 if (arg2 != nullstr)
2243 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2244 jump_to_top_level (DISCARD);
2245 result = EXECUTION_FAILURE;
2249 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2255 execute_cond_command (cond_command)
2256 COND_COM *cond_command;
2260 result = EXECUTION_SUCCESS;
2262 this_command_name = "[[";
2263 /* If we're in a function, update the line number information. */
2264 if (variable_context)
2265 line_number = cond_command->line - function_line_number;
2268 debug_print_cond_command (cond_command);
2270 last_command_exit_value = result = execute_cond_node (cond_command);
2273 #endif /* COND_COMMAND */
2283 var = bind_variable ("_", arg);
2284 VUNSETATTR (var, att_exported);
2287 /* Execute a null command. Fork a subshell if the command uses pipes or is
2288 to be run asynchronously. This handles all the side effects that are
2289 supposed to take place. */
2291 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2292 REDIRECT *redirects;
2293 int pipe_in, pipe_out, async;
2294 pid_t old_last_command_subst_pid;
2296 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2298 /* We have a null command, but we really want a subshell to take
2299 care of it. Just fork, do piping and redirections, and exit. */
2300 if (make_child ((char *)NULL, async) == 0)
2302 /* Cancel traps, in trap.c. */
2303 restore_original_signals (); /* XXX */
2305 do_piping (pipe_in, pipe_out);
2307 subshell_environment = SUBSHELL_ASYNC;
2309 if (do_redirections (redirects, 1, 0, 0) == 0)
2310 exit (EXECUTION_SUCCESS);
2312 exit (EXECUTION_FAILURE);
2316 close_pipes (pipe_in, pipe_out);
2317 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2318 unlink_fifo_list ();
2320 return (EXECUTION_SUCCESS);
2325 /* Even if there aren't any command names, pretend to do the
2326 redirections that are specified. The user expects the side
2327 effects to take place. If the redirections fail, then return
2328 failure. Otherwise, if a command substitution took place while
2329 expanding the command or a redirection, return the value of that
2330 substitution. Otherwise, return EXECUTION_SUCCESS. */
2332 if (do_redirections (redirects, 0, 0, 0) != 0)
2333 return (EXECUTION_FAILURE);
2334 else if (old_last_command_subst_pid != last_command_subst_pid)
2335 return (last_command_exit_value);
2337 return (EXECUTION_SUCCESS);
2341 /* This is a hack to suppress word splitting for assignment statements
2342 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2344 fix_assignment_words (words)
2353 b = builtin_address_internal (words->word->word, 0);
2354 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2357 for (w = words; w; w = w->next)
2358 if (w->word->flags & W_ASSIGNMENT)
2359 w->word->flags |= (W_NOSPLIT|W_NOGLOB);
2362 /* The meaty part of all the executions. We have to start hacking the
2363 real execution of commands here. Fork a process, set things up,
2364 execute the command. */
2366 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2367 SIMPLE_COM *simple_command;
2368 int pipe_in, pipe_out, async;
2369 struct fd_bitmap *fds_to_close;
2371 WORD_LIST *words, *lastword;
2372 char *command_line, *lastarg, *temp;
2373 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2374 pid_t old_last_command_subst_pid, old_last_async_pid;
2378 result = EXECUTION_SUCCESS;
2379 special_builtin_failed = builtin_is_special = 0;
2380 command_line = (char *)0;
2382 /* If we're in a function, update the line number information. */
2383 if (variable_context)
2384 line_number = simple_command->line - function_line_number;
2386 /* Remember what this command line looks like at invocation. */
2387 command_string_index = 0;
2388 print_simple_command (simple_command);
2391 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2393 old_last_command_subst_pid = last_command_subst_pid;
2394 old_last_async_pid = last_asynchronous_pid;
2396 already_forked = dofork = 0;
2398 /* If we're in a pipeline or run in the background, set DOFORK so we
2399 make the child early, before word expansion. This keeps assignment
2400 statements from affecting the parent shell's environment when they
2402 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2404 /* Something like `%2 &' should restart job 2 in the background, not cause
2405 the shell to fork here. */
2406 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2407 simple_command->words && simple_command->words->word &&
2408 simple_command->words->word->word &&
2409 (simple_command->words->word->word[0] == '%'))
2414 /* XXX memory leak if expand_words() error causes a jump_to_top_level */
2415 command_line = savestring (the_printed_command);
2417 /* Do this now, because execute_disk_command will do it anyway in the
2418 vast majority of cases. */
2419 maybe_make_export_env ();
2421 if (make_child (command_line, async) == 0)
2424 simple_command->flags |= CMD_NO_FORK;
2426 subshell_environment = (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2427 ? (SUBSHELL_PIPE|SUBSHELL_FORK)
2428 : (SUBSHELL_ASYNC|SUBSHELL_FORK);
2430 /* We need to do this before piping to handle some really
2431 pathological cases where one of the pipe file descriptors
2434 close_fd_bitmap (fds_to_close);
2436 do_piping (pipe_in, pipe_out);
2437 pipe_in = pipe_out = -1;
2439 last_asynchronous_pid = old_last_async_pid;
2443 close_pipes (pipe_in, pipe_out);
2444 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2445 unlink_fifo_list ();
2447 command_line = (char *)NULL; /* don't free this. */
2448 bind_lastarg ((char *)NULL);
2453 /* If we are re-running this as the result of executing the `command'
2454 builtin, do not expand the command words a second time. */
2455 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2457 current_fds_to_close = fds_to_close;
2458 fix_assignment_words (simple_command->words);
2459 words = expand_words (simple_command->words);
2460 current_fds_to_close = (struct fd_bitmap *)NULL;
2463 words = copy_word_list (simple_command->words);
2465 /* It is possible for WORDS not to have anything left in it.
2466 Perhaps all the words consisted of `$foo', and there was
2467 no variable `$foo'. */
2470 result = execute_null_command (simple_command->redirects,
2472 already_forked ? 0 : async,
2473 old_last_command_subst_pid);
2478 bind_lastarg ((char *)NULL);
2479 set_pipestatus_from_exit (result);
2484 lastarg = (char *)NULL;
2486 begin_unwind_frame ("simple-command");
2488 if (echo_command_at_execute)
2489 xtrace_print_word_list (words);
2491 builtin = (Function *)NULL;
2492 func = (SHELL_VAR *)NULL;
2493 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2495 /* Posix.2 says special builtins are found before functions. We
2496 don't set builtin_is_special anywhere other than here, because
2497 this path is followed only when the `command' builtin is *not*
2498 being used, and we don't want to exit the shell if a special
2499 builtin executed with `command builtin' fails. `command' is not
2500 a special builtin. */
2501 if (posixly_correct)
2503 builtin = find_special_builtin (words->word->word);
2505 builtin_is_special = 1;
2508 func = find_function (words->word->word);
2511 add_unwind_protect (dispose_words, words);
2514 /* Bind the last word in this command to "$_" after execution. */
2515 for (lastword = words; lastword->next; lastword = lastword->next)
2517 lastarg = lastword->word->word;
2519 #if defined (JOB_CONTROL)
2520 /* Is this command a job control related thing? */
2521 if (words->word->word[0] == '%' && already_forked == 0)
2523 this_command_name = async ? "bg" : "fg";
2524 last_shell_builtin = this_shell_builtin;
2525 this_shell_builtin = builtin_address (this_command_name);
2526 result = (*this_shell_builtin) (words);
2530 /* One other possiblilty. The user may want to resume an existing job.
2531 If they do, find out whether this word is a candidate for a running
2533 if (job_control && already_forked == 0 && async == 0 &&
2534 !first_word_quoted &&
2536 words->word->word[0] &&
2537 !simple_command->redirects &&
2538 pipe_in == NO_PIPE &&
2539 pipe_out == NO_PIPE &&
2540 (temp = get_string_value ("auto_resume")))
2544 int wl, cl, exact, substring, match, started_status;
2545 register PROCESS *p;
2547 word = words->word->word;
2548 exact = STREQ (temp, "exact");
2549 substring = STREQ (temp, "substring");
2551 for (i = job_slots - 1; i > -1; i--)
2553 if (jobs[i] == 0 || (JOBSTATE (i) != JSTOPPED))
2561 cl = strlen (p->command);
2562 match = STREQN (p->command, word, cl);
2565 match = strindex (p->command, word) != (char *)0;
2567 match = STREQN (p->command, word, wl);
2575 run_unwind_frame ("simple-command");
2576 this_command_name = "fg";
2577 last_shell_builtin = this_shell_builtin;
2578 this_shell_builtin = builtin_address ("fg");
2580 started_status = start_job (i, 1);
2581 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2583 while (p != jobs[i]->pipe);
2586 #endif /* JOB_CONTROL */
2588 /* Remember the name of this command globally. */
2589 this_command_name = words->word->word;
2593 /* This command could be a shell builtin or a user-defined function.
2594 We have already found special builtins by this time, so we do not
2595 set builtin_is_special. If this is a function or builtin, and we
2596 have pipes, then fork a subshell in here. Otherwise, just execute
2597 the command directly. */
2598 if (func == 0 && builtin == 0)
2599 builtin = find_shell_builtin (this_command_name);
2601 last_shell_builtin = this_shell_builtin;
2602 this_shell_builtin = builtin;
2604 if (builtin || func)
2608 /* reset_terminating_signals (); */ /* XXX */
2609 /* Cancel traps, in trap.c. */
2610 restore_original_signals ();
2614 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2615 pipe_in == NO_PIPE &&
2616 (stdin_redirects (simple_command->redirects) == 0))
2617 async_redirect_stdin ();
2618 setup_async_signals ();
2621 execute_subshell_builtin_or_function
2622 (words, simple_command->redirects, builtin, func,
2623 pipe_in, pipe_out, async, fds_to_close,
2624 simple_command->flags);
2628 result = execute_builtin_or_function
2629 (words, builtin, func, simple_command->redirects, fds_to_close,
2630 simple_command->flags);
2633 if (result > EX_SHERRBASE)
2635 result = builtin_status (result);
2636 if (builtin_is_special)
2637 special_builtin_failed = 1;
2639 /* In POSIX mode, if there are assignment statements preceding
2640 a special builtin, they persist after the builtin
2642 if (posixly_correct && builtin_is_special && temporary_env)
2643 merge_temporary_env ();
2647 if (result == EX_USAGE)
2648 result = EX_BADUSAGE;
2649 else if (result > EX_SHERRBASE)
2650 result = EXECUTION_FAILURE;
2653 set_pipestatus_from_exit (result);
2659 if (command_line == 0)
2660 command_line = savestring (the_printed_command);
2662 execute_disk_command (words, simple_command->redirects, command_line,
2663 pipe_in, pipe_out, async, fds_to_close,
2664 simple_command->flags);
2667 bind_lastarg (lastarg);
2668 FREE (command_line);
2669 run_unwind_frame ("simple-command");
2673 /* Translate the special builtin exit statuses. We don't really need a
2674 function for this; it's a placeholder for future work. */
2676 builtin_status (result)
2690 r = EXECUTION_FAILURE;
2693 r = EXECUTION_SUCCESS;
2700 execute_builtin (builtin, words, flags, subshell)
2703 int flags, subshell;
2705 int old_e_flag, result, eval_unwind;
2707 old_e_flag = exit_immediately_on_error;
2708 /* The eval builtin calls parse_and_execute, which does not know about
2709 the setting of flags, and always calls the execution functions with
2710 flags that will exit the shell on an error if -e is set. If the
2711 eval builtin is being called, and we're supposed to ignore the exit
2712 value of the command, we turn the -e flag off ourselves, then
2713 restore it when the command completes. */
2714 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2716 begin_unwind_frame ("eval_builtin");
2717 unwind_protect_int (exit_immediately_on_error);
2718 exit_immediately_on_error = 0;
2724 /* The temporary environment for a builtin is supposed to apply to
2725 all commands executed by that builtin. Currently, this is a
2726 problem only with the `source' and `eval' builtins. */
2727 if (builtin == source_builtin || builtin == eval_builtin)
2730 begin_unwind_frame ("builtin_env");
2734 builtin_env = copy_array (temporary_env);
2736 add_unwind_protect (dispose_builtin_env, (char *)NULL);
2737 dispose_used_env_vars ();
2739 /* Otherwise we inherit builtin_env from our caller. */
2742 /* `return' does a longjmp() back to a saved environment in execute_function.
2743 If a variable assignment list preceded the command, and the shell is
2744 running in POSIX mode, we need to merge that into the shell_variables
2745 table, since `return' is a POSIX special builtin. */
2746 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2748 begin_unwind_frame ("return_temp_env");
2749 add_unwind_protect (merge_temporary_env, (char *)NULL);
2752 result = ((*builtin) (words->next));
2754 /* This shouldn't happen, but in case `return' comes back instead of
2755 longjmp'ing, we need to unwind. */
2756 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2757 discard_unwind_frame ("return_temp_env");
2759 if (subshell == 0 && (builtin == source_builtin || builtin == eval_builtin))
2761 /* In POSIX mode, if any variable assignments precede the `.' or
2762 `eval' builtin, they persist after the builtin completes, since `.'
2763 and `eval' are special builtins. */
2764 if (posixly_correct && builtin_env)
2765 merge_builtin_env ();
2767 run_unwind_frame ("builtin_env");
2772 exit_immediately_on_error += old_e_flag;
2773 discard_unwind_frame ("eval_builtin");
2780 execute_function (var, words, flags, fds_to_close, async, subshell)
2783 int flags, subshell, async;
2784 struct fd_bitmap *fds_to_close;
2786 int return_val, result;
2789 SHELL_VAR *old_shell_function;
2791 tc = (COMMAND *)copy_command (function_cell (var));
2792 if (tc && (flags & CMD_IGNORE_RETURN))
2793 tc->flags |= CMD_IGNORE_RETURN;
2797 begin_unwind_frame ("function_calling");
2799 add_unwind_protect (pop_context, (char *)NULL);
2800 unwind_protect_int (line_number);
2801 unwind_protect_int (return_catch_flag);
2802 unwind_protect_jmp_buf (return_catch);
2803 add_unwind_protect (dispose_command, (char *)tc);
2804 unwind_protect_pointer (this_shell_function);
2805 unwind_protect_int (loop_level);
2808 this_shell_function = var;
2809 make_funcname_visible (1);
2811 debug_trap = (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2812 ? trap_list[DEBUG_TRAP]
2818 debug_trap = savestring (debug_trap);
2819 /* XXX order is important here! unwind-protect commands are run
2820 in reverse order of registering. If this causes problems,
2821 take out the xfree unwind-protect and live with the small
2823 add_unwind_protect (xfree, debug_trap);
2824 add_unwind_protect (set_debug_trap, debug_trap);
2826 restore_default_signal (DEBUG_TRAP);
2829 /* The temporary environment for a function is supposed to apply to
2830 all commands executed within the function body. */
2833 function_env = copy_array (temporary_env);
2834 /* In POSIX mode, variable assignments preceding function names are
2835 supposed to persist in the environment after the function returns,
2836 as if a special builtin command had been executed. */
2839 if (posixly_correct)
2840 add_unwind_protect (merge_function_env, (char *)NULL);
2842 add_unwind_protect (dispose_function_env, (char *)NULL);
2844 dispose_used_env_vars ();
2846 /* Otherwise, we inherit function_env from our caller. */
2848 remember_args (words->next, 1);
2850 /* Number of the line on which the function body starts. */
2851 line_number = function_line_number = tc->line;
2855 #if defined (JOB_CONTROL)
2856 stop_pipeline (async, (COMMAND *)NULL);
2858 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
2860 if (fc && (flags & CMD_IGNORE_RETURN))
2861 fc->flags |= CMD_IGNORE_RETURN;
2868 return_catch_flag++;
2869 return_val = setjmp (return_catch);
2872 result = return_catch_value;
2874 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2877 run_unwind_frame ("function_calling");
2879 if (variable_context == 0 || this_shell_function == 0)
2880 make_funcname_visible (0);
2885 /* A convenience routine for use by other parts of the shell to execute
2886 a particular shell function. */
2888 execute_shell_function (var, words)
2893 struct fd_bitmap *bitmap;
2895 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
2896 begin_unwind_frame ("execute-shell-function");
2897 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
2899 ret = execute_function (var, words, 0, bitmap, 0, 0);
2901 dispose_fd_bitmap (bitmap);
2902 discard_unwind_frame ("execute-shell-function");
2907 /* Execute a shell builtin or function in a subshell environment. This
2908 routine does not return; it only calls exit(). If BUILTIN is non-null,
2909 it points to a function to call to execute a shell builtin; otherwise
2910 VAR points at the body of a function to execute. WORDS is the arguments
2911 to the command, REDIRECTS specifies redirections to perform before the
2912 command is executed. */
2914 execute_subshell_builtin_or_function (words, redirects, builtin, var,
2915 pipe_in, pipe_out, async, fds_to_close,
2918 REDIRECT *redirects;
2921 int pipe_in, pipe_out, async;
2922 struct fd_bitmap *fds_to_close;
2926 #if defined (JOB_CONTROL)
2929 jobs_hack = (builtin == jobs_builtin) &&
2930 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
2933 /* A subshell is neither a login shell nor interactive. */
2934 login_shell = interactive = 0;
2936 subshell_environment = SUBSHELL_ASYNC;
2938 maybe_make_export_env (); /* XXX - is this needed? */
2940 #if defined (JOB_CONTROL)
2941 /* Eradicate all traces of job control after we fork the subshell, so
2942 all jobs begun by this subshell are in the same process group as
2943 the shell itself. */
2945 /* Allow the output of `jobs' to be piped. */
2947 kill_current_pipeline ();
2949 without_job_control ();
2951 set_sigchld_handler ();
2952 #endif /* JOB_CONTROL */
2954 set_sigint_handler ();
2957 close_fd_bitmap (fds_to_close);
2959 do_piping (pipe_in, pipe_out);
2961 if (do_redirections (redirects, 1, 0, 0) != 0)
2962 exit (EXECUTION_FAILURE);
2966 /* Give builtins a place to jump back to on failure,
2967 so we don't go back up to main(). */
2968 result = setjmp (top_level);
2970 if (result == EXITPROG)
2971 exit (last_command_exit_value);
2973 exit (EXECUTION_FAILURE);
2976 r = execute_builtin (builtin, words, flags, 1);
2983 exit (execute_function (var, words, flags, fds_to_close, async, 1));
2986 /* Execute a builtin or function in the current shell context. If BUILTIN
2987 is non-null, it is the builtin command to execute, otherwise VAR points
2988 to the body of a function. WORDS are the command's arguments, REDIRECTS
2989 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2990 file descriptors to close.
2992 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2993 not undone before this function returns. */
2995 execute_builtin_or_function (words, builtin, var, redirects,
2996 fds_to_close, flags)
3000 REDIRECT *redirects;
3001 struct fd_bitmap *fds_to_close;
3005 REDIRECT *saved_undo_list;
3006 Function *saved_this_shell_builtin;
3008 if (do_redirections (redirects, 1, 1, 0) != 0)
3010 cleanup_redirects (redirection_undo_list);
3011 redirection_undo_list = (REDIRECT *)NULL;
3012 dispose_exec_redirects ();
3013 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3016 saved_this_shell_builtin = this_shell_builtin;
3017 saved_undo_list = redirection_undo_list;
3019 /* Calling the "exec" builtin changes redirections forever. */
3020 if (builtin == exec_builtin)
3022 dispose_redirects (saved_undo_list);
3023 saved_undo_list = exec_redirection_undo_list;
3024 exec_redirection_undo_list = (REDIRECT *)NULL;
3027 dispose_exec_redirects ();
3029 if (saved_undo_list)
3031 begin_unwind_frame ("saved redirects");
3032 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3035 redirection_undo_list = (REDIRECT *)NULL;
3038 result = execute_builtin (builtin, words, flags, 0);
3040 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3042 /* If we are executing the `command' builtin, but this_shell_builtin is
3043 set to `exec_builtin', we know that we have something like
3044 `command exec [redirection]', since otherwise `exec' would have
3045 overwritten the shell and we wouldn't get here. In this case, we
3046 want to behave as if the `command' builtin had not been specified
3047 and preserve the redirections. */
3048 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3050 if (saved_undo_list)
3051 dispose_redirects (saved_undo_list);
3052 redirection_undo_list = exec_redirection_undo_list;
3053 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3054 discard_unwind_frame ("saved_redirects");
3057 if (saved_undo_list)
3059 redirection_undo_list = saved_undo_list;
3060 discard_unwind_frame ("saved redirects");
3063 if (redirection_undo_list)
3065 cleanup_redirects (redirection_undo_list);
3066 redirection_undo_list = (REDIRECT *)NULL;
3073 setup_async_signals ()
3075 #if defined (__BEOS__)
3076 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3079 #if defined (JOB_CONTROL)
3080 if (job_control == 0)
3083 set_signal_handler (SIGINT, SIG_IGN);
3084 set_signal_ignored (SIGINT);
3085 set_signal_handler (SIGQUIT, SIG_IGN);
3086 set_signal_ignored (SIGQUIT);
3090 /* Execute a simple command that is hopefully defined in a disk file
3095 3) look up the command
3098 6) If the execve failed, see if the file has executable mode set.
3099 If so, and it isn't a directory, then execute its contents as
3102 Note that the filename hashing stuff has to take place up here,
3103 in the parent. This is probably why the Bourne style shells
3104 don't handle it, since that would require them to go through
3105 this gnarly hair, for no good reason. */
3107 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3108 async, fds_to_close, cmdflags)
3110 REDIRECT *redirects;
3112 int pipe_in, pipe_out, async;
3113 struct fd_bitmap *fds_to_close;
3116 char *pathname, *command, **args;
3120 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3121 pathname = words->word->word;
3123 #if defined (RESTRICTED_SHELL)
3124 if (restricted && strchr (pathname, '/'))
3126 internal_error ("%s: restricted: cannot specify `/' in command names",
3128 last_command_exit_value = EXECUTION_FAILURE;
3131 #endif /* RESTRICTED_SHELL */
3133 command = search_for_command (pathname);
3137 maybe_make_export_env ();
3138 put_command_name_into_env (command);
3141 /* We have to make the child before we check for the non-existence
3142 of COMMAND, since we want the error messages to be redirected. */
3143 /* If we can get away without forking and there are no pipes to deal with,
3144 don't bother to fork, just directly exec the command. */
3145 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3148 pid = make_child (savestring (command_line), async);
3152 int old_interactive;
3155 /* This has been disabled for the time being. */
3156 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3157 if (posixly_correct == 0)
3158 put_gnu_argv_flags_into_env ((int)getpid (), glob_argv_flags);
3162 /* Cancel traps, in trap.c. */
3163 restore_original_signals ();
3165 /* restore_original_signals may have undone the work done
3166 by make_child to ensure that SIGINT and SIGQUIT are ignored
3167 in asynchronous children. */
3170 if ((cmdflags & CMD_STDIN_REDIR) &&
3171 pipe_in == NO_PIPE &&
3172 (stdin_redirects (redirects) == 0))
3173 async_redirect_stdin ();
3174 setup_async_signals ();
3177 /* This functionality is now provided by close-on-exec of the
3178 file descriptors manipulated by redirection and piping.
3179 Some file descriptors still need to be closed in all children
3180 because of the way bash does pipes; fds_to_close is a
3181 bitmap of all such file descriptors. */
3183 close_fd_bitmap (fds_to_close);
3185 do_piping (pipe_in, pipe_out);
3189 old_interactive = interactive;
3193 subshell_environment = SUBSHELL_FORK;
3195 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
3197 #if defined (PROCESS_SUBSTITUTION)
3198 /* Try to remove named pipes that may have been created as the
3199 result of redirections. */
3200 unlink_fifo_list ();
3201 #endif /* PROCESS_SUBSTITUTION */
3202 exit (EXECUTION_FAILURE);
3206 interactive = old_interactive;
3210 internal_error ("%s: command not found", pathname);
3211 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3214 /* Execve expects the command name to be in args[0]. So we
3215 leave it there, in the same format that the user used to
3217 args = word_list_to_argv (words, 0, 0, (int *)NULL);
3218 exit (shell_execve (command, args, export_env));
3222 /* Make sure that the pipes are closed in the parent. */
3223 close_pipes (pipe_in, pipe_out);
3224 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3225 unlink_fifo_list ();
3231 #if !defined (HAVE_HASH_BANG_EXEC)
3232 /* If the operating system on which we're running does not handle
3233 the #! executable format, then help out. SAMPLE is the text read
3234 from the file, SAMPLE_LEN characters. COMMAND is the name of
3235 the script; it and ARGS, the arguments given by the user, will
3236 become arguments to the specified interpreter. ENV is the environment
3237 to pass to the interpreter.
3239 The word immediately following the #! is the interpreter to execute.
3240 A single argument to the interpreter is allowed. */
3242 /* CPP defines to decide whether a particular index into the #! line
3243 corresponds to a valid interpreter name or argument character, or
3244 whitespace. The MSDOS define is to allow \r to be treated the same
3247 #if !defined (MSDOS)
3248 # define STRINGCHAR(ind) \
3249 (!whitespace (sample[ind]) && sample[ind] != '\n' && ind < sample_len)
3250 # define WHITECHAR(ind) \
3251 (whitespace (sample[ind]) && sample[ind] != '\n' && ind < sample_len)
3253 # define STRINGCHAR(ind) \
3254 (!whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r' && ind < sample_len)
3255 # define WHITECHAR(ind) \
3256 (whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r' && ind < sample_len)
3260 execute_shell_script (sample, sample_len, command, args, env)
3261 unsigned char *sample;
3267 char *execname, *firstarg;
3268 int start, size_increment, larry;
3270 /* Find the name of the interpreter to exec. */
3271 for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
3274 for (start = i; STRINGCHAR(i); i++)
3277 execname = substring ((char *)sample, start, i);
3280 /* Now the argument, if any. */
3281 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3284 /* If there is more text on the line, then it is an argument for the
3289 for (start = i; STRINGCHAR(i); i++)
3291 firstarg = substring ((char *)sample, start, i);
3295 larry = array_len (args) + size_increment;
3297 args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
3299 for (i = larry - 1; i; i--)
3300 args[i] = args[i - size_increment];
3311 args[larry] = (char *)NULL;
3313 return (shell_execve (execname, args, env));
3318 #endif /* !HAVE_HASH_BANG_EXEC */
3321 initialize_subshell ()
3324 /* Forget about any aliases that we knew of. We are in a subshell. */
3325 delete_all_aliases ();
3328 #if defined (HISTORY)
3329 /* Forget about the history lines we have read. This is a non-interactive
3331 history_lines_this_session = 0;
3334 #if defined (JOB_CONTROL)
3335 /* Forget about the way job control was working. We are in a subshell. */
3336 without_job_control ();
3337 set_sigchld_handler ();
3338 #endif /* JOB_CONTROL */
3340 /* Reset the values of the shell flags and options. */
3341 reset_shell_flags ();
3342 reset_shell_options ();
3343 reset_shopt_options ();
3345 /* Zero out builtin_env, since this could be a shell script run from a
3346 sourced file with a temporary environment supplied to the `source/.'
3347 builtin. Such variables are not supposed to be exported (empirical
3348 testing with sh and ksh). */
3351 clear_unwind_protect_list (0);
3353 /* We're no longer inside a shell function. */
3354 variable_context = return_catch_flag = 0;
3356 /* If we're not interactive, close the file descriptor from which we're
3357 reading the current shell script. */
3358 if (interactive_shell == 0)
3359 unset_bash_input (1);
3362 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3363 # define SETOSTYPE(x) __setostype(x)
3365 # define SETOSTYPE(x)
3368 #define READ_SAMPLE_BUF(file, buf, len) \
3371 fd = open(file, O_RDONLY); \
3374 len = read (fd, (char *)buf, 80); \
3382 /* Call execve (), handling interpreting shell scripts, and handling
3385 shell_execve (command, args, env)
3391 unsigned char sample[80];
3394 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3395 execve (command, args, env);
3396 i = errno; /* error from execve() */
3399 /* If we get to this point, then start checking out the file.
3400 Maybe it is something we can hack ourselves. */
3403 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3404 internal_error ("%s: is a directory", command);
3407 #if defined (HAVE_HASH_BANG_EXEC)
3408 READ_SAMPLE_BUF (command, sample, sample_len);
3409 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3412 sys_error ("%s: bad interpreter", command);
3417 file_error (command);
3419 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3422 /* This file is executable.
3423 If it begins with #!, then help out people with losing operating
3424 systems. Otherwise, check to see if it is a binary file by seeing
3425 if the contents of the first line (or up to 80 characters) are in the
3426 ASCII set. If it's a text file, execute the contents as shell commands,
3427 otherwise return 126 (EX_BINARY_FILE). */
3428 READ_SAMPLE_BUF (command, sample, sample_len);
3430 if (sample_len == 0)
3431 return (EXECUTION_SUCCESS);
3433 /* Is this supposed to be an executable script?
3434 If so, the format of the line is "#! interpreter [argument]".
3435 A single argument is allowed. The BSD kernel restricts
3436 the length of the entire line to 32 characters (32 bytes
3437 being the size of the BSD exec header), but we allow 80
3441 #if !defined (HAVE_HASH_BANG_EXEC)
3442 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3443 return (execute_shell_script (sample, sample_len, command, args, env));
3446 if (check_binary_file (sample, sample_len))
3448 internal_error ("%s: cannot execute binary file", command);
3449 return (EX_BINARY_FILE);
3453 /* We have committed to attempting to execute the contents of this file
3454 as shell commands. */
3456 initialize_subshell ();
3458 set_sigint_handler ();
3460 /* Insert the name of this shell into the argument list. */
3461 larray = array_len (args) + 1;
3462 args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
3464 for (i = larray - 1; i; i--)
3465 args[i] = args[i - 1];
3467 args[0] = shell_name;
3469 args[larray] = (char *)NULL;
3471 if (args[0][0] == '-')
3474 #if defined (RESTRICTED_SHELL)
3476 change_flag ('r', FLAG_OFF);
3481 /* Can't free subshell_argv[0]; that is shell_name. */
3482 for (i = 1; i < subshell_argc; i++)
3483 free (subshell_argv[i]);
3484 free (subshell_argv);
3487 dispose_command (currently_executing_command); /* XXX */
3488 currently_executing_command = (COMMAND *)NULL;
3490 subshell_argc = larray;
3491 subshell_argv = args;
3492 subshell_envp = env;
3494 unbind_args (); /* remove the positional parameters */
3496 longjmp (subshell_top_level, 1);
3500 execute_intern_function (name, function)
3506 if (check_identifier (name, posixly_correct) == 0)
3508 if (posixly_correct && interactive_shell == 0)
3510 last_command_exit_value = EX_USAGE;
3511 jump_to_top_level (EXITPROG);
3513 return (EXECUTION_FAILURE);
3516 var = find_function (name->word);
3517 if (var && (readonly_p (var) || noassign_p (var)))
3519 if (readonly_p (var))
3520 internal_error ("%s: readonly function", var->name);
3521 return (EXECUTION_FAILURE);
3524 bind_function (name->word, function);
3525 return (EXECUTION_SUCCESS);
3528 #if defined (INCLUDE_UNUSED)
3529 #if defined (PROCESS_SUBSTITUTION)
3533 register int i, fd_table_size;
3535 fd_table_size = getdtablesize ();
3536 if (fd_table_size > 256) /* clamp to a reasonable value */
3537 fd_table_size = 256;
3539 for (i = 3; i < fd_table_size; i++)
3542 #endif /* PROCESS_SUBSTITUTION */
3546 close_pipes (in, out)
3555 /* Redirect input and output to be from and to the specified pipes.
3556 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3558 do_piping (pipe_in, pipe_out)
3559 int pipe_in, pipe_out;
3561 if (pipe_in != NO_PIPE)
3563 if (dup2 (pipe_in, 0) < 0)
3564 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
3568 if (pipe_out != NO_PIPE)
3570 if (pipe_out != REDIRECT_BOTH)
3572 if (dup2 (pipe_out, 1) < 0)
3573 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
3574 if (pipe_out == 0 || pipe_out > 1)
3579 if (dup2 (1, 2) < 0)
3580 sys_error ("cannot duplicate fd 1 to fd 2");