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. */
1062 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1065 int pipe_in, pipe_out;
1066 struct fd_bitmap *fds_to_close;
1068 int user_subshell, return_code, function_value, should_redir_stdin;
1071 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1072 pipe_in == NO_PIPE &&
1073 stdin_redirects (command->redirects) == 0);
1075 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1076 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1078 /* If a command is asynchronous in a subshell (like ( foo ) & or
1079 the special case of an asynchronous GROUP command where the
1080 the subshell bit is turned on down in case cm_group: below),
1081 turn off `asynchronous', so that two subshells aren't spawned.
1083 This seems semantically correct to me. For example,
1084 ( foo ) & seems to say ``do the command `foo' in a subshell
1085 environment, but don't wait for that subshell to finish'',
1086 and "{ foo ; bar ; } &" seems to me to be like functions or
1087 builtins in the background, which executed in a subshell
1088 environment. I just don't see the need to fork two subshells. */
1090 /* Don't fork again, we are already in a subshell. A `doubly
1091 async' shell is not interactive, however. */
1094 #if defined (JOB_CONTROL)
1095 /* If a construct like ( exec xxx yyy ) & is given while job
1096 control is active, we want to prevent exec from putting the
1097 subshell back into the original process group, carefully
1098 undoing all the work we just did in make_child. */
1100 #endif /* JOB_CONTROL */
1101 interactive_shell = 0;
1106 /* Subshells are neither login nor interactive. */
1107 login_shell = interactive = 0;
1109 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1111 reset_terminating_signals (); /* in sig.c */
1112 /* Cancel traps, in trap.c. */
1113 restore_original_signals ();
1115 setup_async_signals ();
1117 #if defined (JOB_CONTROL)
1118 set_sigchld_handler ();
1119 #endif /* JOB_CONTROL */
1121 set_sigint_handler ();
1123 #if defined (JOB_CONTROL)
1124 /* Delete all traces that there were any jobs running. This is
1125 only for subshells. */
1126 without_job_control ();
1127 #endif /* JOB_CONTROL */
1130 close_fd_bitmap (fds_to_close);
1132 do_piping (pipe_in, pipe_out);
1134 /* If this is a user subshell, set a flag if stdin was redirected.
1135 This is used later to decide whether to redirect fd 0 to
1136 /dev/null for async commands in the subshell. This adds more
1137 sh compatibility, but I'm not sure it's the right thing to do. */
1140 stdin_redir = stdin_redirects (command->redirects);
1141 restore_default_signal (0);
1144 /* If this is an asynchronous command (command &), we want to
1145 redirect the standard input from /dev/null in the absence of
1146 any specific redirection involving stdin. */
1147 if (should_redir_stdin && stdin_redir == 0)
1148 async_redirect_stdin ();
1150 /* Do redirections, then dispose of them before recursive call. */
1151 if (command->redirects)
1153 if (do_redirections (command->redirects, 1, 0, 0) != 0)
1154 exit (EXECUTION_FAILURE);
1156 dispose_redirects (command->redirects);
1157 command->redirects = (REDIRECT *)NULL;
1160 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1162 /* If this is a simple command, tell execute_disk_command that it
1163 might be able to get away without forking and simply exec.
1164 This means things like ( sleep 10 ) will only cause one fork.
1165 If we're timing the command, however, we cannot do this
1167 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1168 (tcom->flags & CMD_TIME_PIPELINE) == 0)
1170 tcom->flags |= CMD_NO_FORK;
1171 if (tcom->type == cm_simple)
1172 tcom->value.Simple->flags |= CMD_NO_FORK;
1175 /* If we're inside a function while executing this subshell, we
1176 need to handle a possible `return'. */
1178 if (return_catch_flag)
1179 function_value = setjmp (return_catch);
1182 return_code = return_catch_value;
1184 return_code = execute_command_internal
1185 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1187 /* If we were explicitly placed in a subshell with (), we need
1188 to do the `shell cleanup' things, such as running traps[0]. */
1189 if (user_subshell && signal_is_trapped (0))
1191 last_command_exit_value = return_code;
1192 return_code = run_exit_trap ();
1195 return (return_code);
1200 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1202 int asynchronous, pipe_in, pipe_out;
1203 struct fd_bitmap *fds_to_close;
1205 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1207 struct fd_bitmap *fd_bitmap;
1209 #if defined (JOB_CONTROL)
1211 BLOCK_CHILD (set, oset);
1212 #endif /* JOB_CONTROL */
1214 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1219 while (cmd && cmd->type == cm_connection &&
1220 cmd->value.Connection && cmd->value.Connection->connector == '|')
1222 /* Make a pipeline between the two commands. */
1223 if (pipe (fildes) < 0)
1225 sys_error ("pipe error");
1226 #if defined (JOB_CONTROL)
1227 terminate_current_pipeline ();
1228 kill_current_pipeline ();
1229 #endif /* JOB_CONTROL */
1230 last_command_exit_value = EXECUTION_FAILURE;
1231 /* The unwind-protects installed below will take care
1232 of closing all of the open file descriptors. */
1233 throw_to_top_level ();
1234 return (EXECUTION_FAILURE); /* XXX */
1237 /* Here is a problem: with the new file close-on-exec
1238 code, the read end of the pipe (fildes[0]) stays open
1239 in the first process, so that process will never get a
1240 SIGPIPE. There is no way to signal the first process
1241 that it should close fildes[0] after forking, so it
1242 remains open. No SIGPIPE is ever sent because there
1243 is still a file descriptor open for reading connected
1244 to the pipe. We take care of that here. This passes
1245 around a bitmap of file descriptors that must be
1246 closed after making a child process in execute_simple_command. */
1248 /* We need fd_bitmap to be at least as big as fildes[0].
1249 If fildes[0] is less than fds_to_close->size, then
1250 use fds_to_close->size. */
1251 new_bitmap_size = (fildes[0] < fds_to_close->size)
1252 ? fds_to_close->size
1255 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1257 /* Now copy the old information into the new bitmap. */
1258 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1260 /* And mark the pipe file descriptors to be closed. */
1261 fd_bitmap->bitmap[fildes[0]] = 1;
1263 /* In case there are pipe or out-of-processes errors, we
1264 want all these file descriptors to be closed when
1265 unwind-protects are run, and the storage used for the
1266 bitmaps freed up. */
1267 begin_unwind_frame ("pipe-file-descriptors");
1268 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1269 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1271 add_unwind_protect (close, prev);
1272 dummyfd = fildes[1];
1273 add_unwind_protect (close, dummyfd);
1275 #if defined (JOB_CONTROL)
1276 add_unwind_protect (restore_signal_mask, oset);
1277 #endif /* JOB_CONTROL */
1279 if (ignore_return && cmd->value.Connection->first)
1280 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1281 execute_command_internal (cmd->value.Connection->first, asynchronous,
1282 prev, fildes[1], fd_bitmap);
1290 dispose_fd_bitmap (fd_bitmap);
1291 discard_unwind_frame ("pipe-file-descriptors");
1293 cmd = cmd->value.Connection->second;
1296 /* Now execute the rightmost command in the pipeline. */
1297 if (ignore_return && cmd)
1298 cmd->flags |= CMD_IGNORE_RETURN;
1299 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1304 #if defined (JOB_CONTROL)
1305 UNBLOCK_CHILD (oset);
1308 return (exec_result);
1312 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1314 int asynchronous, pipe_in, pipe_out;
1315 struct fd_bitmap *fds_to_close;
1321 COMMAND *tc, *second;
1322 int ignore_return, exec_result;
1324 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1326 switch (command->value.Connection->connector)
1328 /* Do the first command asynchronously. */
1330 tc = command->value.Connection->first;
1332 return (EXECUTION_SUCCESS);
1337 tc->flags |= CMD_IGNORE_RETURN;
1338 tc->flags |= CMD_AMPERSAND;
1340 /* If this shell was compiled without job control support, if
1341 the shell is not running interactively, if we are currently
1342 in a subshell via `( xxx )', or if job control is not active
1343 then the standard input for an asynchronous command is
1344 forced to /dev/null. */
1345 #if defined (JOB_CONTROL)
1346 if ((!interactive_shell || subshell_environment || !job_control) && !stdin_redir)
1349 #endif /* JOB_CONTROL */
1352 rd.filename = make_bare_word ("/dev/null");
1353 tr = make_redirection (0, r_inputa_direction, rd);
1354 tr->next = tc->redirects;
1357 tc->flags |= CMD_STDIN_REDIR;
1360 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1362 if (tc->flags & CMD_STDIN_REDIR)
1365 /* Remove the redirection we added above. It matters,
1366 especially for loops, which call execute_command ()
1367 multiple times with the same command. */
1372 tc->redirects = tc->redirects->next;
1374 while (tc->redirects && tc->redirects != rp);
1376 tl->next = (REDIRECT *)NULL;
1377 dispose_redirects (tr);
1379 tc->flags &= ~CMD_STDIN_REDIR;
1382 second = command->value.Connection->second;
1386 second->flags |= CMD_IGNORE_RETURN;
1388 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1393 /* Just call execute command on both sides. */
1397 if (command->value.Connection->first)
1398 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1399 if (command->value.Connection->second)
1400 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1403 execute_command (command->value.Connection->first);
1405 exec_result = execute_command_internal (command->value.Connection->second,
1406 asynchronous, pipe_in, pipe_out,
1411 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1418 /* If we have something like `a && b &' or `a || b &', run the
1419 && or || stuff in a subshell. Force a subshell and just call
1420 execute_command_internal again. Leave asynchronous on
1421 so that we get a report from the parent shell about the
1423 command->flags |= CMD_FORCE_SUBSHELL;
1424 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1428 /* Execute the first command. If the result of that is successful
1429 and the connector is AND_AND, or the result is not successful
1430 and the connector is OR_OR, then execute the second command,
1431 otherwise return. */
1433 if (command->value.Connection->first)
1434 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1436 exec_result = execute_command (command->value.Connection->first);
1438 if (((command->value.Connection->connector == AND_AND) &&
1439 (exec_result == EXECUTION_SUCCESS)) ||
1440 ((command->value.Connection->connector == OR_OR) &&
1441 (exec_result != EXECUTION_SUCCESS)))
1443 if (ignore_return && command->value.Connection->second)
1444 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1446 exec_result = execute_command (command->value.Connection->second);
1451 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1452 jump_to_top_level (DISCARD);
1453 exec_result = EXECUTION_FAILURE;
1462 if (!interactive_shell) \
1463 reap_dead_jobs (); \
1467 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1470 execute_for_command (for_command)
1471 FOR_COM *for_command;
1473 register WORD_LIST *releaser, *list;
1478 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1481 if (check_identifier (for_command->name, 1) == 0)
1483 if (posixly_correct && interactive_shell == 0)
1485 last_command_exit_value = EX_USAGE;
1486 jump_to_top_level (EXITPROG);
1488 return (EXECUTION_FAILURE);
1492 identifier = for_command->name->word;
1494 list = releaser = expand_words_no_vars (for_command->map_list);
1496 begin_unwind_frame ("for");
1497 add_unwind_protect (dispose_words, releaser);
1500 if (lexical_scoping)
1502 old_value = copy_variable (find_variable (identifier));
1504 add_unwind_protect (dispose_variable, old_value);
1508 if (for_command->flags & CMD_IGNORE_RETURN)
1509 for_command->action->flags |= CMD_IGNORE_RETURN;
1511 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1514 this_command_name = (char *)NULL;
1515 v = bind_variable (identifier, list->word->word);
1518 if (interactive_shell == 0 && posixly_correct)
1520 last_command_exit_value = EXECUTION_FAILURE;
1521 jump_to_top_level (FORCE_EOF);
1525 run_unwind_frame ("for");
1527 return (EXECUTION_FAILURE);
1530 retval = execute_command (for_command->action);
1551 if (lexical_scoping)
1554 makunbound (identifier, shell_variables);
1557 SHELL_VAR *new_value;
1559 new_value = bind_variable (identifier, value_cell(old_value));
1560 new_value->attributes = old_value->attributes;
1561 dispose_variable (old_value);
1566 dispose_words (releaser);
1567 discard_unwind_frame ("for");
1571 #if defined (ARITH_FOR_COMMAND)
1572 /* Execute an arithmetic for command. The syntax is
1574 for (( init ; step ; test ))
1579 The execution should be exactly equivalent to
1582 while eval \(\( test \)\) ; do
1588 eval_arith_for_expr (l, okp)
1595 new = expand_words_no_vars (l);
1596 if (echo_command_at_execute)
1597 xtrace_print_arith_cmd (new);
1598 expresult = evalexp (new->word->word, okp);
1599 dispose_words (new);
1604 execute_arith_for_command (arith_for_command)
1605 ARITH_FOR_COM *arith_for_command;
1608 int expok, result, body_status;
1610 body_status = EXECUTION_SUCCESS;
1613 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1614 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1616 this_command_name = "(("; /* )) for expression error messages */
1618 if (variable_context)
1619 line_number = arith_for_command->line - function_line_number;
1621 /* Evaluate the initialization expression. */
1622 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1624 return (EXECUTION_FAILURE);
1628 /* Evaluate the test expression. */
1629 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1632 body_status = EXECUTION_FAILURE;
1639 /* Execute the body of the arithmetic for command. */
1641 body_status = execute_command (arith_for_command->action);
1644 /* Handle any `break' or `continue' commands executed by the body. */
1658 /* Evaluate the step expression. */
1659 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1662 body_status = EXECUTION_FAILURE;
1668 return (body_status);
1672 #if defined (SELECT_COMMAND)
1673 static int LINES, COLS, tabsize;
1675 #define RP_SPACE ") "
1676 #define RP_SPACE_LEN 2
1678 /* XXX - does not handle numbers > 1000000 at all. */
1679 #define NUMBER_LEN(s) \
1683 : ((s < 10000) ? 4 \
1684 : ((s < 100000) ? 5 \
1688 print_index_and_element (len, ind, list)
1692 register WORD_LIST *l;
1697 for (i = ind, l = list; l && --i; l = l->next)
1699 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1700 return (STRLEN (l->word->word));
1709 if ((to / tabsize) > (from / tabsize))
1711 putc ('\t', stderr);
1712 from += tabsize - from % tabsize;
1723 print_select_list (list, list_len, max_elem_len, indices_len)
1725 int list_len, max_elem_len, indices_len;
1727 int ind, row, elem_len, pos, cols, rows;
1728 int first_column_indices_len, other_indices_len;
1732 putc ('\n', stderr);
1736 cols = max_elem_len ? COLS / max_elem_len : 1;
1739 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1740 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1748 first_column_indices_len = NUMBER_LEN (rows);
1749 other_indices_len = indices_len;
1751 for (row = 0; row < rows; row++)
1757 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1758 elem_len = print_index_and_element (indices_len, ind + 1, list);
1759 elem_len += indices_len + RP_SPACE_LEN;
1761 if (ind >= list_len)
1763 indent (pos + elem_len, pos + max_elem_len);
1764 pos += max_elem_len;
1766 putc ('\n', stderr);
1770 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1771 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1772 If the number is between 1 and LIST_LEN, return that selection. If EOF
1773 is read, return a null string. If a blank line is entered, or an invalid
1774 number is entered, the loop is executed again. */
1776 select_query (list, list_len, prompt)
1781 int max_elem_len, indices_len, len;
1784 char *repl_string, *t;
1786 t = get_string_value ("LINES");
1787 LINES = (t && *t) ? atoi (t) : 24;
1788 t = get_string_value ("COLUMNS");
1789 COLS = (t && *t) ? atoi (t) : 80;
1792 t = get_string_value ("TABSIZE");
1793 tabsize = (t && *t) ? atoi (t) : 8;
1801 for (l = list; l; l = l->next)
1803 len = STRLEN (l->word->word);
1804 if (len > max_elem_len)
1807 indices_len = NUMBER_LEN (list_len);
1808 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1812 print_select_list (list, list_len, max_elem_len, indices_len);
1813 fprintf (stderr, "%s", prompt);
1817 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1820 return ((char *)NULL);
1822 repl_string = get_string_value ("REPLY");
1823 if (*repl_string == 0)
1825 if (legal_number (repl_string, &reply) == 0)
1827 if (reply < 1 || reply > list_len)
1830 for (l = list; l && --reply; l = l->next)
1832 return (l->word->word);
1836 /* Execute a SELECT command. The syntax is:
1837 SELECT word IN list DO command_list DONE
1838 Only `break' or `return' in command_list will terminate
1841 execute_select_command (select_command)
1842 SELECT_COM *select_command;
1844 WORD_LIST *releaser, *list;
1846 char *identifier, *ps3_prompt, *selection;
1847 int retval, list_len, return_val;
1849 if (check_identifier (select_command->name, 1) == 0)
1850 return (EXECUTION_FAILURE);
1853 identifier = select_command->name->word;
1855 /* command and arithmetic substitution, parameter and variable expansion,
1856 word splitting, pathname expansion, and quote removal. */
1857 list = releaser = expand_words_no_vars (select_command->map_list);
1858 list_len = list_length (list);
1859 if (list == 0 || list_len == 0)
1862 dispose_words (list);
1863 return (EXECUTION_SUCCESS);
1866 begin_unwind_frame ("select");
1867 add_unwind_protect (dispose_words, releaser);
1869 if (select_command->flags & CMD_IGNORE_RETURN)
1870 select_command->action->flags |= CMD_IGNORE_RETURN;
1872 retval = EXECUTION_SUCCESS;
1874 unwind_protect_int (return_catch_flag);
1875 unwind_protect_jmp_buf (return_catch);
1876 return_catch_flag++;
1880 ps3_prompt = get_string_value ("PS3");
1881 if (ps3_prompt == 0)
1885 selection = select_query (list, list_len, ps3_prompt);
1890 v = bind_variable (identifier, selection);
1893 if (interactive_shell == 0 && posixly_correct)
1895 last_command_exit_value = EXECUTION_FAILURE;
1896 jump_to_top_level (FORCE_EOF);
1900 run_unwind_frame ("select");
1901 return (EXECUTION_FAILURE);
1905 return_val = setjmp (return_catch);
1909 retval = return_catch_value;
1913 retval = execute_command (select_command->action);
1934 run_unwind_frame ("select");
1937 #endif /* SELECT_COMMAND */
1939 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1940 The pattern_list is a linked list of pattern clauses; each clause contains
1941 some patterns to compare word_desc against, and an associated command to
1944 execute_case_command (case_command)
1945 CASE_COM *case_command;
1947 register WORD_LIST *list;
1948 WORD_LIST *wlist, *es;
1949 PATTERN_LIST *clauses;
1950 char *word, *pattern;
1951 int retval, match, ignore_return;
1953 /* Posix.2 specifies that the WORD is tilde expanded. */
1954 if (member ('~', case_command->word->word))
1956 word = bash_tilde_expand (case_command->word->word);
1957 free (case_command->word->word);
1958 case_command->word->word = word;
1961 wlist = expand_word_no_split (case_command->word, 0);
1962 word = wlist ? string_list (wlist) : savestring ("");
1963 dispose_words (wlist);
1965 retval = EXECUTION_SUCCESS;
1966 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
1968 begin_unwind_frame ("case");
1969 add_unwind_protect ((Function *)xfree, word);
1971 #define EXIT_CASE() goto exit_case_command
1973 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
1976 for (list = clauses->patterns; list; list = list->next)
1978 /* Posix.2 specifies to tilde expand each member of the pattern
1980 if (member ('~', list->word->word))
1982 pattern = bash_tilde_expand (list->word->word);
1983 free (list->word->word);
1984 list->word->word = pattern;
1987 es = expand_word_leave_quoted (list->word, 0);
1989 if (es && es->word && es->word->word && *(es->word->word))
1990 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
1993 pattern = xmalloc (1);
1997 /* Since the pattern does not undergo quote removal (as per
1998 Posix.2, section 3.9.4.3), the fnmatch () call must be able
1999 to recognize backslashes as escape characters. */
2000 match = fnmatch (pattern, word, FNMATCH_EXTFLAG) != FNM_NOMATCH;
2007 if (clauses->action && ignore_return)
2008 clauses->action->flags |= CMD_IGNORE_RETURN;
2009 retval = execute_command (clauses->action);
2019 discard_unwind_frame ("case");
2026 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2027 Repeatedly execute action while executing test produces
2028 EXECUTION_SUCCESS. */
2030 execute_while_command (while_command)
2031 WHILE_COM *while_command;
2033 return (execute_while_or_until (while_command, CMD_WHILE));
2036 /* UNTIL is just like WHILE except that the test result is negated. */
2038 execute_until_command (while_command)
2039 WHILE_COM *while_command;
2041 return (execute_while_or_until (while_command, CMD_UNTIL));
2044 /* The body for both while and until. The only difference between the
2045 two is that the test value is treated differently. TYPE is
2046 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2047 be EXECUTION_SUCCESS if no commands in the body are executed, and
2048 the status of the last command executed in the body otherwise. */
2050 execute_while_or_until (while_command, type)
2051 WHILE_COM *while_command;
2054 int return_value, body_status;
2056 body_status = EXECUTION_SUCCESS;
2059 while_command->test->flags |= CMD_IGNORE_RETURN;
2060 if (while_command->flags & CMD_IGNORE_RETURN)
2061 while_command->action->flags |= CMD_IGNORE_RETURN;
2065 return_value = execute_command (while_command->test);
2068 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2070 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2074 body_status = execute_command (while_command->action);
2092 return (body_status);
2095 /* IF test THEN command [ELSE command].
2096 IF also allows ELIF in the place of ELSE IF, but
2097 the parser makes *that* stupidity transparent. */
2099 execute_if_command (if_command)
2104 if_command->test->flags |= CMD_IGNORE_RETURN;
2105 return_value = execute_command (if_command->test);
2107 if (return_value == EXECUTION_SUCCESS)
2111 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2112 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2114 return (execute_command (if_command->true_case));
2120 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2121 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2123 return (execute_command (if_command->false_case));
2127 #if defined (DPAREN_ARITHMETIC)
2129 execute_arith_command (arith_command)
2130 ARITH_COM *arith_command;
2132 int result, expok, expresult;
2133 WORD_LIST *new, *p, *printit;
2138 this_command_name = "(("; /* )) */
2139 /* If we're in a function, update the line number information. */
2140 if (variable_context)
2141 line_number = arith_command->line - function_line_number;
2143 new = expand_words (arith_command->exp);
2145 /* If we're tracing, make a new word list with `((' at the front and `))'
2146 at the back and print it. */
2147 if (echo_command_at_execute)
2148 xtrace_print_arith_cmd (new);
2150 result = evalexp (new->word->word, &expok);
2151 dispose_words (new);
2154 return (EXECUTION_FAILURE);
2156 return (result == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2158 #endif /* DPAREN_ARITHMETIC */
2160 #if defined (COND_COMMAND)
2162 static char *nullstr = "";
2165 execute_cond_node (cond)
2168 int result, invert, patmatch, flags;
2169 char *arg1, *arg2, *print2;
2171 invert = (cond->flags & CMD_INVERT_RETURN);
2173 if (cond->type == COND_EXPR)
2174 result = execute_cond_node (cond->left);
2175 else if (cond->type == COND_OR)
2177 result = execute_cond_node (cond->left);
2178 if (result != EXECUTION_SUCCESS)
2179 result = execute_cond_node (cond->right);
2181 else if (cond->type == COND_AND)
2183 result = execute_cond_node (cond->left);
2184 if (result == EXECUTION_SUCCESS)
2185 result = execute_cond_node (cond->right);
2187 else if (cond->type == COND_UNARY)
2189 arg1 = cond_expand_word (cond->left->op, 0);
2192 if (echo_command_at_execute)
2193 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2194 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2195 if (arg1 != nullstr)
2198 else if (cond->type == COND_BINARY)
2200 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2201 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2202 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2204 arg1 = cond_expand_word (cond->left->op, 0);
2207 arg2 = cond_expand_word (cond->right->op, patmatch);
2211 if (echo_command_at_execute)
2212 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2214 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2216 : EXECUTION_FAILURE;
2217 if (arg1 != nullstr)
2219 if (arg2 != nullstr)
2224 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2225 jump_to_top_level (DISCARD);
2226 result = EXECUTION_FAILURE;
2230 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2236 execute_cond_command (cond_command)
2237 COND_COM *cond_command;
2241 result = EXECUTION_SUCCESS;
2243 this_command_name = "[[";
2244 /* If we're in a function, update the line number information. */
2245 if (variable_context)
2246 line_number = cond_command->line - function_line_number;
2249 debug_print_cond_command (cond_command);
2251 last_command_exit_value = result = execute_cond_node (cond_command);
2254 #endif /* COND_COMMAND */
2264 var = bind_variable ("_", arg);
2265 VUNSETATTR (var, att_exported);
2268 /* Execute a null command. Fork a subshell if the command uses pipes or is
2269 to be run asynchronously. This handles all the side effects that are
2270 supposed to take place. */
2272 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2273 REDIRECT *redirects;
2274 int pipe_in, pipe_out, async;
2275 pid_t old_last_command_subst_pid;
2277 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2279 /* We have a null command, but we really want a subshell to take
2280 care of it. Just fork, do piping and redirections, and exit. */
2281 if (make_child ((char *)NULL, async) == 0)
2283 /* Cancel traps, in trap.c. */
2284 restore_original_signals (); /* XXX */
2286 do_piping (pipe_in, pipe_out);
2288 subshell_environment = SUBSHELL_ASYNC;
2290 if (do_redirections (redirects, 1, 0, 0) == 0)
2291 exit (EXECUTION_SUCCESS);
2293 exit (EXECUTION_FAILURE);
2297 close_pipes (pipe_in, pipe_out);
2298 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2299 unlink_fifo_list ();
2301 return (EXECUTION_SUCCESS);
2306 /* Even if there aren't any command names, pretend to do the
2307 redirections that are specified. The user expects the side
2308 effects to take place. If the redirections fail, then return
2309 failure. Otherwise, if a command substitution took place while
2310 expanding the command or a redirection, return the value of that
2311 substitution. Otherwise, return EXECUTION_SUCCESS. */
2313 if (do_redirections (redirects, 0, 0, 0) != 0)
2314 return (EXECUTION_FAILURE);
2315 else if (old_last_command_subst_pid != last_command_subst_pid)
2316 return (last_command_exit_value);
2318 return (EXECUTION_SUCCESS);
2322 /* This is a hack to suppress word splitting for assignment statements
2323 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2325 fix_assignment_words (words)
2334 b = builtin_address_internal (words->word->word, 0);
2335 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2338 for (w = words; w; w = w->next)
2339 if (w->word->flags & W_ASSIGNMENT)
2340 w->word->flags |= (W_NOSPLIT|W_NOGLOB);
2343 /* The meaty part of all the executions. We have to start hacking the
2344 real execution of commands here. Fork a process, set things up,
2345 execute the command. */
2347 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2348 SIMPLE_COM *simple_command;
2349 int pipe_in, pipe_out, async;
2350 struct fd_bitmap *fds_to_close;
2352 WORD_LIST *words, *lastword;
2353 char *command_line, *lastarg, *temp;
2354 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2355 pid_t old_last_command_subst_pid, old_last_async_pid;
2359 result = EXECUTION_SUCCESS;
2360 special_builtin_failed = builtin_is_special = 0;
2361 command_line = (char *)0;
2363 /* If we're in a function, update the line number information. */
2364 if (variable_context)
2365 line_number = simple_command->line - function_line_number;
2367 /* Remember what this command line looks like at invocation. */
2368 command_string_index = 0;
2369 print_simple_command (simple_command);
2372 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2374 old_last_command_subst_pid = last_command_subst_pid;
2375 old_last_async_pid = last_asynchronous_pid;
2377 already_forked = dofork = 0;
2379 /* If we're in a pipeline or run in the background, set DOFORK so we
2380 make the child early, before word expansion. This keeps assignment
2381 statements from affecting the parent shell's environment when they
2383 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2385 /* Something like `%2 &' should restart job 2 in the background, not cause
2386 the shell to fork here. */
2387 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2388 simple_command->words && simple_command->words->word &&
2389 simple_command->words->word->word &&
2390 (simple_command->words->word->word[0] == '%'))
2395 /* XXX memory leak if expand_words() error causes a jump_to_top_level */
2396 command_line = savestring (the_printed_command);
2398 /* Do this now, because execute_disk_command will do it anyway in the
2399 vast majority of cases. */
2400 maybe_make_export_env ();
2402 if (make_child (command_line, async) == 0)
2405 simple_command->flags |= CMD_NO_FORK;
2407 /* We need to do this before piping to handle some really
2408 pathological cases where one of the pipe file descriptors
2411 close_fd_bitmap (fds_to_close);
2413 do_piping (pipe_in, pipe_out);
2414 pipe_in = pipe_out = -1;
2416 last_asynchronous_pid = old_last_async_pid;
2417 subshell_environment = async ? SUBSHELL_ASYNC : SUBSHELL_FORK;
2421 close_pipes (pipe_in, pipe_out);
2422 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2423 unlink_fifo_list ();
2425 command_line = (char *)NULL; /* don't free this. */
2426 bind_lastarg ((char *)NULL);
2431 /* If we are re-running this as the result of executing the `command'
2432 builtin, do not expand the command words a second time. */
2433 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2435 current_fds_to_close = fds_to_close;
2436 fix_assignment_words (simple_command->words);
2437 words = expand_words (simple_command->words);
2438 current_fds_to_close = (struct fd_bitmap *)NULL;
2441 words = copy_word_list (simple_command->words);
2443 /* It is possible for WORDS not to have anything left in it.
2444 Perhaps all the words consisted of `$foo', and there was
2445 no variable `$foo'. */
2448 result = execute_null_command (simple_command->redirects,
2450 already_forked ? 0 : async,
2451 old_last_command_subst_pid);
2456 bind_lastarg ((char *)NULL);
2457 set_pipestatus_from_exit (result);
2462 lastarg = (char *)NULL;
2464 begin_unwind_frame ("simple-command");
2466 if (echo_command_at_execute)
2467 xtrace_print_word_list (words);
2469 builtin = (Function *)NULL;
2470 func = (SHELL_VAR *)NULL;
2471 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2473 /* Posix.2 says special builtins are found before functions. We
2474 don't set builtin_is_special anywhere other than here, because
2475 this path is followed only when the `command' builtin is *not*
2476 being used, and we don't want to exit the shell if a special
2477 builtin executed with `command builtin' fails. `command' is not
2478 a special builtin. */
2479 if (posixly_correct)
2481 builtin = find_special_builtin (words->word->word);
2483 builtin_is_special = 1;
2486 func = find_function (words->word->word);
2489 add_unwind_protect (dispose_words, words);
2492 /* Bind the last word in this command to "$_" after execution. */
2493 for (lastword = words; lastword->next; lastword = lastword->next)
2495 lastarg = lastword->word->word;
2497 #if defined (JOB_CONTROL)
2498 /* Is this command a job control related thing? */
2499 if (words->word->word[0] == '%' && already_forked == 0)
2501 this_command_name = async ? "bg" : "fg";
2502 last_shell_builtin = this_shell_builtin;
2503 this_shell_builtin = builtin_address (this_command_name);
2504 result = (*this_shell_builtin) (words);
2508 /* One other possiblilty. The user may want to resume an existing job.
2509 If they do, find out whether this word is a candidate for a running
2511 if (job_control && already_forked == 0 && async == 0 &&
2512 !first_word_quoted &&
2514 words->word->word[0] &&
2515 !simple_command->redirects &&
2516 pipe_in == NO_PIPE &&
2517 pipe_out == NO_PIPE &&
2518 (temp = get_string_value ("auto_resume")))
2522 int wl, cl, exact, substring, match, started_status;
2523 register PROCESS *p;
2525 word = words->word->word;
2526 exact = STREQ (temp, "exact");
2527 substring = STREQ (temp, "substring");
2529 for (i = job_slots - 1; i > -1; i--)
2531 if (jobs[i] == 0 || (JOBSTATE (i) != JSTOPPED))
2539 cl = strlen (p->command);
2540 match = STREQN (p->command, word, cl);
2543 match = strindex (p->command, word) != (char *)0;
2545 match = STREQN (p->command, word, wl);
2553 run_unwind_frame ("simple-command");
2554 this_command_name = "fg";
2555 last_shell_builtin = this_shell_builtin;
2556 this_shell_builtin = builtin_address ("fg");
2558 started_status = start_job (i, 1);
2559 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2561 while (p != jobs[i]->pipe);
2564 #endif /* JOB_CONTROL */
2566 /* Remember the name of this command globally. */
2567 this_command_name = words->word->word;
2571 /* This command could be a shell builtin or a user-defined function.
2572 We have already found special builtins by this time, so we do not
2573 set builtin_is_special. If this is a function or builtin, and we
2574 have pipes, then fork a subshell in here. Otherwise, just execute
2575 the command directly. */
2576 if (func == 0 && builtin == 0)
2577 builtin = find_shell_builtin (this_command_name);
2579 last_shell_builtin = this_shell_builtin;
2580 this_shell_builtin = builtin;
2582 if (builtin || func)
2586 /* reset_terminating_signals (); */ /* XXX */
2587 /* Cancel traps, in trap.c. */
2588 restore_original_signals ();
2592 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2593 pipe_in == NO_PIPE &&
2594 (stdin_redirects (simple_command->redirects) == 0))
2595 async_redirect_stdin ();
2596 setup_async_signals ();
2599 execute_subshell_builtin_or_function
2600 (words, simple_command->redirects, builtin, func,
2601 pipe_in, pipe_out, async, fds_to_close,
2602 simple_command->flags);
2606 result = execute_builtin_or_function
2607 (words, builtin, func, simple_command->redirects, fds_to_close,
2608 simple_command->flags);
2611 if (result > EX_SHERRBASE)
2613 result = builtin_status (result);
2614 if (builtin_is_special)
2615 special_builtin_failed = 1;
2617 /* In POSIX mode, if there are assignment statements preceding
2618 a special builtin, they persist after the builtin
2620 if (posixly_correct && builtin_is_special && temporary_env)
2621 merge_temporary_env ();
2625 if (result == EX_USAGE)
2626 result = EX_BADUSAGE;
2627 else if (result > EX_SHERRBASE)
2628 result = EXECUTION_FAILURE;
2631 set_pipestatus_from_exit (result);
2637 if (command_line == 0)
2638 command_line = savestring (the_printed_command);
2640 execute_disk_command (words, simple_command->redirects, command_line,
2641 pipe_in, pipe_out, async, fds_to_close,
2642 simple_command->flags);
2645 bind_lastarg (lastarg);
2646 FREE (command_line);
2647 run_unwind_frame ("simple-command");
2651 /* Translate the special builtin exit statuses. We don't really need a
2652 function for this; it's a placeholder for future work. */
2654 builtin_status (result)
2668 r = EXECUTION_FAILURE;
2671 r = EXECUTION_SUCCESS;
2678 execute_builtin (builtin, words, flags, subshell)
2681 int flags, subshell;
2683 int old_e_flag, result, eval_unwind;
2685 old_e_flag = exit_immediately_on_error;
2686 /* The eval builtin calls parse_and_execute, which does not know about
2687 the setting of flags, and always calls the execution functions with
2688 flags that will exit the shell on an error if -e is set. If the
2689 eval builtin is being called, and we're supposed to ignore the exit
2690 value of the command, we turn the -e flag off ourselves, then
2691 restore it when the command completes. */
2692 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2694 begin_unwind_frame ("eval_builtin");
2695 unwind_protect_int (exit_immediately_on_error);
2696 exit_immediately_on_error = 0;
2702 /* The temporary environment for a builtin is supposed to apply to
2703 all commands executed by that builtin. Currently, this is a
2704 problem only with the `source' and `eval' builtins. */
2705 if (builtin == source_builtin || builtin == eval_builtin)
2708 begin_unwind_frame ("builtin_env");
2712 builtin_env = copy_array (temporary_env);
2714 add_unwind_protect (dispose_builtin_env, (char *)NULL);
2715 dispose_used_env_vars ();
2719 builtin_env = (char **)NULL;
2723 result = ((*builtin) (words->next));
2725 if (subshell == 0 && (builtin == source_builtin || builtin == eval_builtin))
2727 /* In POSIX mode, if any variable assignments precede the `.' or
2728 `eval' builtin, they persist after the builtin completes, since `.'
2729 and `eval' are special builtins. */
2730 if (posixly_correct && builtin_env)
2731 merge_builtin_env ();
2733 dispose_builtin_env ();
2734 discard_unwind_frame ("builtin_env");
2736 run_unwind_frame ("builtin_env");
2742 exit_immediately_on_error += old_e_flag;
2743 discard_unwind_frame ("eval_builtin");
2750 execute_function (var, words, flags, fds_to_close, async, subshell)
2753 int flags, subshell, async;
2754 struct fd_bitmap *fds_to_close;
2756 int return_val, result;
2759 SHELL_VAR *old_shell_function;
2761 tc = (COMMAND *)copy_command (function_cell (var));
2762 if (tc && (flags & CMD_IGNORE_RETURN))
2763 tc->flags |= CMD_IGNORE_RETURN;
2767 begin_unwind_frame ("function_calling");
2769 add_unwind_protect (pop_context, (char *)NULL);
2770 unwind_protect_int (line_number);
2771 unwind_protect_int (return_catch_flag);
2772 unwind_protect_jmp_buf (return_catch);
2773 add_unwind_protect (dispose_command, (char *)tc);
2774 unwind_protect_pointer (this_shell_function);
2775 unwind_protect_int (loop_level);
2778 this_shell_function = var;
2779 make_funcname_visible (1);
2781 debug_trap = (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2782 ? trap_list[DEBUG_TRAP]
2788 debug_trap = savestring (debug_trap);
2789 /* XXX order is important here! unwind-protect commands are run
2790 in reverse order of registering. If this causes problems,
2791 take out the xfree unwind-protect and live with the small
2793 add_unwind_protect (xfree, debug_trap);
2794 add_unwind_protect (set_debug_trap, debug_trap);
2796 restore_default_signal (DEBUG_TRAP);
2799 /* The temporary environment for a function is supposed to apply to
2800 all commands executed within the function body. */
2803 function_env = copy_array (temporary_env);
2805 add_unwind_protect (dispose_function_env, (char *)NULL);
2806 dispose_used_env_vars ();
2810 function_env = (char **)NULL;
2813 remember_args (words->next, 1);
2815 /* Number of the line on which the function body starts. */
2816 line_number = function_line_number = tc->line;
2820 #if defined (JOB_CONTROL)
2821 stop_pipeline (async, (COMMAND *)NULL);
2823 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
2825 if (fc && (flags & CMD_IGNORE_RETURN))
2826 fc->flags |= CMD_IGNORE_RETURN;
2833 return_catch_flag++;
2834 return_val = setjmp (return_catch);
2837 result = return_catch_value;
2839 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2842 run_unwind_frame ("function_calling");
2844 if (variable_context == 0 || this_shell_function == 0)
2845 make_funcname_visible (0);
2850 /* A convenience routine for use by other parts of the shell to execute
2851 a particular shell function. */
2853 execute_shell_function (var, words)
2858 struct fd_bitmap *bitmap;
2860 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
2861 begin_unwind_frame ("execute-shell-function");
2862 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
2864 ret = execute_function (var, words, 0, bitmap, 0, 0);
2866 dispose_fd_bitmap (bitmap);
2867 discard_unwind_frame ("execute-shell-function");
2872 /* Execute a shell builtin or function in a subshell environment. This
2873 routine does not return; it only calls exit(). If BUILTIN is non-null,
2874 it points to a function to call to execute a shell builtin; otherwise
2875 VAR points at the body of a function to execute. WORDS is the arguments
2876 to the command, REDIRECTS specifies redirections to perform before the
2877 command is executed. */
2879 execute_subshell_builtin_or_function (words, redirects, builtin, var,
2880 pipe_in, pipe_out, async, fds_to_close,
2883 REDIRECT *redirects;
2886 int pipe_in, pipe_out, async;
2887 struct fd_bitmap *fds_to_close;
2891 #if defined (JOB_CONTROL)
2894 jobs_hack = (builtin == jobs_builtin) &&
2895 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
2898 /* A subshell is neither a login shell nor interactive. */
2899 login_shell = interactive = 0;
2901 subshell_environment = SUBSHELL_ASYNC;
2903 maybe_make_export_env (); /* XXX - is this needed? */
2905 #if defined (JOB_CONTROL)
2906 /* Eradicate all traces of job control after we fork the subshell, so
2907 all jobs begun by this subshell are in the same process group as
2908 the shell itself. */
2910 /* Allow the output of `jobs' to be piped. */
2912 kill_current_pipeline ();
2914 without_job_control ();
2916 set_sigchld_handler ();
2917 #endif /* JOB_CONTROL */
2919 set_sigint_handler ();
2922 close_fd_bitmap (fds_to_close);
2924 do_piping (pipe_in, pipe_out);
2926 if (do_redirections (redirects, 1, 0, 0) != 0)
2927 exit (EXECUTION_FAILURE);
2931 /* Give builtins a place to jump back to on failure,
2932 so we don't go back up to main(). */
2933 result = setjmp (top_level);
2935 if (result == EXITPROG)
2936 exit (last_command_exit_value);
2938 exit (EXECUTION_FAILURE);
2941 r = execute_builtin (builtin, words, flags, 1);
2948 exit (execute_function (var, words, flags, fds_to_close, async, 1));
2951 /* Execute a builtin or function in the current shell context. If BUILTIN
2952 is non-null, it is the builtin command to execute, otherwise VAR points
2953 to the body of a function. WORDS are the command's arguments, REDIRECTS
2954 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2955 file descriptors to close.
2957 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2958 not undone before this function returns. */
2960 execute_builtin_or_function (words, builtin, var, redirects,
2961 fds_to_close, flags)
2965 REDIRECT *redirects;
2966 struct fd_bitmap *fds_to_close;
2970 REDIRECT *saved_undo_list;
2972 if (do_redirections (redirects, 1, 1, 0) != 0)
2974 cleanup_redirects (redirection_undo_list);
2975 redirection_undo_list = (REDIRECT *)NULL;
2976 dispose_exec_redirects ();
2977 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
2980 saved_undo_list = redirection_undo_list;
2982 /* Calling the "exec" builtin changes redirections forever. */
2983 if (builtin == exec_builtin)
2985 dispose_redirects (saved_undo_list);
2986 saved_undo_list = exec_redirection_undo_list;
2987 exec_redirection_undo_list = (REDIRECT *)NULL;
2990 dispose_exec_redirects ();
2992 if (saved_undo_list)
2994 begin_unwind_frame ("saved redirects");
2995 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
2998 redirection_undo_list = (REDIRECT *)NULL;
3001 result = execute_builtin (builtin, words, flags, 0);
3003 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3005 if (saved_undo_list)
3007 redirection_undo_list = saved_undo_list;
3008 discard_unwind_frame ("saved redirects");
3011 if (redirection_undo_list)
3013 cleanup_redirects (redirection_undo_list);
3014 redirection_undo_list = (REDIRECT *)NULL;
3021 setup_async_signals ()
3023 #if defined (__BEOS__)
3024 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3027 #if defined (JOB_CONTROL)
3028 if (job_control == 0)
3031 set_signal_handler (SIGINT, SIG_IGN);
3032 set_signal_ignored (SIGINT);
3033 set_signal_handler (SIGQUIT, SIG_IGN);
3034 set_signal_ignored (SIGQUIT);
3038 /* Execute a simple command that is hopefully defined in a disk file
3043 3) look up the command
3046 6) If the execve failed, see if the file has executable mode set.
3047 If so, and it isn't a directory, then execute its contents as
3050 Note that the filename hashing stuff has to take place up here,
3051 in the parent. This is probably why the Bourne style shells
3052 don't handle it, since that would require them to go through
3053 this gnarly hair, for no good reason. */
3055 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3056 async, fds_to_close, cmdflags)
3058 REDIRECT *redirects;
3060 int pipe_in, pipe_out, async;
3061 struct fd_bitmap *fds_to_close;
3064 char *pathname, *command, **args;
3068 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3069 pathname = words->word->word;
3071 #if defined (RESTRICTED_SHELL)
3072 if (restricted && strchr (pathname, '/'))
3074 internal_error ("%s: restricted: cannot specify `/' in command names",
3076 last_command_exit_value = EXECUTION_FAILURE;
3079 #endif /* RESTRICTED_SHELL */
3081 command = search_for_command (pathname);
3085 maybe_make_export_env ();
3086 put_command_name_into_env (command);
3089 /* We have to make the child before we check for the non-existence
3090 of COMMAND, since we want the error messages to be redirected. */
3091 /* If we can get away without forking and there are no pipes to deal with,
3092 don't bother to fork, just directly exec the command. */
3093 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3096 pid = make_child (savestring (command_line), async);
3100 int old_interactive;
3103 /* This has been disabled for the time being. */
3104 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3105 if (posixly_correct == 0)
3106 put_gnu_argv_flags_into_env ((int)getpid (), glob_argv_flags);
3110 /* Cancel traps, in trap.c. */
3111 restore_original_signals ();
3113 /* restore_original_signals may have undone the work done
3114 by make_child to ensure that SIGINT and SIGQUIT are ignored
3115 in asynchronous children. */
3118 if ((cmdflags & CMD_STDIN_REDIR) &&
3119 pipe_in == NO_PIPE &&
3120 (stdin_redirects (redirects) == 0))
3121 async_redirect_stdin ();
3122 setup_async_signals ();
3125 /* This functionality is now provided by close-on-exec of the
3126 file descriptors manipulated by redirection and piping.
3127 Some file descriptors still need to be closed in all children
3128 because of the way bash does pipes; fds_to_close is a
3129 bitmap of all such file descriptors. */
3131 close_fd_bitmap (fds_to_close);
3133 do_piping (pipe_in, pipe_out);
3137 old_interactive = interactive;
3141 subshell_environment = SUBSHELL_FORK;
3143 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
3145 #if defined (PROCESS_SUBSTITUTION)
3146 /* Try to remove named pipes that may have been created as the
3147 result of redirections. */
3148 unlink_fifo_list ();
3149 #endif /* PROCESS_SUBSTITUTION */
3150 exit (EXECUTION_FAILURE);
3154 interactive = old_interactive;
3158 internal_error ("%s: command not found", pathname);
3159 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3162 /* Execve expects the command name to be in args[0]. So we
3163 leave it there, in the same format that the user used to
3165 args = word_list_to_argv (words, 0, 0, (int *)NULL);
3166 exit (shell_execve (command, args, export_env));
3170 /* Make sure that the pipes are closed in the parent. */
3171 close_pipes (pipe_in, pipe_out);
3172 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3173 unlink_fifo_list ();
3179 #if !defined (HAVE_HASH_BANG_EXEC)
3180 /* If the operating system on which we're running does not handle
3181 the #! executable format, then help out. SAMPLE is the text read
3182 from the file, SAMPLE_LEN characters. COMMAND is the name of
3183 the script; it and ARGS, the arguments given by the user, will
3184 become arguments to the specified interpreter. ENV is the environment
3185 to pass to the interpreter.
3187 The word immediately following the #! is the interpreter to execute.
3188 A single argument to the interpreter is allowed. */
3190 execute_shell_script (sample, sample_len, command, args, env)
3191 unsigned char *sample;
3197 char *execname, *firstarg;
3198 int start, size_increment, larry;
3200 /* Find the name of the interpreter to exec. */
3201 for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
3205 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
3210 execname = substring ((char *)sample, start, i);
3213 execname = xmalloc (1 + larry);
3214 strncpy (execname, (char *)(sample + start), larry);
3215 execname[larry] = '\0';
3219 /* Now the argument, if any. */
3220 firstarg = (char *)NULL;
3222 whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
3226 /* If there is more text on the line, then it is an argument for the
3228 if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
3231 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
3235 firstarg = substring ((char *)sample, start, i);
3238 firstarg = xmalloc (1 + larry);
3239 strncpy (firstarg, (char *)(sample + start), larry);
3240 firstarg[larry] = '\0';
3246 larry = array_len (args) + size_increment;
3248 args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
3250 for (i = larry - 1; i; i--)
3251 args[i] = args[i - size_increment];
3262 args[larry] = (char *)NULL;
3264 return (shell_execve (execname, args, env));
3266 #endif /* !HAVE_HASH_BANG_EXEC */
3269 initialize_subshell ()
3272 /* Forget about any aliases that we knew of. We are in a subshell. */
3273 delete_all_aliases ();
3276 #if defined (HISTORY)
3277 /* Forget about the history lines we have read. This is a non-interactive
3279 history_lines_this_session = 0;
3282 #if defined (JOB_CONTROL)
3283 /* Forget about the way job control was working. We are in a subshell. */
3284 without_job_control ();
3285 set_sigchld_handler ();
3286 #endif /* JOB_CONTROL */
3288 /* Reset the values of the shell flags and options. */
3289 reset_shell_flags ();
3290 reset_shell_options ();
3291 reset_shopt_options ();
3293 /* If we're not interactive, close the file descriptor from which we're
3294 reading the current shell script. */
3295 if (interactive_shell == 0)
3296 unset_bash_input (1);
3299 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3300 # define SETOSTYPE(x) __setostype(x)
3302 # define SETOSTYPE(x)
3305 /* Call execve (), handling interpreting shell scripts, and handling
3308 shell_execve (command, args, env)
3315 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3316 execve (command, args, env);
3319 /* If we get to this point, then start checking out the file.
3320 Maybe it is something we can hack ourselves. */
3321 if (errno != ENOEXEC)
3324 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3325 internal_error ("%s: is a directory", command);
3329 file_error (command);
3331 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3334 /* This file is executable.
3335 If it begins with #!, then help out people with losing operating
3336 systems. Otherwise, check to see if it is a binary file by seeing
3337 if the first line (or up to 80 characters) are in the ASCII set.
3338 Execute the contents as shell commands. */
3339 fd = open (command, O_RDONLY);
3342 unsigned char sample[80];
3345 sample_len = read (fd, (char *)sample, 80);
3348 if (sample_len == 0)
3349 return (EXECUTION_SUCCESS);
3351 /* Is this supposed to be an executable script?
3352 If so, the format of the line is "#! interpreter [argument]".
3353 A single argument is allowed. The BSD kernel restricts
3354 the length of the entire line to 32 characters (32 bytes
3355 being the size of the BSD exec header), but we allow 80
3359 #if !defined (HAVE_HASH_BANG_EXEC)
3360 if (sample[0] == '#' && sample[1] == '!')
3361 return (execute_shell_script (sample, sample_len, command, args, env));
3364 if (check_binary_file (sample, sample_len))
3366 internal_error ("%s: cannot execute binary file", command);
3367 return (EX_BINARY_FILE);
3372 initialize_subshell ();
3374 set_sigint_handler ();
3376 /* Insert the name of this shell into the argument list. */
3377 larray = array_len (args) + 1;
3378 args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
3380 for (i = larray - 1; i; i--)
3381 args[i] = args[i - 1];
3383 args[0] = shell_name;
3385 args[larray] = (char *)NULL;
3387 if (args[0][0] == '-')
3390 #if defined (RESTRICTED_SHELL)
3392 change_flag ('r', FLAG_OFF);
3397 /* Can't free subshell_argv[0]; that is shell_name. */
3398 for (i = 1; i < subshell_argc; i++)
3399 free (subshell_argv[i]);
3400 free (subshell_argv);
3403 dispose_command (currently_executing_command); /* XXX */
3404 currently_executing_command = (COMMAND *)NULL;
3406 subshell_argc = larray;
3407 subshell_argv = args;
3408 subshell_envp = env;
3410 unbind_args (); /* remove the positional parameters */
3412 longjmp (subshell_top_level, 1);
3416 execute_intern_function (name, function)
3422 if (check_identifier (name, posixly_correct) == 0)
3424 if (posixly_correct && interactive_shell == 0)
3426 last_command_exit_value = EX_USAGE;
3427 jump_to_top_level (EXITPROG);
3429 return (EXECUTION_FAILURE);
3432 var = find_function (name->word);
3433 if (var && readonly_p (var))
3435 internal_error ("%s: readonly function", var->name);
3436 return (EXECUTION_FAILURE);
3439 bind_function (name->word, function);
3440 return (EXECUTION_SUCCESS);
3443 #if defined (INCLUDE_UNUSED)
3444 #if defined (PROCESS_SUBSTITUTION)
3448 register int i, fd_table_size;
3450 fd_table_size = getdtablesize ();
3451 if (fd_table_size > 256) /* clamp to a reasonable value */
3452 fd_table_size = 256;
3454 for (i = 3; i < fd_table_size; i++)
3457 #endif /* PROCESS_SUBSTITUTION */
3461 close_pipes (in, out)
3470 /* Redirect input and output to be from and to the specified pipes.
3471 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3473 do_piping (pipe_in, pipe_out)
3474 int pipe_in, pipe_out;
3476 if (pipe_in != NO_PIPE)
3478 if (dup2 (pipe_in, 0) < 0)
3479 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
3483 if (pipe_out != NO_PIPE)
3485 if (pipe_out != REDIRECT_BOTH)
3487 if (dup2 (pipe_out, 1) < 0)
3488 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
3489 if (pipe_out == 0 || pipe_out > 1)
3494 if (dup2 (1, 2) < 0)
3495 sys_error ("cannot duplicate fd 1 to fd 2");