Patch-ID: bash41-010
[bash.git] / execute_cmd.c
blobe65a03f129df0157d8d65f0fb7fc0a44306d8f52
1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2009 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
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #pragma alloca
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
27 #include <stdio.h>
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 # include <sys/file.h>
32 #endif
33 #include "filecntl.h"
34 #include "posixstat.h"
35 #include <signal.h>
36 #ifndef _MINIX
37 # include <sys/param.h>
38 #endif
40 #if defined (HAVE_UNISTD_H)
41 # include <unistd.h>
42 #endif
44 #include "posixtime.h"
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 # include <sys/resource.h>
48 #endif
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 # include <sys/times.h>
52 #endif
54 #include <errno.h>
56 #if !defined (errno)
57 extern int errno;
58 #endif
60 #define NEED_FPURGE_DECL
62 #include "bashansi.h"
63 #include "bashintl.h"
65 #include "memalloc.h"
66 #include "shell.h"
67 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
68 #include "flags.h"
69 #include "builtins.h"
70 #include "hashlib.h"
71 #include "jobs.h"
72 #include "execute_cmd.h"
73 #include "findcmd.h"
74 #include "redir.h"
75 #include "trap.h"
76 #include "pathexp.h"
77 #include "hashcmd.h"
79 #if defined (COND_COMMAND)
80 # include "test.h"
81 #endif
83 #include "builtins/common.h"
84 #include "builtins/builtext.h" /* list of builtins */
86 #include <glob/strmatch.h>
87 #include <tilde/tilde.h>
89 #if defined (BUFFERED_INPUT)
90 # include "input.h"
91 #endif
93 #if defined (ALIAS)
94 # include "alias.h"
95 #endif
97 #if defined (HISTORY)
98 # include "bashhist.h"
99 #endif
101 extern int posixly_correct;
102 extern int expand_aliases;
103 extern int autocd;
104 extern int breaking, continuing, loop_level;
105 extern int parse_and_execute_level, running_trap, sourcelevel;
106 extern int command_string_index, line_number;
107 extern int dot_found_in_search;
108 extern int already_making_children;
109 extern int tempenv_assign_error;
110 extern char *the_printed_command, *shell_name;
111 extern pid_t last_command_subst_pid;
112 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
113 extern char **subshell_argv, **subshell_envp;
114 extern int subshell_argc;
115 #if 0
116 extern char *glob_argv_flags;
117 #endif
119 extern int close __P((int));
121 /* Static functions defined and used in this file. */
122 static void close_pipes __P((int, int));
123 static void do_piping __P((int, int));
124 static void bind_lastarg __P((char *));
125 static int shell_control_structure __P((enum command_type));
126 static void cleanup_redirects __P((REDIRECT *));
128 #if defined (JOB_CONTROL)
129 static int restore_signal_mask __P((sigset_t *));
130 #endif
132 static void async_redirect_stdin __P((void));
134 static int builtin_status __P((int));
136 static int execute_for_command __P((FOR_COM *));
137 #if defined (SELECT_COMMAND)
138 static int print_index_and_element __P((int, int, WORD_LIST *));
139 static void indent __P((int, int));
140 static void print_select_list __P((WORD_LIST *, int, int, int));
141 static char *select_query __P((WORD_LIST *, int, char *, int));
142 static int execute_select_command __P((SELECT_COM *));
143 #endif
144 #if defined (DPAREN_ARITHMETIC)
145 static int execute_arith_command __P((ARITH_COM *));
146 #endif
147 #if defined (COND_COMMAND)
148 static int execute_cond_node __P((COND_COM *));
149 static int execute_cond_command __P((COND_COM *));
150 #endif
151 #if defined (COMMAND_TIMING)
152 static int mkfmt __P((char *, int, int, time_t, int));
153 static void print_formatted_time __P((FILE *, char *,
154 time_t, int, time_t, int,
155 time_t, int, int));
156 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
157 #endif
158 #if defined (ARITH_FOR_COMMAND)
159 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
160 static int execute_arith_for_command __P((ARITH_FOR_COM *));
161 #endif
162 static int execute_case_command __P((CASE_COM *));
163 static int execute_while_command __P((WHILE_COM *));
164 static int execute_until_command __P((WHILE_COM *));
165 static int execute_while_or_until __P((WHILE_COM *, int));
166 static int execute_if_command __P((IF_COM *));
167 static int execute_null_command __P((REDIRECT *, int, int, int));
168 static void fix_assignment_words __P((WORD_LIST *));
169 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
170 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
171 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
172 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
173 SHELL_VAR *,
174 REDIRECT *, struct fd_bitmap *, int));
175 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
176 sh_builtin_func_t *,
177 SHELL_VAR *,
178 int, int, int,
179 struct fd_bitmap *,
180 int));
181 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
182 int, int, int, struct fd_bitmap *, int));
184 static char *getinterp __P((char *, int, int *));
185 static void initialize_subshell __P((void));
186 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
187 #if defined (COPROCESS_SUPPORT)
188 static int execute_coproc __P((COMMAND *, int, int, struct fd_bitmap *));
189 #endif
191 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
193 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
195 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
197 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
198 so that reader_loop can set it to zero before executing a command. */
199 int stdin_redir;
201 /* The name of the command that is currently being executed.
202 `test' needs this, for example. */
203 char *this_command_name;
205 /* The printed representation of the currently-executing command (same as
206 the_printed_command), except when a trap is being executed. Useful for
207 a debugger to know where exactly the program is currently executing. */
208 char *the_printed_command_except_trap;
210 /* For catching RETURN in a function. */
211 int return_catch_flag;
212 int return_catch_value;
213 procenv_t return_catch;
215 /* The value returned by the last synchronous command. */
216 int last_command_exit_value;
218 /* Whether or not the last command (corresponding to last_command_exit_value)
219 was terminated by a signal, and, if so, which one. */
220 int last_command_exit_signal;
222 /* The list of redirections to perform which will undo the redirections
223 that I made in the shell. */
224 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
226 /* The list of redirections to perform which will undo the internal
227 redirections performed by the `exec' builtin. These are redirections
228 that must be undone even when exec discards redirection_undo_list. */
229 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
231 /* When greater than zero, value is the `level' of builtins we are
232 currently executing (e.g. `eval echo a' would have it set to 2). */
233 int executing_builtin = 0;
235 /* Non-zero if we are executing a command list (a;b;c, etc.) */
236 int executing_list = 0;
238 /* Non-zero if failing commands in a command substitution should not exit the
239 shell even if -e is set. Used to pass the CMD_IGNORE_RETURN flag down to
240 commands run in command substitutions by parse_and_execute. */
241 int comsub_ignore_return = 0;
243 /* Non-zero if we have just forked and are currently running in a subshell
244 environment. */
245 int subshell_environment;
247 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
248 int subshell_level = 0;
250 /* Currently-executing shell function. */
251 SHELL_VAR *this_shell_function;
253 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
254 int match_ignore_case = 0;
256 struct stat SB; /* used for debugging */
258 static int special_builtin_failed;
260 static COMMAND *currently_executing_command;
262 /* The line number that the currently executing function starts on. */
263 static int function_line_number;
265 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
266 number containing the function name. Used by executing_line_number to
267 report the correct line number. Kind of a hack. */
268 static int showing_function_line;
270 static int line_number_for_err_trap;
272 /* A sort of function nesting level counter */
273 static int funcnest = 0;
274 int funcnest_max = 0; /* XXX - for bash-4.2 */
276 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
278 #define FD_BITMAP_DEFAULT_SIZE 32
280 /* Functions to allocate and deallocate the structures used to pass
281 information from the shell to its children about file descriptors
282 to close. */
283 struct fd_bitmap *
284 new_fd_bitmap (size)
285 int size;
287 struct fd_bitmap *ret;
289 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
291 ret->size = size;
293 if (size)
295 ret->bitmap = (char *)xmalloc (size);
296 memset (ret->bitmap, '\0', size);
298 else
299 ret->bitmap = (char *)NULL;
300 return (ret);
303 void
304 dispose_fd_bitmap (fdbp)
305 struct fd_bitmap *fdbp;
307 FREE (fdbp->bitmap);
308 free (fdbp);
311 void
312 close_fd_bitmap (fdbp)
313 struct fd_bitmap *fdbp;
315 register int i;
317 if (fdbp)
319 for (i = 0; i < fdbp->size; i++)
320 if (fdbp->bitmap[i])
322 close (i);
323 fdbp->bitmap[i] = 0;
328 /* Return the line number of the currently executing command. */
330 executing_line_number ()
332 if (executing && showing_function_line == 0 &&
333 (variable_context == 0 || interactive_shell == 0) &&
334 currently_executing_command)
336 #if defined (COND_COMMAND)
337 if (currently_executing_command->type == cm_cond)
338 return currently_executing_command->value.Cond->line;
339 #endif
340 #if defined (DPAREN_ARITHMETIC)
341 else if (currently_executing_command->type == cm_arith)
342 return currently_executing_command->value.Arith->line;
343 #endif
344 #if defined (ARITH_FOR_COMMAND)
345 else if (currently_executing_command->type == cm_arith_for)
346 return currently_executing_command->value.ArithFor->line;
347 #endif
349 return line_number;
351 else
352 return line_number;
355 /* Execute the command passed in COMMAND. COMMAND is exactly what
356 read_command () places into GLOBAL_COMMAND. See "command.h" for the
357 details of the command structure.
359 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
360 return values. Executing a command with nothing in it returns
361 EXECUTION_SUCCESS. */
363 execute_command (command)
364 COMMAND *command;
366 struct fd_bitmap *bitmap;
367 int result;
369 current_fds_to_close = (struct fd_bitmap *)NULL;
370 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
371 begin_unwind_frame ("execute-command");
372 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
374 /* Just do the command, but not asynchronously. */
375 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
377 dispose_fd_bitmap (bitmap);
378 discard_unwind_frame ("execute-command");
380 #if defined (PROCESS_SUBSTITUTION)
381 /* don't unlink fifos if we're in a shell function; wait until the function
382 returns. */
383 if (variable_context == 0)
384 unlink_fifo_list ();
385 #endif /* PROCESS_SUBSTITUTION */
387 QUIT;
388 return (result);
391 /* Return 1 if TYPE is a shell control structure type. */
392 static int
393 shell_control_structure (type)
394 enum command_type type;
396 switch (type)
398 #if defined (ARITH_FOR_COMMAND)
399 case cm_arith_for:
400 #endif
401 #if defined (SELECT_COMMAND)
402 case cm_select:
403 #endif
404 #if defined (DPAREN_ARITHMETIC)
405 case cm_arith:
406 #endif
407 #if defined (COND_COMMAND)
408 case cm_cond:
409 #endif
410 case cm_case:
411 case cm_while:
412 case cm_until:
413 case cm_if:
414 case cm_for:
415 case cm_group:
416 case cm_function_def:
417 return (1);
419 default:
420 return (0);
424 /* A function to use to unwind_protect the redirection undo list
425 for loops. */
426 static void
427 cleanup_redirects (list)
428 REDIRECT *list;
430 do_redirections (list, RX_ACTIVE);
431 dispose_redirects (list);
434 #if 0
435 /* Function to unwind_protect the redirections for functions and builtins. */
436 static void
437 cleanup_func_redirects (list)
438 REDIRECT *list;
440 do_redirections (list, RX_ACTIVE);
442 #endif
444 void
445 dispose_exec_redirects ()
447 if (exec_redirection_undo_list)
449 dispose_redirects (exec_redirection_undo_list);
450 exec_redirection_undo_list = (REDIRECT *)NULL;
454 #if defined (JOB_CONTROL)
455 /* A function to restore the signal mask to its proper value when the shell
456 is interrupted or errors occur while creating a pipeline. */
457 static int
458 restore_signal_mask (set)
459 sigset_t *set;
461 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
463 #endif /* JOB_CONTROL */
465 #ifdef DEBUG
466 /* A debugging function that can be called from gdb, for instance. */
467 void
468 open_files ()
470 register int i;
471 int f, fd_table_size;
473 fd_table_size = getdtablesize ();
475 fprintf (stderr, "pid %ld open files:", (long)getpid ());
476 for (i = 3; i < fd_table_size; i++)
478 if ((f = fcntl (i, F_GETFD, 0)) != -1)
479 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
481 fprintf (stderr, "\n");
483 #endif
485 static void
486 async_redirect_stdin ()
488 int fd;
490 fd = open ("/dev/null", O_RDONLY);
491 if (fd > 0)
493 dup2 (fd, 0);
494 close (fd);
496 else if (fd < 0)
497 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
500 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
502 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
503 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
504 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
505 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
506 from and where it goes. They can have the value of NO_PIPE, which means
507 I/O is stdin/stdout.
508 FDS_TO_CLOSE is a list of file descriptors to close once the child has
509 been forked. This list often contains the unusable sides of pipes, etc.
511 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
512 return values. Executing a command with nothing in it returns
513 EXECUTION_SUCCESS. */
515 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
516 fds_to_close)
517 COMMAND *command;
518 int asynchronous;
519 int pipe_in, pipe_out;
520 struct fd_bitmap *fds_to_close;
522 int exec_result, user_subshell, invert, ignore_return, was_error_trap;
523 REDIRECT *my_undo_list, *exec_undo_list;
524 volatile int last_pid;
525 volatile int save_line_number;
527 #if 0
528 if (command == 0 || breaking || continuing || read_but_dont_execute)
529 return (EXECUTION_SUCCESS);
530 #else
531 if (breaking || continuing)
532 return (last_command_exit_value);
533 if (command == 0 || read_but_dont_execute)
534 return (EXECUTION_SUCCESS);
535 #endif
537 QUIT;
538 run_pending_traps ();
540 #if 0
541 if (running_trap == 0)
542 #endif
543 currently_executing_command = command;
545 invert = (command->flags & CMD_INVERT_RETURN) != 0;
547 /* If we're inverting the return value and `set -e' has been executed,
548 we don't want a failing command to inadvertently cause the shell
549 to exit. */
550 if (exit_immediately_on_error && invert) /* XXX */
551 command->flags |= CMD_IGNORE_RETURN; /* XXX */
553 exec_result = EXECUTION_SUCCESS;
555 /* If a command was being explicitly run in a subshell, or if it is
556 a shell control-structure, and it has a pipe, then we do the command
557 in a subshell. */
558 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
559 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
561 #if defined (COPROCESS_SUPPORT)
562 if (command->type == cm_coproc)
563 return (execute_coproc (command, pipe_in, pipe_out, fds_to_close));
564 #endif
566 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
568 if (command->type == cm_subshell ||
569 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
570 (shell_control_structure (command->type) &&
571 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
573 pid_t paren_pid;
575 /* Fork a subshell, turn off the subshell bit, turn off job
576 control and call execute_command () on the command again. */
577 line_number_for_err_trap = line_number;
578 paren_pid = make_child (savestring (make_command_string (command)),
579 asynchronous);
580 if (paren_pid == 0)
581 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
582 /* NOTREACHED */
583 else
585 close_pipes (pipe_in, pipe_out);
587 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
588 unlink_fifo_list ();
589 #endif
590 /* If we are part of a pipeline, and not the end of the pipeline,
591 then we should simply return and let the last command in the
592 pipe be waited for. If we are not in a pipeline, or are the
593 last command in the pipeline, then we wait for the subshell
594 and return its exit status as usual. */
595 if (pipe_out != NO_PIPE)
596 return (EXECUTION_SUCCESS);
598 stop_pipeline (asynchronous, (COMMAND *)NULL);
600 if (asynchronous == 0)
602 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
603 invert = (command->flags & CMD_INVERT_RETURN) != 0;
604 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
606 last_command_exit_value = wait_for (paren_pid);
608 /* If we have to, invert the return value. */
609 if (invert)
610 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
611 ? EXECUTION_FAILURE
612 : EXECUTION_SUCCESS);
613 else
614 exec_result = last_command_exit_value;
616 if (user_subshell && was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
618 last_command_exit_value = exec_result;
619 save_line_number = line_number;
620 line_number = line_number_for_err_trap;
621 run_error_trap ();
622 line_number = save_line_number;
625 if (user_subshell && ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
627 last_command_exit_value = exec_result;
628 run_pending_traps ();
629 jump_to_top_level (ERREXIT);
632 return (last_command_exit_value = exec_result);
634 else
636 DESCRIBE_PID (paren_pid);
638 run_pending_traps ();
640 return (EXECUTION_SUCCESS);
645 #if defined (COMMAND_TIMING)
646 if (command->flags & CMD_TIME_PIPELINE)
648 if (asynchronous)
650 command->flags |= CMD_FORCE_SUBSHELL;
651 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
653 else
655 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
656 #if 0
657 if (running_trap == 0)
658 #endif
659 currently_executing_command = (COMMAND *)NULL;
661 return (exec_result);
663 #endif /* COMMAND_TIMING */
665 if (shell_control_structure (command->type) && command->redirects)
666 stdin_redir = stdin_redirects (command->redirects);
668 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
669 redirection.) */
670 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
672 cleanup_redirects (redirection_undo_list);
673 redirection_undo_list = (REDIRECT *)NULL;
674 dispose_exec_redirects ();
675 return (last_command_exit_value = EXECUTION_FAILURE);
678 if (redirection_undo_list)
680 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
681 dispose_redirects (redirection_undo_list);
682 redirection_undo_list = (REDIRECT *)NULL;
684 else
685 my_undo_list = (REDIRECT *)NULL;
687 if (exec_redirection_undo_list)
689 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
690 dispose_redirects (exec_redirection_undo_list);
691 exec_redirection_undo_list = (REDIRECT *)NULL;
693 else
694 exec_undo_list = (REDIRECT *)NULL;
696 if (my_undo_list || exec_undo_list)
697 begin_unwind_frame ("loop_redirections");
699 if (my_undo_list)
700 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
702 if (exec_undo_list)
703 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
705 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
707 QUIT;
709 switch (command->type)
711 case cm_simple:
713 save_line_number = line_number;
714 /* We can't rely on variables retaining their values across a
715 call to execute_simple_command if a longjmp occurs as the
716 result of a `return' builtin. This is true for sure with gcc. */
717 #if defined (RECYCLES_PIDS)
718 last_made_pid = NO_PID;
719 #endif
720 last_pid = last_made_pid;
721 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
723 if (ignore_return && command->value.Simple)
724 command->value.Simple->flags |= CMD_IGNORE_RETURN;
725 if (command->flags & CMD_STDIN_REDIR)
726 command->value.Simple->flags |= CMD_STDIN_REDIR;
728 line_number_for_err_trap = line_number = command->value.Simple->line;
729 exec_result =
730 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
731 asynchronous, fds_to_close);
732 line_number = save_line_number;
734 /* The temporary environment should be used for only the simple
735 command immediately following its definition. */
736 dispose_used_env_vars ();
738 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
739 /* Reclaim memory allocated with alloca () on machines which
740 may be using the alloca emulation code. */
741 (void) alloca (0);
742 #endif /* (ultrix && mips) || C_ALLOCA */
744 /* If we forked to do the command, then we must wait_for ()
745 the child. */
747 /* XXX - this is something to watch out for if there are problems
748 when the shell is compiled without job control. */
749 if (already_making_children && pipe_out == NO_PIPE &&
750 last_made_pid != last_pid)
752 stop_pipeline (asynchronous, (COMMAND *)NULL);
754 if (asynchronous)
756 DESCRIBE_PID (last_made_pid);
758 else
759 #if !defined (JOB_CONTROL)
760 /* Do not wait for asynchronous processes started from
761 startup files. */
762 if (last_made_pid != last_asynchronous_pid)
763 #endif
764 /* When executing a shell function that executes other
765 commands, this causes the last simple command in
766 the function to be waited for twice. This also causes
767 subshells forked to execute builtin commands (e.g., in
768 pipelines) to be waited for twice. */
769 exec_result = wait_for (last_made_pid);
773 /* 2009/02/13 -- pipeline failure is processed elsewhere. This handles
774 only the failure of a simple command. */
775 if (was_error_trap && ignore_return == 0 && invert == 0 && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)
777 last_command_exit_value = exec_result;
778 line_number = line_number_for_err_trap;
779 run_error_trap ();
780 line_number = save_line_number;
783 if (ignore_return == 0 && invert == 0 &&
784 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
785 (exit_immediately_on_error && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)))
787 last_command_exit_value = exec_result;
788 run_pending_traps ();
789 jump_to_top_level (ERREXIT);
792 break;
794 case cm_for:
795 if (ignore_return)
796 command->value.For->flags |= CMD_IGNORE_RETURN;
797 exec_result = execute_for_command (command->value.For);
798 break;
800 #if defined (ARITH_FOR_COMMAND)
801 case cm_arith_for:
802 if (ignore_return)
803 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
804 exec_result = execute_arith_for_command (command->value.ArithFor);
805 break;
806 #endif
808 #if defined (SELECT_COMMAND)
809 case cm_select:
810 if (ignore_return)
811 command->value.Select->flags |= CMD_IGNORE_RETURN;
812 exec_result = execute_select_command (command->value.Select);
813 break;
814 #endif
816 case cm_case:
817 if (ignore_return)
818 command->value.Case->flags |= CMD_IGNORE_RETURN;
819 exec_result = execute_case_command (command->value.Case);
820 break;
822 case cm_while:
823 if (ignore_return)
824 command->value.While->flags |= CMD_IGNORE_RETURN;
825 exec_result = execute_while_command (command->value.While);
826 break;
828 case cm_until:
829 if (ignore_return)
830 command->value.While->flags |= CMD_IGNORE_RETURN;
831 exec_result = execute_until_command (command->value.While);
832 break;
834 case cm_if:
835 if (ignore_return)
836 command->value.If->flags |= CMD_IGNORE_RETURN;
837 exec_result = execute_if_command (command->value.If);
838 break;
840 case cm_group:
842 /* This code can be executed from either of two paths: an explicit
843 '{}' command, or via a function call. If we are executed via a
844 function call, we have already taken care of the function being
845 executed in the background (down there in execute_simple_command ()),
846 and this command should *not* be marked as asynchronous. If we
847 are executing a regular '{}' group command, and asynchronous == 1,
848 we must want to execute the whole command in the background, so we
849 need a subshell, and we want the stuff executed in that subshell
850 (this group command) to be executed in the foreground of that
851 subshell (i.e. there will not be *another* subshell forked).
853 What we do is to force a subshell if asynchronous, and then call
854 execute_command_internal again with asynchronous still set to 1,
855 but with the original group command, so the printed command will
856 look right.
858 The code above that handles forking off subshells will note that
859 both subshell and async are on, and turn off async in the child
860 after forking the subshell (but leave async set in the parent, so
861 the normal call to describe_pid is made). This turning off
862 async is *crucial*; if it is not done, this will fall into an
863 infinite loop of executions through this spot in subshell after
864 subshell until the process limit is exhausted. */
866 if (asynchronous)
868 command->flags |= CMD_FORCE_SUBSHELL;
869 exec_result =
870 execute_command_internal (command, 1, pipe_in, pipe_out,
871 fds_to_close);
873 else
875 if (ignore_return && command->value.Group->command)
876 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
877 exec_result =
878 execute_command_internal (command->value.Group->command,
879 asynchronous, pipe_in, pipe_out,
880 fds_to_close);
882 break;
884 case cm_connection:
885 exec_result = execute_connection (command, asynchronous,
886 pipe_in, pipe_out, fds_to_close);
887 break;
889 #if defined (DPAREN_ARITHMETIC)
890 case cm_arith:
891 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
892 if (ignore_return)
893 command->value.Arith->flags |= CMD_IGNORE_RETURN;
894 line_number_for_err_trap = save_line_number = line_number;
895 exec_result = execute_arith_command (command->value.Arith);
896 line_number = save_line_number;
898 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
900 last_command_exit_value = exec_result;
901 save_line_number = line_number;
902 line_number = line_number_for_err_trap;
903 run_error_trap ();
904 line_number = save_line_number;
907 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
909 last_command_exit_value = exec_result;
910 run_pending_traps ();
911 jump_to_top_level (ERREXIT);
914 break;
915 #endif
917 #if defined (COND_COMMAND)
918 case cm_cond:
919 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
920 if (ignore_return)
921 command->value.Cond->flags |= CMD_IGNORE_RETURN;
923 line_number_for_err_trap = save_line_number = line_number;
924 exec_result = execute_cond_command (command->value.Cond);
925 line_number = save_line_number;
927 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
929 last_command_exit_value = exec_result;
930 save_line_number = line_number;
931 line_number = line_number_for_err_trap;
932 run_error_trap ();
933 line_number = save_line_number;
936 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
938 last_command_exit_value = exec_result;
939 run_pending_traps ();
940 jump_to_top_level (ERREXIT);
943 break;
944 #endif
946 case cm_function_def:
947 exec_result = execute_intern_function (command->value.Function_def->name,
948 command->value.Function_def->command);
949 break;
951 default:
952 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
955 if (my_undo_list)
957 do_redirections (my_undo_list, RX_ACTIVE);
958 dispose_redirects (my_undo_list);
961 if (exec_undo_list)
962 dispose_redirects (exec_undo_list);
964 if (my_undo_list || exec_undo_list)
965 discard_unwind_frame ("loop_redirections");
967 /* Invert the return value if we have to */
968 if (invert)
969 exec_result = (exec_result == EXECUTION_SUCCESS)
970 ? EXECUTION_FAILURE
971 : EXECUTION_SUCCESS;
973 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
974 /* This is where we set PIPESTATUS from the exit status of the appropriate
975 compound commands (the ones that look enough like simple commands to
976 cause confusion). We might be able to optimize by not doing this if
977 subshell_environment != 0. */
978 switch (command->type)
980 # if defined (DPAREN_ARITHMETIC)
981 case cm_arith:
982 # endif
983 # if defined (COND_COMMAND)
984 case cm_cond:
985 # endif
986 set_pipestatus_from_exit (exec_result);
987 break;
989 #endif
991 last_command_exit_value = exec_result;
992 run_pending_traps ();
993 #if 0
994 if (running_trap == 0)
995 #endif
996 currently_executing_command = (COMMAND *)NULL;
997 return (last_command_exit_value);
1000 #if defined (COMMAND_TIMING)
1002 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1003 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
1004 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
1005 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
1006 #endif
1008 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1009 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1011 static const int precs[] = { 0, 100, 10, 1 };
1013 /* Expand one `%'-prefixed escape sequence from a time format string. */
1014 static int
1015 mkfmt (buf, prec, lng, sec, sec_fraction)
1016 char *buf;
1017 int prec, lng;
1018 time_t sec;
1019 int sec_fraction;
1021 time_t min;
1022 char abuf[INT_STRLEN_BOUND(time_t) + 1];
1023 int ind, aind;
1025 ind = 0;
1026 abuf[sizeof(abuf) - 1] = '\0';
1028 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1029 if (lng)
1031 min = sec / 60;
1032 sec %= 60;
1033 aind = sizeof(abuf) - 2;
1035 abuf[aind--] = (min % 10) + '0';
1036 while (min /= 10);
1037 aind++;
1038 while (abuf[aind])
1039 buf[ind++] = abuf[aind++];
1040 buf[ind++] = 'm';
1043 /* Now add the seconds. */
1044 aind = sizeof (abuf) - 2;
1046 abuf[aind--] = (sec % 10) + '0';
1047 while (sec /= 10);
1048 aind++;
1049 while (abuf[aind])
1050 buf[ind++] = abuf[aind++];
1052 /* We want to add a decimal point and PREC places after it if PREC is
1053 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1054 and 999. */
1055 if (prec != 0)
1057 buf[ind++] = '.';
1058 for (aind = 1; aind <= prec; aind++)
1060 buf[ind++] = (sec_fraction / precs[aind]) + '0';
1061 sec_fraction %= precs[aind];
1065 if (lng)
1066 buf[ind++] = 's';
1067 buf[ind] = '\0';
1069 return (ind);
1072 /* Interpret the format string FORMAT, interpolating the following escape
1073 sequences:
1074 %[prec][l][RUS]
1076 where the optional `prec' is a precision, meaning the number of
1077 characters after the decimal point, the optional `l' means to format
1078 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1079 and the last character is one of
1081 R number of seconds of `real' time
1082 U number of seconds of `user' time
1083 S number of seconds of `system' time
1085 An occurrence of `%%' in the format string is translated to a `%'. The
1086 result is printed to FP, a pointer to a FILE. The other variables are
1087 the seconds and thousandths of a second of real, user, and system time,
1088 resectively. */
1089 static void
1090 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1091 FILE *fp;
1092 char *format;
1093 time_t rs;
1094 int rsf;
1095 time_t us;
1096 int usf;
1097 time_t ss;
1098 int ssf, cpu;
1100 int prec, lng, len;
1101 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1102 time_t sum;
1103 int sum_frac;
1104 int sindex, ssize;
1106 len = strlen (format);
1107 ssize = (len + 64) - (len % 64);
1108 str = (char *)xmalloc (ssize);
1109 sindex = 0;
1111 for (s = format; *s; s++)
1113 if (*s != '%' || s[1] == '\0')
1115 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1116 str[sindex++] = *s;
1118 else if (s[1] == '%')
1120 s++;
1121 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1122 str[sindex++] = *s;
1124 else if (s[1] == 'P')
1126 s++;
1127 #if 0
1128 /* clamp CPU usage at 100% */
1129 if (cpu > 10000)
1130 cpu = 10000;
1131 #endif
1132 sum = cpu / 100;
1133 sum_frac = (cpu % 100) * 10;
1134 len = mkfmt (ts, 2, 0, sum, sum_frac);
1135 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1136 strcpy (str + sindex, ts);
1137 sindex += len;
1139 else
1141 prec = 3; /* default is three places past the decimal point. */
1142 lng = 0; /* default is to not use minutes or append `s' */
1143 s++;
1144 if (DIGIT (*s)) /* `precision' */
1146 prec = *s++ - '0';
1147 if (prec > 3) prec = 3;
1149 if (*s == 'l') /* `length extender' */
1151 lng = 1;
1152 s++;
1154 if (*s == 'R' || *s == 'E')
1155 len = mkfmt (ts, prec, lng, rs, rsf);
1156 else if (*s == 'U')
1157 len = mkfmt (ts, prec, lng, us, usf);
1158 else if (*s == 'S')
1159 len = mkfmt (ts, prec, lng, ss, ssf);
1160 else
1162 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1163 free (str);
1164 return;
1166 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1167 strcpy (str + sindex, ts);
1168 sindex += len;
1172 str[sindex] = '\0';
1173 fprintf (fp, "%s\n", str);
1174 fflush (fp);
1176 free (str);
1179 static int
1180 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1181 COMMAND *command;
1182 int asynchronous, pipe_in, pipe_out;
1183 struct fd_bitmap *fds_to_close;
1185 int rv, posix_time, old_flags;
1186 time_t rs, us, ss;
1187 int rsf, usf, ssf;
1188 int cpu;
1189 char *time_format;
1191 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1192 struct timeval real, user, sys;
1193 struct timeval before, after;
1194 # if defined (HAVE_STRUCT_TIMEZONE)
1195 struct timezone dtz; /* posix doesn't define this */
1196 # endif
1197 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1198 #else
1199 # if defined (HAVE_TIMES)
1200 clock_t tbefore, tafter, real, user, sys;
1201 struct tms before, after;
1202 # endif
1203 #endif
1205 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1206 # if defined (HAVE_STRUCT_TIMEZONE)
1207 gettimeofday (&before, &dtz);
1208 # else
1209 gettimeofday (&before, (void *)NULL);
1210 # endif /* !HAVE_STRUCT_TIMEZONE */
1211 getrusage (RUSAGE_SELF, &selfb);
1212 getrusage (RUSAGE_CHILDREN, &kidsb);
1213 #else
1214 # if defined (HAVE_TIMES)
1215 tbefore = times (&before);
1216 # endif
1217 #endif
1219 posix_time = (command->flags & CMD_TIME_POSIX);
1221 old_flags = command->flags;
1222 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1223 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1224 command->flags = old_flags;
1226 rs = us = ss = 0;
1227 rsf = usf = ssf = cpu = 0;
1229 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1230 # if defined (HAVE_STRUCT_TIMEZONE)
1231 gettimeofday (&after, &dtz);
1232 # else
1233 gettimeofday (&after, (void *)NULL);
1234 # endif /* !HAVE_STRUCT_TIMEZONE */
1235 getrusage (RUSAGE_SELF, &selfa);
1236 getrusage (RUSAGE_CHILDREN, &kidsa);
1238 difftimeval (&real, &before, &after);
1239 timeval_to_secs (&real, &rs, &rsf);
1241 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1242 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1243 timeval_to_secs (&user, &us, &usf);
1245 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1246 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1247 timeval_to_secs (&sys, &ss, &ssf);
1249 cpu = timeval_to_cpu (&real, &user, &sys);
1250 #else
1251 # if defined (HAVE_TIMES)
1252 tafter = times (&after);
1254 real = tafter - tbefore;
1255 clock_t_to_secs (real, &rs, &rsf);
1257 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1258 clock_t_to_secs (user, &us, &usf);
1260 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1261 clock_t_to_secs (sys, &ss, &ssf);
1263 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1265 # else
1266 rs = us = ss = 0;
1267 rsf = usf = ssf = cpu = 0;
1268 # endif
1269 #endif
1271 if (posix_time)
1272 time_format = POSIX_TIMEFORMAT;
1273 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1274 time_format = BASH_TIMEFORMAT;
1276 if (time_format && *time_format)
1277 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1279 return rv;
1281 #endif /* COMMAND_TIMING */
1283 /* Execute a command that's supposed to be in a subshell. This must be
1284 called after make_child and we must be running in the child process.
1285 The caller will return or exit() immediately with the value this returns. */
1286 static int
1287 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1288 COMMAND *command;
1289 int asynchronous;
1290 int pipe_in, pipe_out;
1291 struct fd_bitmap *fds_to_close;
1293 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1294 int ois, user_coproc;
1295 int result;
1296 COMMAND *tcom;
1298 USE_VAR(user_subshell);
1299 USE_VAR(user_coproc);
1300 USE_VAR(invert);
1301 USE_VAR(tcom);
1302 USE_VAR(asynchronous);
1304 subshell_level++;
1305 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1306 pipe_in == NO_PIPE &&
1307 stdin_redirects (command->redirects) == 0);
1309 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1310 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1311 user_coproc = command->type == cm_coproc;
1313 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1315 /* If a command is asynchronous in a subshell (like ( foo ) & or
1316 the special case of an asynchronous GROUP command where the
1317 the subshell bit is turned on down in case cm_group: below),
1318 turn off `asynchronous', so that two subshells aren't spawned.
1319 XXX - asynchronous used to be set to 0 in this block, but that
1320 means that setup_async_signals was never run. Now it's set to
1321 0 after subshell_environment is set appropriately and setup_async_signals
1322 is run.
1324 This seems semantically correct to me. For example,
1325 ( foo ) & seems to say ``do the command `foo' in a subshell
1326 environment, but don't wait for that subshell to finish'',
1327 and "{ foo ; bar ; } &" seems to me to be like functions or
1328 builtins in the background, which executed in a subshell
1329 environment. I just don't see the need to fork two subshells. */
1331 /* Don't fork again, we are already in a subshell. A `doubly
1332 async' shell is not interactive, however. */
1333 if (asynchronous)
1335 #if defined (JOB_CONTROL)
1336 /* If a construct like ( exec xxx yyy ) & is given while job
1337 control is active, we want to prevent exec from putting the
1338 subshell back into the original process group, carefully
1339 undoing all the work we just did in make_child. */
1340 original_pgrp = -1;
1341 #endif /* JOB_CONTROL */
1342 ois = interactive_shell;
1343 interactive_shell = 0;
1344 /* This test is to prevent alias expansion by interactive shells that
1345 run `(command) &' but to allow scripts that have enabled alias
1346 expansion with `shopt -s expand_alias' to continue to expand
1347 aliases. */
1348 if (ois != interactive_shell)
1349 expand_aliases = 0;
1352 /* Subshells are neither login nor interactive. */
1353 login_shell = interactive = 0;
1355 if (user_subshell)
1356 subshell_environment = SUBSHELL_PAREN;
1357 else
1359 subshell_environment = 0; /* XXX */
1360 if (asynchronous)
1361 subshell_environment |= SUBSHELL_ASYNC;
1362 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1363 subshell_environment |= SUBSHELL_PIPE;
1364 if (user_coproc)
1365 subshell_environment |= SUBSHELL_COPROC;
1368 reset_terminating_signals (); /* in sig.c */
1369 /* Cancel traps, in trap.c. */
1370 restore_original_signals ();
1372 /* Make sure restore_original_signals doesn't undo the work done by
1373 make_child to ensure that asynchronous children are immune to SIGINT
1374 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1375 not spawned. */
1376 if (asynchronous)
1378 setup_async_signals ();
1379 asynchronous = 0;
1382 #if defined (JOB_CONTROL)
1383 set_sigchld_handler ();
1384 #endif /* JOB_CONTROL */
1386 set_sigint_handler ();
1388 #if defined (JOB_CONTROL)
1389 /* Delete all traces that there were any jobs running. This is
1390 only for subshells. */
1391 without_job_control ();
1392 #endif /* JOB_CONTROL */
1394 if (fds_to_close)
1395 close_fd_bitmap (fds_to_close);
1397 do_piping (pipe_in, pipe_out);
1399 #if defined (COPROCESS_SUPPORT)
1400 coproc_closeall ();
1401 #endif
1403 /* If this is a user subshell, set a flag if stdin was redirected.
1404 This is used later to decide whether to redirect fd 0 to
1405 /dev/null for async commands in the subshell. This adds more
1406 sh compatibility, but I'm not sure it's the right thing to do. */
1407 if (user_subshell)
1409 stdin_redir = stdin_redirects (command->redirects);
1410 restore_default_signal (0);
1413 /* If this is an asynchronous command (command &), we want to
1414 redirect the standard input from /dev/null in the absence of
1415 any specific redirection involving stdin. */
1416 if (should_redir_stdin && stdin_redir == 0)
1417 async_redirect_stdin ();
1419 /* Do redirections, then dispose of them before recursive call. */
1420 if (command->redirects)
1422 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1423 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1425 dispose_redirects (command->redirects);
1426 command->redirects = (REDIRECT *)NULL;
1429 if (command->type == cm_subshell)
1430 tcom = command->value.Subshell->command;
1431 else if (user_coproc)
1432 tcom = command->value.Coproc->command;
1433 else
1434 tcom = command;
1436 if (command->flags & CMD_TIME_PIPELINE)
1437 tcom->flags |= CMD_TIME_PIPELINE;
1438 if (command->flags & CMD_TIME_POSIX)
1439 tcom->flags |= CMD_TIME_POSIX;
1441 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1442 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1443 tcom->flags |= CMD_IGNORE_RETURN;
1445 /* If this is a simple command, tell execute_disk_command that it
1446 might be able to get away without forking and simply exec.
1447 This means things like ( sleep 10 ) will only cause one fork.
1448 If we're timing the command or inverting its return value, however,
1449 we cannot do this optimization. */
1450 if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1451 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1452 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1454 tcom->flags |= CMD_NO_FORK;
1455 if (tcom->type == cm_simple)
1456 tcom->value.Simple->flags |= CMD_NO_FORK;
1459 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1460 tcom->flags &= ~CMD_INVERT_RETURN;
1462 result = setjmp (top_level);
1464 /* If we're inside a function while executing this subshell, we
1465 need to handle a possible `return'. */
1466 function_value = 0;
1467 if (return_catch_flag)
1468 function_value = setjmp (return_catch);
1470 /* If we're going to exit the shell, we don't want to invert the return
1471 status. */
1472 if (result == EXITPROG)
1473 invert = 0, return_code = last_command_exit_value;
1474 else if (result)
1475 return_code = EXECUTION_FAILURE;
1476 else if (function_value)
1477 return_code = return_catch_value;
1478 else
1479 return_code = execute_command_internal (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1481 /* If we are asked to, invert the return value. */
1482 if (invert)
1483 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1484 : EXECUTION_SUCCESS;
1486 /* If we were explicitly placed in a subshell with (), we need
1487 to do the `shell cleanup' things, such as running traps[0]. */
1488 if (user_subshell && signal_is_trapped (0))
1490 last_command_exit_value = return_code;
1491 return_code = run_exit_trap ();
1494 subshell_level--;
1495 return (return_code);
1496 /* NOTREACHED */
1499 #if defined (COPROCESS_SUPPORT)
1500 #define COPROC_MAX 16
1502 typedef struct cpelement
1504 struct cpelement *next;
1505 struct coproc *coproc;
1507 cpelement_t;
1509 typedef struct cplist
1511 struct cpelement *head;
1512 struct cpelement *tail;
1513 int ncoproc;
1515 cplist_t;
1517 static struct cpelement *cpe_alloc __P((struct coproc *));
1518 static void cpe_dispose __P((struct cpelement *));
1519 static struct cpelement *cpl_add __P((struct coproc *));
1520 static struct cpelement *cpl_delete __P((pid_t));
1521 static void cpl_reap __P((void));
1522 static void cpl_flush __P((void));
1523 static struct cpelement *cpl_search __P((pid_t));
1524 static struct cpelement *cpl_searchbyname __P((char *));
1525 static void cpl_prune __P((void));
1527 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0 };
1529 cplist_t coproc_list = {0, 0, 0};
1531 /* Functions to manage the list of coprocs */
1533 static struct cpelement *
1534 cpe_alloc (cp)
1535 Coproc *cp;
1537 struct cpelement *cpe;
1539 cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1540 cpe->coproc = cp;
1541 cpe->next = (struct cpelement *)0;
1542 return cpe;
1545 static void
1546 cpe_dispose (cpe)
1547 struct cpelement *cpe;
1549 free (cpe);
1552 static struct cpelement *
1553 cpl_add (cp)
1554 Coproc *cp;
1556 struct cpelement *cpe;
1558 cpe = cpe_alloc (cp);
1560 if (coproc_list.head == 0)
1562 coproc_list.head = coproc_list.tail = cpe;
1563 coproc_list.ncoproc = 0; /* just to make sure */
1565 else
1567 coproc_list.tail->next = cpe;
1568 coproc_list.tail = cpe;
1570 coproc_list.ncoproc++;
1572 return cpe;
1575 static struct cpelement *
1576 cpl_delete (pid)
1577 pid_t pid;
1579 struct cpelement *prev, *p;
1581 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1582 if (p->coproc->c_pid == pid)
1584 prev->next = p->next; /* remove from list */
1585 break;
1588 if (p == 0)
1589 return 0; /* not found */
1591 #if defined (DEBUG)
1592 itrace("cpl_delete: deleting %d", pid);
1593 #endif
1595 /* Housekeeping in the border cases. */
1596 if (p == coproc_list.head)
1597 coproc_list.head = coproc_list.head->next;
1598 else if (p == coproc_list.tail)
1599 coproc_list.tail = prev;
1601 coproc_list.ncoproc--;
1602 if (coproc_list.ncoproc == 0)
1603 coproc_list.head = coproc_list.tail = 0;
1604 else if (coproc_list.ncoproc == 1)
1605 coproc_list.tail = coproc_list.head; /* just to make sure */
1607 return (p);
1610 static void
1611 cpl_reap ()
1613 struct cpelement *prev, *p;
1615 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1616 if (p->coproc->c_flags & COPROC_DEAD)
1618 prev->next = p->next; /* remove from list */
1620 /* Housekeeping in the border cases. */
1621 if (p == coproc_list.head)
1622 coproc_list.head = coproc_list.head->next;
1623 else if (p == coproc_list.tail)
1624 coproc_list.tail = prev;
1626 coproc_list.ncoproc--;
1627 if (coproc_list.ncoproc == 0)
1628 coproc_list.head = coproc_list.tail = 0;
1629 else if (coproc_list.ncoproc == 1)
1630 coproc_list.tail = coproc_list.head; /* just to make sure */
1632 #if defined (DEBUG)
1633 itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1634 #endif
1636 coproc_dispose (p->coproc);
1637 cpe_dispose (p);
1641 /* Clear out the list of saved statuses */
1642 static void
1643 cpl_flush ()
1645 struct cpelement *cpe, *p;
1647 for (cpe = coproc_list.head; cpe; )
1649 p = cpe;
1650 cpe = cpe->next;
1652 coproc_dispose (p->coproc);
1653 cpe_dispose (p);
1656 coproc_list.head = coproc_list.tail = 0;
1657 coproc_list.ncoproc = 0;
1660 /* Search for PID in the list of coprocs; return the cpelement struct if
1661 found. If not found, return NULL. */
1662 static struct cpelement *
1663 cpl_search (pid)
1664 pid_t pid;
1666 struct cpelement *cp;
1668 for (cp = coproc_list.head ; cp; cp = cp->next)
1669 if (cp->coproc->c_pid == pid)
1670 return cp;
1671 return (struct cpelement *)NULL;
1674 /* Search for the coproc named NAME in the list of coprocs; return the
1675 cpelement struct if found. If not found, return NULL. */
1676 static struct cpelement *
1677 cpl_searchbyname (name)
1678 char *name;
1680 struct cpelement *cp;
1682 for (cp = coproc_list.head ; cp; cp = cp->next)
1683 if (STREQ (cp->coproc->c_name, name))
1684 return cp;
1685 return (struct cpelement *)NULL;
1688 #if 0
1689 static void
1690 cpl_prune ()
1692 struct cpelement *cp;
1694 while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1696 cp = coproc_list.head;
1697 coproc_list.head = coproc_list.head->next;
1698 coproc_dispose (cp->coproc);
1699 cpe_dispose (cp);
1700 coproc_list.ncoproc--;
1703 #endif
1705 /* These currently use a single global "shell coproc" but are written in a
1706 way to not preclude additional coprocs later (using the list management
1707 package above). */
1709 struct coproc *
1710 getcoprocbypid (pid)
1711 pid_t pid;
1713 return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1716 struct coproc *
1717 getcoprocbyname (name)
1718 const char *name;
1720 return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1723 void
1724 coproc_init (cp)
1725 struct coproc *cp;
1727 cp->c_name = 0;
1728 cp->c_pid = NO_PID;
1729 cp->c_rfd = cp->c_wfd = -1;
1730 cp->c_rsave = cp->c_wsave = -1;
1731 cp->c_flags = cp->c_status = 0;
1734 struct coproc *
1735 coproc_alloc (name, pid)
1736 char *name;
1737 pid_t pid;
1739 struct coproc *cp;
1741 cp = &sh_coproc; /* XXX */
1742 coproc_init (cp);
1744 cp->c_name = savestring (name);
1745 cp->c_pid = pid;
1747 return (cp);
1750 void
1751 coproc_dispose (cp)
1752 struct coproc *cp;
1754 if (cp == 0)
1755 return;
1757 coproc_unsetvars (cp);
1758 FREE (cp->c_name);
1759 coproc_close (cp);
1760 coproc_init (cp);
1763 /* Placeholder for now. */
1764 void
1765 coproc_flush ()
1767 coproc_dispose (&sh_coproc);
1770 void
1771 coproc_close (cp)
1772 struct coproc *cp;
1774 if (cp->c_rfd >= 0)
1776 close (cp->c_rfd);
1777 cp->c_rfd = -1;
1779 if (cp->c_wfd >= 0)
1781 close (cp->c_wfd);
1782 cp->c_wfd = -1;
1784 cp->c_rsave = cp->c_wsave = -1;
1787 void
1788 coproc_closeall ()
1790 coproc_close (&sh_coproc);
1793 void
1794 coproc_reap ()
1796 struct coproc *cp;
1798 cp = &sh_coproc;
1799 if (cp && (cp->c_flags & COPROC_DEAD))
1800 coproc_dispose (cp);
1803 void
1804 coproc_rclose (cp, fd)
1805 struct coproc *cp;
1806 int fd;
1808 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1810 close (cp->c_rfd);
1811 cp->c_rfd = -1;
1815 void
1816 coproc_wclose (cp, fd)
1817 struct coproc *cp;
1818 int fd;
1820 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1822 close (cp->c_wfd);
1823 cp->c_wfd = -1;
1827 void
1828 coproc_checkfd (cp, fd)
1829 struct coproc *cp;
1830 int fd;
1832 int update;
1834 update = 0;
1835 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1836 update = cp->c_rfd = -1;
1837 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1838 update = cp->c_wfd = -1;
1839 if (update)
1840 coproc_setvars (cp);
1843 void
1844 coproc_fdchk (fd)
1845 int fd;
1847 coproc_checkfd (&sh_coproc, fd);
1850 void
1851 coproc_fdclose (cp, fd)
1852 struct coproc *cp;
1853 int fd;
1855 coproc_rclose (cp, fd);
1856 coproc_wclose (cp, fd);
1857 coproc_setvars (cp);
1860 void
1861 coproc_fdsave (cp)
1862 struct coproc *cp;
1864 cp->c_rsave = cp->c_rfd;
1865 cp->c_wsave = cp->c_wfd;
1868 void
1869 coproc_fdrestore (cp)
1870 struct coproc *cp;
1872 cp->c_rfd = cp->c_rsave;
1873 cp->c_wfd = cp->c_wsave;
1876 void
1877 coproc_pidchk (pid, status)
1878 pid_t pid;
1880 struct coproc *cp;
1882 cp = getcoprocbypid (pid);
1883 #if 0
1884 if (cp)
1885 itrace("coproc_pidchk: pid %d has died", pid);
1886 #endif
1887 if (cp)
1889 cp->c_status = status;
1890 cp->c_flags |= COPROC_DEAD;
1891 cp->c_flags &= ~COPROC_RUNNING;
1892 #if 0
1893 coproc_dispose (cp);
1894 #endif
1898 void
1899 coproc_setvars (cp)
1900 struct coproc *cp;
1902 SHELL_VAR *v;
1903 char *namevar, *t;
1904 int l;
1905 #if defined (ARRAY_VARS)
1906 arrayind_t ind;
1907 #endif
1909 if (cp->c_name == 0)
1910 return;
1912 l = strlen (cp->c_name);
1913 namevar = xmalloc (l + 16);
1915 #if defined (ARRAY_VARS)
1916 v = find_variable (cp->c_name);
1917 if (v == 0)
1918 v = make_new_array_variable (cp->c_name);
1919 if (array_p (v) == 0)
1920 v = convert_var_to_array (v);
1922 t = itos (cp->c_rfd);
1923 ind = 0;
1924 v = bind_array_variable (cp->c_name, ind, t, 0);
1925 free (t);
1927 t = itos (cp->c_wfd);
1928 ind = 1;
1929 bind_array_variable (cp->c_name, ind, t, 0);
1930 free (t);
1931 #else
1932 sprintf (namevar, "%s_READ", cp->c_name);
1933 t = itos (cp->c_rfd);
1934 bind_variable (namevar, t, 0);
1935 free (t);
1936 sprintf (namevar, "%s_WRITE", cp->c_name);
1937 t = itos (cp->c_wfd);
1938 bind_variable (namevar, t, 0);
1939 free (t);
1940 #endif
1942 sprintf (namevar, "%s_PID", cp->c_name);
1943 t = itos (cp->c_pid);
1944 bind_variable (namevar, t, 0);
1945 free (t);
1947 free (namevar);
1950 void
1951 coproc_unsetvars (cp)
1952 struct coproc *cp;
1954 int l;
1955 char *namevar;
1957 if (cp->c_name == 0)
1958 return;
1960 l = strlen (cp->c_name);
1961 namevar = xmalloc (l + 16);
1963 sprintf (namevar, "%s_PID", cp->c_name);
1964 unbind_variable (namevar);
1966 #if defined (ARRAY_VARS)
1967 unbind_variable (cp->c_name);
1968 #else
1969 sprintf (namevar, "%s_READ", cp->c_name);
1970 unbind_variable (namevar);
1971 sprintf (namevar, "%s_WRITE", cp->c_name);
1972 unbind_variable (namevar);
1973 #endif
1975 free (namevar);
1978 static int
1979 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
1980 COMMAND *command;
1981 int pipe_in, pipe_out;
1982 struct fd_bitmap *fds_to_close;
1984 int rpipe[2], wpipe[2], estat;
1985 pid_t coproc_pid;
1986 Coproc *cp;
1987 char *tcmd;
1989 /* XXX -- will require changes to handle multiple coprocs */
1990 if (sh_coproc.c_pid != NO_PID)
1992 #if 0
1993 internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc.c_pid, sh_coproc.c_name);
1994 return (last_command_exit_value = EXECUTION_FAILURE);
1995 #else
1996 internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc.c_pid, sh_coproc.c_name);
1997 #endif
1999 coproc_init (&sh_coproc);
2001 command_string_index = 0;
2002 tcmd = make_command_string (command);
2004 sh_openpipe ((int *)&rpipe); /* 0 = parent read, 1 = child write */
2005 sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2007 coproc_pid = make_child (savestring (tcmd), 1);
2008 if (coproc_pid == 0)
2010 close (rpipe[0]);
2011 close (wpipe[1]);
2013 estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2015 fflush (stdout);
2016 fflush (stderr);
2018 exit (estat);
2021 close (rpipe[1]);
2022 close (wpipe[0]);
2024 cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2025 cp->c_rfd = rpipe[0];
2026 cp->c_wfd = wpipe[1];
2028 SET_CLOSE_ON_EXEC (cp->c_rfd);
2029 SET_CLOSE_ON_EXEC (cp->c_wfd);
2031 coproc_setvars (cp);
2033 #if 0
2034 itrace ("execute_coproc: [%d] %s", coproc_pid, the_printed_command);
2035 #endif
2037 close_pipes (pipe_in, pipe_out);
2038 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2039 unlink_fifo_list ();
2040 #endif
2041 stop_pipeline (1, (COMMAND *)NULL);
2042 DESCRIBE_PID (coproc_pid);
2043 run_pending_traps ();
2045 return (EXECUTION_SUCCESS);
2047 #endif
2049 static int
2050 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2051 COMMAND *command;
2052 int asynchronous, pipe_in, pipe_out;
2053 struct fd_bitmap *fds_to_close;
2055 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2056 COMMAND *cmd;
2057 struct fd_bitmap *fd_bitmap;
2059 #if defined (JOB_CONTROL)
2060 sigset_t set, oset;
2061 BLOCK_CHILD (set, oset);
2062 #endif /* JOB_CONTROL */
2064 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2066 prev = pipe_in;
2067 cmd = command;
2069 while (cmd && cmd->type == cm_connection &&
2070 cmd->value.Connection && cmd->value.Connection->connector == '|')
2072 /* Make a pipeline between the two commands. */
2073 if (pipe (fildes) < 0)
2075 sys_error (_("pipe error"));
2076 #if defined (JOB_CONTROL)
2077 terminate_current_pipeline ();
2078 kill_current_pipeline ();
2079 UNBLOCK_CHILD (oset);
2080 #endif /* JOB_CONTROL */
2081 last_command_exit_value = EXECUTION_FAILURE;
2082 /* The unwind-protects installed below will take care
2083 of closing all of the open file descriptors. */
2084 throw_to_top_level ();
2085 return (EXECUTION_FAILURE); /* XXX */
2088 /* Here is a problem: with the new file close-on-exec
2089 code, the read end of the pipe (fildes[0]) stays open
2090 in the first process, so that process will never get a
2091 SIGPIPE. There is no way to signal the first process
2092 that it should close fildes[0] after forking, so it
2093 remains open. No SIGPIPE is ever sent because there
2094 is still a file descriptor open for reading connected
2095 to the pipe. We take care of that here. This passes
2096 around a bitmap of file descriptors that must be
2097 closed after making a child process in execute_simple_command. */
2099 /* We need fd_bitmap to be at least as big as fildes[0].
2100 If fildes[0] is less than fds_to_close->size, then
2101 use fds_to_close->size. */
2102 new_bitmap_size = (fildes[0] < fds_to_close->size)
2103 ? fds_to_close->size
2104 : fildes[0] + 8;
2106 fd_bitmap = new_fd_bitmap (new_bitmap_size);
2108 /* Now copy the old information into the new bitmap. */
2109 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2111 /* And mark the pipe file descriptors to be closed. */
2112 fd_bitmap->bitmap[fildes[0]] = 1;
2114 /* In case there are pipe or out-of-processes errors, we
2115 want all these file descriptors to be closed when
2116 unwind-protects are run, and the storage used for the
2117 bitmaps freed up. */
2118 begin_unwind_frame ("pipe-file-descriptors");
2119 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2120 add_unwind_protect (close_fd_bitmap, fd_bitmap);
2121 if (prev >= 0)
2122 add_unwind_protect (close, prev);
2123 dummyfd = fildes[1];
2124 add_unwind_protect (close, dummyfd);
2126 #if defined (JOB_CONTROL)
2127 add_unwind_protect (restore_signal_mask, &oset);
2128 #endif /* JOB_CONTROL */
2130 if (ignore_return && cmd->value.Connection->first)
2131 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2132 execute_command_internal (cmd->value.Connection->first, asynchronous,
2133 prev, fildes[1], fd_bitmap);
2135 if (prev >= 0)
2136 close (prev);
2138 prev = fildes[0];
2139 close (fildes[1]);
2141 dispose_fd_bitmap (fd_bitmap);
2142 discard_unwind_frame ("pipe-file-descriptors");
2144 cmd = cmd->value.Connection->second;
2147 /* Now execute the rightmost command in the pipeline. */
2148 if (ignore_return && cmd)
2149 cmd->flags |= CMD_IGNORE_RETURN;
2150 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2152 if (prev >= 0)
2153 close (prev);
2155 #if defined (JOB_CONTROL)
2156 UNBLOCK_CHILD (oset);
2157 #endif
2159 QUIT;
2160 return (exec_result);
2163 static int
2164 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2165 COMMAND *command;
2166 int asynchronous, pipe_in, pipe_out;
2167 struct fd_bitmap *fds_to_close;
2169 REDIRECT *rp;
2170 COMMAND *tc, *second;
2171 int ignore_return, exec_result, was_error_trap, invert;
2172 volatile int save_line_number;
2174 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2176 switch (command->value.Connection->connector)
2178 /* Do the first command asynchronously. */
2179 case '&':
2180 tc = command->value.Connection->first;
2181 if (tc == 0)
2182 return (EXECUTION_SUCCESS);
2184 rp = tc->redirects;
2186 if (ignore_return)
2187 tc->flags |= CMD_IGNORE_RETURN;
2188 tc->flags |= CMD_AMPERSAND;
2190 /* If this shell was compiled without job control support,
2191 if we are currently in a subshell via `( xxx )', or if job
2192 control is not active then the standard input for an
2193 asynchronous command is forced to /dev/null. */
2194 #if defined (JOB_CONTROL)
2195 if ((subshell_environment || !job_control) && !stdin_redir)
2196 #else
2197 if (!stdin_redir)
2198 #endif /* JOB_CONTROL */
2199 tc->flags |= CMD_STDIN_REDIR;
2201 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2202 QUIT;
2204 if (tc->flags & CMD_STDIN_REDIR)
2205 tc->flags &= ~CMD_STDIN_REDIR;
2207 second = command->value.Connection->second;
2208 if (second)
2210 if (ignore_return)
2211 second->flags |= CMD_IGNORE_RETURN;
2213 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2216 break;
2218 /* Just call execute command on both sides. */
2219 case ';':
2220 if (ignore_return)
2222 if (command->value.Connection->first)
2223 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2224 if (command->value.Connection->second)
2225 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2227 executing_list++;
2228 QUIT;
2229 execute_command (command->value.Connection->first);
2230 QUIT;
2231 exec_result = execute_command_internal (command->value.Connection->second,
2232 asynchronous, pipe_in, pipe_out,
2233 fds_to_close);
2234 executing_list--;
2235 break;
2237 case '|':
2238 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2239 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2240 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2242 line_number_for_err_trap = line_number;
2243 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2245 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2247 last_command_exit_value = exec_result;
2248 save_line_number = line_number;
2249 line_number = line_number_for_err_trap;
2250 run_error_trap ();
2251 line_number = save_line_number;
2254 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2256 last_command_exit_value = exec_result;
2257 run_pending_traps ();
2258 jump_to_top_level (ERREXIT);
2261 break;
2263 case AND_AND:
2264 case OR_OR:
2265 if (asynchronous)
2267 /* If we have something like `a && b &' or `a || b &', run the
2268 && or || stuff in a subshell. Force a subshell and just call
2269 execute_command_internal again. Leave asynchronous on
2270 so that we get a report from the parent shell about the
2271 background job. */
2272 command->flags |= CMD_FORCE_SUBSHELL;
2273 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2274 break;
2277 /* Execute the first command. If the result of that is successful
2278 and the connector is AND_AND, or the result is not successful
2279 and the connector is OR_OR, then execute the second command,
2280 otherwise return. */
2282 executing_list++;
2283 if (command->value.Connection->first)
2284 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2286 exec_result = execute_command (command->value.Connection->first);
2287 QUIT;
2288 if (((command->value.Connection->connector == AND_AND) &&
2289 (exec_result == EXECUTION_SUCCESS)) ||
2290 ((command->value.Connection->connector == OR_OR) &&
2291 (exec_result != EXECUTION_SUCCESS)))
2293 if (ignore_return && command->value.Connection->second)
2294 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2296 exec_result = execute_command (command->value.Connection->second);
2298 executing_list--;
2299 break;
2301 default:
2302 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2303 jump_to_top_level (DISCARD);
2304 exec_result = EXECUTION_FAILURE;
2307 return exec_result;
2310 #define REAP() \
2311 do \
2313 if (!interactive_shell) \
2314 reap_dead_jobs (); \
2316 while (0)
2318 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2319 DO command; DONE */
2320 static int
2321 execute_for_command (for_command)
2322 FOR_COM *for_command;
2324 register WORD_LIST *releaser, *list;
2325 SHELL_VAR *v;
2326 char *identifier;
2327 int retval, save_line_number;
2328 #if 0
2329 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2330 #endif
2332 save_line_number = line_number;
2333 if (check_identifier (for_command->name, 1) == 0)
2335 if (posixly_correct && interactive_shell == 0)
2337 last_command_exit_value = EX_BADUSAGE;
2338 jump_to_top_level (ERREXIT);
2340 return (EXECUTION_FAILURE);
2343 loop_level++;
2344 identifier = for_command->name->word;
2346 list = releaser = expand_words_no_vars (for_command->map_list);
2348 begin_unwind_frame ("for");
2349 add_unwind_protect (dispose_words, releaser);
2351 #if 0
2352 if (lexical_scoping)
2354 old_value = copy_variable (find_variable (identifier));
2355 if (old_value)
2356 add_unwind_protect (dispose_variable, old_value);
2358 #endif
2360 if (for_command->flags & CMD_IGNORE_RETURN)
2361 for_command->action->flags |= CMD_IGNORE_RETURN;
2363 for (retval = EXECUTION_SUCCESS; list; list = list->next)
2365 QUIT;
2367 line_number = for_command->line;
2369 /* Remember what this command looks like, for debugger. */
2370 command_string_index = 0;
2371 print_for_command_head (for_command);
2373 if (echo_command_at_execute)
2374 xtrace_print_for_command_head (for_command);
2376 /* Save this command unless it's a trap command and we're not running
2377 a debug trap. */
2378 #if 0
2379 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2380 #else
2381 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2382 #endif
2384 FREE (the_printed_command_except_trap);
2385 the_printed_command_except_trap = savestring (the_printed_command);
2388 retval = run_debug_trap ();
2389 #if defined (DEBUGGER)
2390 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2391 skip the command. */
2392 if (debugging_mode && retval != EXECUTION_SUCCESS)
2393 continue;
2394 #endif
2396 this_command_name = (char *)NULL;
2397 v = bind_variable (identifier, list->word->word, 0);
2398 if (readonly_p (v) || noassign_p (v))
2400 line_number = save_line_number;
2401 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2403 last_command_exit_value = EXECUTION_FAILURE;
2404 jump_to_top_level (FORCE_EOF);
2406 else
2408 dispose_words (releaser);
2409 discard_unwind_frame ("for");
2410 loop_level--;
2411 return (EXECUTION_FAILURE);
2414 retval = execute_command (for_command->action);
2415 REAP ();
2416 QUIT;
2418 if (breaking)
2420 breaking--;
2421 break;
2424 if (continuing)
2426 continuing--;
2427 if (continuing)
2428 break;
2432 loop_level--;
2433 line_number = save_line_number;
2435 #if 0
2436 if (lexical_scoping)
2438 if (!old_value)
2439 unbind_variable (identifier);
2440 else
2442 SHELL_VAR *new_value;
2444 new_value = bind_variable (identifier, value_cell(old_value), 0);
2445 new_value->attributes = old_value->attributes;
2446 dispose_variable (old_value);
2449 #endif
2451 dispose_words (releaser);
2452 discard_unwind_frame ("for");
2453 return (retval);
2456 #if defined (ARITH_FOR_COMMAND)
2457 /* Execute an arithmetic for command. The syntax is
2459 for (( init ; step ; test ))
2461 body
2462 done
2464 The execution should be exactly equivalent to
2466 eval \(\( init \)\)
2467 while eval \(\( test \)\) ; do
2468 body;
2469 eval \(\( step \)\)
2470 done
2472 static intmax_t
2473 eval_arith_for_expr (l, okp)
2474 WORD_LIST *l;
2475 int *okp;
2477 WORD_LIST *new;
2478 intmax_t expresult;
2479 int r;
2481 new = expand_words_no_vars (l);
2482 if (new)
2484 if (echo_command_at_execute)
2485 xtrace_print_arith_cmd (new);
2486 this_command_name = "(("; /* )) for expression error messages */
2488 command_string_index = 0;
2489 print_arith_command (new);
2490 if (signal_in_progress (DEBUG_TRAP) == 0)
2492 FREE (the_printed_command_except_trap);
2493 the_printed_command_except_trap = savestring (the_printed_command);
2496 r = run_debug_trap ();
2497 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2498 skip the command. */
2499 #if defined (DEBUGGER)
2500 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
2501 expresult = evalexp (new->word->word, okp);
2502 else
2504 expresult = 0;
2505 if (okp)
2506 *okp = 1;
2508 #else
2509 expresult = evalexp (new->word->word, okp);
2510 #endif
2511 dispose_words (new);
2513 else
2515 expresult = 0;
2516 if (okp)
2517 *okp = 1;
2519 return (expresult);
2522 static int
2523 execute_arith_for_command (arith_for_command)
2524 ARITH_FOR_COM *arith_for_command;
2526 intmax_t expresult;
2527 int expok, body_status, arith_lineno, save_lineno;
2529 body_status = EXECUTION_SUCCESS;
2530 loop_level++;
2531 save_lineno = line_number;
2533 if (arith_for_command->flags & CMD_IGNORE_RETURN)
2534 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
2536 this_command_name = "(("; /* )) for expression error messages */
2538 /* save the starting line number of the command so we can reset
2539 line_number before executing each expression -- for $LINENO
2540 and the DEBUG trap. */
2541 line_number = arith_lineno = arith_for_command->line;
2542 if (variable_context && interactive_shell)
2543 line_number -= function_line_number;
2545 /* Evaluate the initialization expression. */
2546 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
2547 if (expok == 0)
2549 line_number = save_lineno;
2550 return (EXECUTION_FAILURE);
2553 while (1)
2555 /* Evaluate the test expression. */
2556 line_number = arith_lineno;
2557 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
2558 line_number = save_lineno;
2560 if (expok == 0)
2562 body_status = EXECUTION_FAILURE;
2563 break;
2565 REAP ();
2566 if (expresult == 0)
2567 break;
2569 /* Execute the body of the arithmetic for command. */
2570 QUIT;
2571 body_status = execute_command (arith_for_command->action);
2572 QUIT;
2574 /* Handle any `break' or `continue' commands executed by the body. */
2575 if (breaking)
2577 breaking--;
2578 break;
2581 if (continuing)
2583 continuing--;
2584 if (continuing)
2585 break;
2588 /* Evaluate the step expression. */
2589 line_number = arith_lineno;
2590 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
2591 line_number = save_lineno;
2593 if (expok == 0)
2595 body_status = EXECUTION_FAILURE;
2596 break;
2600 loop_level--;
2601 line_number = save_lineno;
2603 return (body_status);
2605 #endif
2607 #if defined (SELECT_COMMAND)
2608 static int LINES, COLS, tabsize;
2610 #define RP_SPACE ") "
2611 #define RP_SPACE_LEN 2
2613 /* XXX - does not handle numbers > 1000000 at all. */
2614 #define NUMBER_LEN(s) \
2615 ((s < 10) ? 1 \
2616 : ((s < 100) ? 2 \
2617 : ((s < 1000) ? 3 \
2618 : ((s < 10000) ? 4 \
2619 : ((s < 100000) ? 5 \
2620 : 6)))))
2622 static int
2623 print_index_and_element (len, ind, list)
2624 int len, ind;
2625 WORD_LIST *list;
2627 register WORD_LIST *l;
2628 register int i;
2630 if (list == 0)
2631 return (0);
2632 for (i = ind, l = list; l && --i; l = l->next)
2634 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
2635 return (STRLEN (l->word->word));
2638 static void
2639 indent (from, to)
2640 int from, to;
2642 while (from < to)
2644 if ((to / tabsize) > (from / tabsize))
2646 putc ('\t', stderr);
2647 from += tabsize - from % tabsize;
2649 else
2651 putc (' ', stderr);
2652 from++;
2657 static void
2658 print_select_list (list, list_len, max_elem_len, indices_len)
2659 WORD_LIST *list;
2660 int list_len, max_elem_len, indices_len;
2662 int ind, row, elem_len, pos, cols, rows;
2663 int first_column_indices_len, other_indices_len;
2665 if (list == 0)
2667 putc ('\n', stderr);
2668 return;
2671 cols = max_elem_len ? COLS / max_elem_len : 1;
2672 if (cols == 0)
2673 cols = 1;
2674 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
2675 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
2677 if (rows == 1)
2679 rows = cols;
2680 cols = 1;
2683 first_column_indices_len = NUMBER_LEN (rows);
2684 other_indices_len = indices_len;
2686 for (row = 0; row < rows; row++)
2688 ind = row;
2689 pos = 0;
2690 while (1)
2692 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
2693 elem_len = print_index_and_element (indices_len, ind + 1, list);
2694 elem_len += indices_len + RP_SPACE_LEN;
2695 ind += rows;
2696 if (ind >= list_len)
2697 break;
2698 indent (pos + elem_len, pos + max_elem_len);
2699 pos += max_elem_len;
2701 putc ('\n', stderr);
2705 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2706 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2707 If the number is between 1 and LIST_LEN, return that selection. If EOF
2708 is read, return a null string. If a blank line is entered, or an invalid
2709 number is entered, the loop is executed again. */
2710 static char *
2711 select_query (list, list_len, prompt, print_menu)
2712 WORD_LIST *list;
2713 int list_len;
2714 char *prompt;
2715 int print_menu;
2717 int max_elem_len, indices_len, len;
2718 intmax_t reply;
2719 WORD_LIST *l;
2720 char *repl_string, *t;
2722 t = get_string_value ("LINES");
2723 LINES = (t && *t) ? atoi (t) : 24;
2724 t = get_string_value ("COLUMNS");
2725 COLS = (t && *t) ? atoi (t) : 80;
2727 #if 0
2728 t = get_string_value ("TABSIZE");
2729 tabsize = (t && *t) ? atoi (t) : 8;
2730 if (tabsize <= 0)
2731 tabsize = 8;
2732 #else
2733 tabsize = 8;
2734 #endif
2736 max_elem_len = 0;
2737 for (l = list; l; l = l->next)
2739 len = STRLEN (l->word->word);
2740 if (len > max_elem_len)
2741 max_elem_len = len;
2743 indices_len = NUMBER_LEN (list_len);
2744 max_elem_len += indices_len + RP_SPACE_LEN + 2;
2746 while (1)
2748 if (print_menu)
2749 print_select_list (list, list_len, max_elem_len, indices_len);
2750 fprintf (stderr, "%s", prompt);
2751 fflush (stderr);
2752 QUIT;
2754 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
2756 putchar ('\n');
2757 return ((char *)NULL);
2759 repl_string = get_string_value ("REPLY");
2760 if (*repl_string == 0)
2762 print_menu = 1;
2763 continue;
2765 if (legal_number (repl_string, &reply) == 0)
2766 return "";
2767 if (reply < 1 || reply > list_len)
2768 return "";
2770 for (l = list; l && --reply; l = l->next)
2772 return (l->word->word);
2776 /* Execute a SELECT command. The syntax is:
2777 SELECT word IN list DO command_list DONE
2778 Only `break' or `return' in command_list will terminate
2779 the command. */
2780 static int
2781 execute_select_command (select_command)
2782 SELECT_COM *select_command;
2784 WORD_LIST *releaser, *list;
2785 SHELL_VAR *v;
2786 char *identifier, *ps3_prompt, *selection;
2787 int retval, list_len, show_menu, save_line_number;
2789 if (check_identifier (select_command->name, 1) == 0)
2790 return (EXECUTION_FAILURE);
2792 save_line_number = line_number;
2793 line_number = select_command->line;
2795 command_string_index = 0;
2796 print_select_command_head (select_command);
2798 if (echo_command_at_execute)
2799 xtrace_print_select_command_head (select_command);
2801 #if 0
2802 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2803 #else
2804 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2805 #endif
2807 FREE (the_printed_command_except_trap);
2808 the_printed_command_except_trap = savestring (the_printed_command);
2811 retval = run_debug_trap ();
2812 #if defined (DEBUGGER)
2813 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2814 skip the command. */
2815 if (debugging_mode && retval != EXECUTION_SUCCESS)
2816 return (EXECUTION_SUCCESS);
2817 #endif
2819 loop_level++;
2820 identifier = select_command->name->word;
2822 /* command and arithmetic substitution, parameter and variable expansion,
2823 word splitting, pathname expansion, and quote removal. */
2824 list = releaser = expand_words_no_vars (select_command->map_list);
2825 list_len = list_length (list);
2826 if (list == 0 || list_len == 0)
2828 if (list)
2829 dispose_words (list);
2830 line_number = save_line_number;
2831 return (EXECUTION_SUCCESS);
2834 begin_unwind_frame ("select");
2835 add_unwind_protect (dispose_words, releaser);
2837 if (select_command->flags & CMD_IGNORE_RETURN)
2838 select_command->action->flags |= CMD_IGNORE_RETURN;
2840 retval = EXECUTION_SUCCESS;
2841 show_menu = 1;
2843 while (1)
2845 line_number = select_command->line;
2846 ps3_prompt = get_string_value ("PS3");
2847 if (ps3_prompt == 0)
2848 ps3_prompt = "#? ";
2850 QUIT;
2851 selection = select_query (list, list_len, ps3_prompt, show_menu);
2852 QUIT;
2853 if (selection == 0)
2855 /* select_query returns EXECUTION_FAILURE if the read builtin
2856 fails, so we want to return failure in this case. */
2857 retval = EXECUTION_FAILURE;
2858 break;
2861 v = bind_variable (identifier, selection, 0);
2862 if (readonly_p (v) || noassign_p (v))
2864 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2866 last_command_exit_value = EXECUTION_FAILURE;
2867 jump_to_top_level (FORCE_EOF);
2869 else
2871 dispose_words (releaser);
2872 discard_unwind_frame ("select");
2873 loop_level--;
2874 line_number = save_line_number;
2875 return (EXECUTION_FAILURE);
2879 retval = execute_command (select_command->action);
2881 REAP ();
2882 QUIT;
2884 if (breaking)
2886 breaking--;
2887 break;
2890 if (continuing)
2892 continuing--;
2893 if (continuing)
2894 break;
2897 #if defined (KSH_COMPATIBLE_SELECT)
2898 show_menu = 0;
2899 selection = get_string_value ("REPLY");
2900 if (selection && *selection == '\0')
2901 show_menu = 1;
2902 #endif
2905 loop_level--;
2906 line_number = save_line_number;
2908 dispose_words (releaser);
2909 discard_unwind_frame ("select");
2910 return (retval);
2912 #endif /* SELECT_COMMAND */
2914 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2915 The pattern_list is a linked list of pattern clauses; each clause contains
2916 some patterns to compare word_desc against, and an associated command to
2917 execute. */
2918 static int
2919 execute_case_command (case_command)
2920 CASE_COM *case_command;
2922 register WORD_LIST *list;
2923 WORD_LIST *wlist, *es;
2924 PATTERN_LIST *clauses;
2925 char *word, *pattern;
2926 int retval, match, ignore_return, save_line_number;
2928 save_line_number = line_number;
2929 line_number = case_command->line;
2931 command_string_index = 0;
2932 print_case_command_head (case_command);
2934 if (echo_command_at_execute)
2935 xtrace_print_case_command_head (case_command);
2937 #if 0
2938 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2939 #else
2940 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2941 #endif
2943 FREE (the_printed_command_except_trap);
2944 the_printed_command_except_trap = savestring (the_printed_command);
2947 retval = run_debug_trap();
2948 #if defined (DEBUGGER)
2949 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2950 skip the command. */
2951 if (debugging_mode && retval != EXECUTION_SUCCESS)
2953 line_number = save_line_number;
2954 return (EXECUTION_SUCCESS);
2956 #endif
2958 wlist = expand_word_unsplit (case_command->word, 0);
2959 word = wlist ? string_list (wlist) : savestring ("");
2960 dispose_words (wlist);
2962 retval = EXECUTION_SUCCESS;
2963 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2965 begin_unwind_frame ("case");
2966 add_unwind_protect ((Function *)xfree, word);
2968 #define EXIT_CASE() goto exit_case_command
2970 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2972 QUIT;
2973 for (list = clauses->patterns; list; list = list->next)
2975 es = expand_word_leave_quoted (list->word, 0);
2977 if (es && es->word && es->word->word && *(es->word->word))
2978 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2979 else
2981 pattern = (char *)xmalloc (1);
2982 pattern[0] = '\0';
2985 /* Since the pattern does not undergo quote removal (as per
2986 Posix.2, section 3.9.4.3), the strmatch () call must be able
2987 to recognize backslashes as escape characters. */
2988 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
2989 free (pattern);
2991 dispose_words (es);
2993 if (match)
2997 if (clauses->action && ignore_return)
2998 clauses->action->flags |= CMD_IGNORE_RETURN;
2999 retval = execute_command (clauses->action);
3001 while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3002 if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3003 EXIT_CASE ();
3004 else
3005 break;
3008 QUIT;
3012 exit_case_command:
3013 free (word);
3014 discard_unwind_frame ("case");
3015 line_number = save_line_number;
3016 return (retval);
3019 #define CMD_WHILE 0
3020 #define CMD_UNTIL 1
3022 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3023 Repeatedly execute action while executing test produces
3024 EXECUTION_SUCCESS. */
3025 static int
3026 execute_while_command (while_command)
3027 WHILE_COM *while_command;
3029 return (execute_while_or_until (while_command, CMD_WHILE));
3032 /* UNTIL is just like WHILE except that the test result is negated. */
3033 static int
3034 execute_until_command (while_command)
3035 WHILE_COM *while_command;
3037 return (execute_while_or_until (while_command, CMD_UNTIL));
3040 /* The body for both while and until. The only difference between the
3041 two is that the test value is treated differently. TYPE is
3042 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3043 be EXECUTION_SUCCESS if no commands in the body are executed, and
3044 the status of the last command executed in the body otherwise. */
3045 static int
3046 execute_while_or_until (while_command, type)
3047 WHILE_COM *while_command;
3048 int type;
3050 int return_value, body_status;
3052 body_status = EXECUTION_SUCCESS;
3053 loop_level++;
3055 while_command->test->flags |= CMD_IGNORE_RETURN;
3056 if (while_command->flags & CMD_IGNORE_RETURN)
3057 while_command->action->flags |= CMD_IGNORE_RETURN;
3059 while (1)
3061 return_value = execute_command (while_command->test);
3062 REAP ();
3064 /* Need to handle `break' in the test when we would break out of the
3065 loop. The job control code will set `breaking' to loop_level
3066 when a job in a loop is stopped with SIGTSTP. If the stopped job
3067 is in the loop test, `breaking' will not be reset unless we do
3068 this, and the shell will cease to execute commands. */
3069 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3071 if (breaking)
3072 breaking--;
3073 break;
3075 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3077 if (breaking)
3078 breaking--;
3079 break;
3082 QUIT;
3083 body_status = execute_command (while_command->action);
3084 QUIT;
3086 if (breaking)
3088 breaking--;
3089 break;
3092 if (continuing)
3094 continuing--;
3095 if (continuing)
3096 break;
3099 loop_level--;
3101 return (body_status);
3104 /* IF test THEN command [ELSE command].
3105 IF also allows ELIF in the place of ELSE IF, but
3106 the parser makes *that* stupidity transparent. */
3107 static int
3108 execute_if_command (if_command)
3109 IF_COM *if_command;
3111 int return_value, save_line_number;
3113 save_line_number = line_number;
3114 if_command->test->flags |= CMD_IGNORE_RETURN;
3115 return_value = execute_command (if_command->test);
3116 line_number = save_line_number;
3118 if (return_value == EXECUTION_SUCCESS)
3120 QUIT;
3122 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3123 if_command->true_case->flags |= CMD_IGNORE_RETURN;
3125 return (execute_command (if_command->true_case));
3127 else
3129 QUIT;
3131 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3132 if_command->false_case->flags |= CMD_IGNORE_RETURN;
3134 return (execute_command (if_command->false_case));
3138 #if defined (DPAREN_ARITHMETIC)
3139 static int
3140 execute_arith_command (arith_command)
3141 ARITH_COM *arith_command;
3143 int expok, save_line_number, retval;
3144 intmax_t expresult;
3145 WORD_LIST *new;
3146 char *exp;
3148 expresult = 0;
3150 save_line_number = line_number;
3151 this_command_name = "(("; /* )) */
3152 line_number = arith_command->line;
3153 /* If we're in a function, update the line number information. */
3154 if (variable_context && interactive_shell)
3155 line_number -= function_line_number;
3157 command_string_index = 0;
3158 print_arith_command (arith_command->exp);
3160 if (signal_in_progress (DEBUG_TRAP) == 0)
3162 FREE (the_printed_command_except_trap);
3163 the_printed_command_except_trap = savestring (the_printed_command);
3166 /* Run the debug trap before each arithmetic command, but do it after we
3167 update the line number information and before we expand the various
3168 words in the expression. */
3169 retval = run_debug_trap ();
3170 #if defined (DEBUGGER)
3171 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3172 skip the command. */
3173 if (debugging_mode && retval != EXECUTION_SUCCESS)
3175 line_number = save_line_number;
3176 return (EXECUTION_SUCCESS);
3178 #endif
3180 new = expand_words_no_vars (arith_command->exp);
3182 /* If we're tracing, make a new word list with `((' at the front and `))'
3183 at the back and print it. */
3184 if (echo_command_at_execute)
3185 xtrace_print_arith_cmd (new);
3187 if (new)
3189 exp = new->next ? string_list (new) : new->word->word;
3190 expresult = evalexp (exp, &expok);
3191 line_number = save_line_number;
3192 if (exp != new->word->word)
3193 free (exp);
3194 dispose_words (new);
3196 else
3198 expresult = 0;
3199 expok = 1;
3202 if (expok == 0)
3203 return (EXECUTION_FAILURE);
3205 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3207 #endif /* DPAREN_ARITHMETIC */
3209 #if defined (COND_COMMAND)
3211 static char * const nullstr = "";
3213 static int
3214 execute_cond_node (cond)
3215 COND_COM *cond;
3217 int result, invert, patmatch, rmatch, mflags, ignore;
3218 char *arg1, *arg2;
3220 invert = (cond->flags & CMD_INVERT_RETURN);
3221 ignore = (cond->flags & CMD_IGNORE_RETURN);
3222 if (ignore)
3224 if (cond->left)
3225 cond->left->flags |= CMD_IGNORE_RETURN;
3226 if (cond->right)
3227 cond->right->flags |= CMD_IGNORE_RETURN;
3230 if (cond->type == COND_EXPR)
3231 result = execute_cond_node (cond->left);
3232 else if (cond->type == COND_OR)
3234 result = execute_cond_node (cond->left);
3235 if (result != EXECUTION_SUCCESS)
3236 result = execute_cond_node (cond->right);
3238 else if (cond->type == COND_AND)
3240 result = execute_cond_node (cond->left);
3241 if (result == EXECUTION_SUCCESS)
3242 result = execute_cond_node (cond->right);
3244 else if (cond->type == COND_UNARY)
3246 if (ignore)
3247 comsub_ignore_return++;
3248 arg1 = cond_expand_word (cond->left->op, 0);
3249 if (ignore)
3250 comsub_ignore_return--;
3251 if (arg1 == 0)
3252 arg1 = nullstr;
3253 if (echo_command_at_execute)
3254 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3255 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3256 if (arg1 != nullstr)
3257 free (arg1);
3259 else if (cond->type == COND_BINARY)
3261 rmatch = 0;
3262 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3263 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
3264 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3265 #if defined (COND_REGEXP)
3266 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3267 cond->op->word[2] == '\0');
3268 #endif
3270 if (ignore)
3271 comsub_ignore_return++;
3272 arg1 = cond_expand_word (cond->left->op, 0);
3273 if (ignore)
3274 comsub_ignore_return--;
3275 if (arg1 == 0)
3276 arg1 = nullstr;
3277 if (ignore)
3278 comsub_ignore_return++;
3279 arg2 = cond_expand_word (cond->right->op,
3280 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3281 if (ignore)
3282 comsub_ignore_return--;
3283 if (arg2 == 0)
3284 arg2 = nullstr;
3286 if (echo_command_at_execute)
3287 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3289 #if defined (COND_REGEXP)
3290 if (rmatch)
3292 mflags = SHMAT_PWARN;
3293 #if defined (ARRAY_VARS)
3294 mflags |= SHMAT_SUBEXP;
3295 #endif
3297 result = sh_regmatch (arg1, arg2, mflags);
3299 else
3300 #endif /* COND_REGEXP */
3302 int oe;
3303 oe = extended_glob;
3304 extended_glob = 1;
3305 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3306 ? EXECUTION_SUCCESS
3307 : EXECUTION_FAILURE;
3308 extended_glob = oe;
3310 if (arg1 != nullstr)
3311 free (arg1);
3312 if (arg2 != nullstr)
3313 free (arg2);
3315 else
3317 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3318 jump_to_top_level (DISCARD);
3319 result = EXECUTION_FAILURE;
3322 if (invert)
3323 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3325 return result;
3328 static int
3329 execute_cond_command (cond_command)
3330 COND_COM *cond_command;
3332 int retval, save_line_number;
3334 retval = EXECUTION_SUCCESS;
3335 save_line_number = line_number;
3337 this_command_name = "[[";
3338 line_number = cond_command->line;
3339 /* If we're in a function, update the line number information. */
3340 if (variable_context && interactive_shell)
3341 line_number -= function_line_number;
3342 command_string_index = 0;
3343 print_cond_command (cond_command);
3345 if (signal_in_progress (DEBUG_TRAP) == 0)
3347 FREE (the_printed_command_except_trap);
3348 the_printed_command_except_trap = savestring (the_printed_command);
3351 /* Run the debug trap before each conditional command, but do it after we
3352 update the line number information. */
3353 retval = run_debug_trap ();
3354 #if defined (DEBUGGER)
3355 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3356 skip the command. */
3357 if (debugging_mode && retval != EXECUTION_SUCCESS)
3359 line_number = save_line_number;
3360 return (EXECUTION_SUCCESS);
3362 #endif
3364 #if 0
3365 debug_print_cond_command (cond_command);
3366 #endif
3368 last_command_exit_value = retval = execute_cond_node (cond_command);
3369 line_number = save_line_number;
3370 return (retval);
3372 #endif /* COND_COMMAND */
3374 static void
3375 bind_lastarg (arg)
3376 char *arg;
3378 SHELL_VAR *var;
3380 if (arg == 0)
3381 arg = "";
3382 var = bind_variable ("_", arg, 0);
3383 VUNSETATTR (var, att_exported);
3386 /* Execute a null command. Fork a subshell if the command uses pipes or is
3387 to be run asynchronously. This handles all the side effects that are
3388 supposed to take place. */
3389 static int
3390 execute_null_command (redirects, pipe_in, pipe_out, async)
3391 REDIRECT *redirects;
3392 int pipe_in, pipe_out, async;
3394 int r;
3395 int forcefork;
3396 REDIRECT *rd;
3398 for (forcefork = 0, rd = redirects; rd; rd = rd->next)
3399 forcefork += rd->rflags & REDIR_VARASSIGN;
3401 if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
3403 /* We have a null command, but we really want a subshell to take
3404 care of it. Just fork, do piping and redirections, and exit. */
3405 if (make_child ((char *)NULL, async) == 0)
3407 /* Cancel traps, in trap.c. */
3408 restore_original_signals (); /* XXX */
3410 do_piping (pipe_in, pipe_out);
3412 #if defined (COPROCESS_SUPPORT)
3413 coproc_closeall ();
3414 #endif
3416 subshell_environment = 0;
3417 if (async)
3418 subshell_environment |= SUBSHELL_ASYNC;
3419 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3420 subshell_environment |= SUBSHELL_PIPE;
3422 if (do_redirections (redirects, RX_ACTIVE) == 0)
3423 exit (EXECUTION_SUCCESS);
3424 else
3425 exit (EXECUTION_FAILURE);
3427 else
3429 close_pipes (pipe_in, pipe_out);
3430 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3431 unlink_fifo_list ();
3432 #endif
3433 return (EXECUTION_SUCCESS);
3436 else
3438 /* Even if there aren't any command names, pretend to do the
3439 redirections that are specified. The user expects the side
3440 effects to take place. If the redirections fail, then return
3441 failure. Otherwise, if a command substitution took place while
3442 expanding the command or a redirection, return the value of that
3443 substitution. Otherwise, return EXECUTION_SUCCESS. */
3445 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
3446 cleanup_redirects (redirection_undo_list);
3447 redirection_undo_list = (REDIRECT *)NULL;
3449 if (r != 0)
3450 return (EXECUTION_FAILURE);
3451 else if (last_command_subst_pid != NO_PID)
3452 return (last_command_exit_value);
3453 else
3454 return (EXECUTION_SUCCESS);
3458 /* This is a hack to suppress word splitting for assignment statements
3459 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3460 static void
3461 fix_assignment_words (words)
3462 WORD_LIST *words;
3464 WORD_LIST *w;
3465 struct builtin *b;
3466 int assoc;
3468 if (words == 0)
3469 return;
3471 b = 0;
3472 assoc = 0;
3474 for (w = words; w; w = w->next)
3475 if (w->word->flags & W_ASSIGNMENT)
3477 if (b == 0)
3479 b = builtin_address_internal (words->word->word, 0);
3480 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3481 return;
3482 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3483 words->word->flags |= W_ASSNBLTIN;
3485 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
3486 #if defined (ARRAY_VARS)
3487 if (assoc)
3488 w->word->flags |= W_ASSIGNASSOC;
3489 #endif
3491 #if defined (ARRAY_VARS)
3492 /* Note that we saw an associative array option to a builtin that takes
3493 assignment statements. This is a bit of a kludge. */
3494 else if (w->word->word[0] == '-' && strchr (w->word->word, 'A'))
3496 if (b == 0)
3498 b = builtin_address_internal (words->word->word, 0);
3499 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3500 return;
3501 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3502 words->word->flags |= W_ASSNBLTIN;
3504 if (words->word->flags & W_ASSNBLTIN)
3505 assoc = 1;
3507 #endif
3510 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3511 to PATHNAME, is a directory. Used by the autocd code below. */
3512 static int
3513 is_dirname (pathname)
3514 char *pathname;
3516 char *temp;
3517 temp = search_for_command (pathname);
3518 return (temp ? file_isdir (temp) : file_isdir (pathname));
3521 /* The meaty part of all the executions. We have to start hacking the
3522 real execution of commands here. Fork a process, set things up,
3523 execute the command. */
3524 static int
3525 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
3526 SIMPLE_COM *simple_command;
3527 int pipe_in, pipe_out, async;
3528 struct fd_bitmap *fds_to_close;
3530 WORD_LIST *words, *lastword;
3531 char *command_line, *lastarg, *temp;
3532 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
3533 pid_t old_last_async_pid;
3534 sh_builtin_func_t *builtin;
3535 SHELL_VAR *func;
3537 result = EXECUTION_SUCCESS;
3538 special_builtin_failed = builtin_is_special = 0;
3539 command_line = (char *)0;
3541 /* If we're in a function, update the line number information. */
3542 if (variable_context && interactive_shell && sourcelevel == 0)
3543 line_number -= function_line_number;
3545 /* Remember what this command line looks like at invocation. */
3546 command_string_index = 0;
3547 print_simple_command (simple_command);
3549 #if 0
3550 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3551 #else
3552 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3553 #endif
3555 FREE (the_printed_command_except_trap);
3556 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
3559 /* Run the debug trap before each simple command, but do it after we
3560 update the line number information. */
3561 result = run_debug_trap ();
3562 #if defined (DEBUGGER)
3563 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3564 skip the command. */
3565 if (debugging_mode && result != EXECUTION_SUCCESS)
3566 return (EXECUTION_SUCCESS);
3567 #endif
3569 first_word_quoted =
3570 simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
3572 last_command_subst_pid = NO_PID;
3573 old_last_async_pid = last_asynchronous_pid;
3575 already_forked = dofork = 0;
3577 /* If we're in a pipeline or run in the background, set DOFORK so we
3578 make the child early, before word expansion. This keeps assignment
3579 statements from affecting the parent shell's environment when they
3580 should not. */
3581 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
3583 /* Something like `%2 &' should restart job 2 in the background, not cause
3584 the shell to fork here. */
3585 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
3586 simple_command->words && simple_command->words->word &&
3587 simple_command->words->word->word &&
3588 (simple_command->words->word->word[0] == '%'))
3589 dofork = 0;
3591 if (dofork)
3593 /* Do this now, because execute_disk_command will do it anyway in the
3594 vast majority of cases. */
3595 maybe_make_export_env ();
3597 /* Don't let a DEBUG trap overwrite the command string to be saved with
3598 the process/job associated with this child. */
3599 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
3601 already_forked = 1;
3602 simple_command->flags |= CMD_NO_FORK;
3604 subshell_environment = SUBSHELL_FORK;
3605 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3606 subshell_environment |= SUBSHELL_PIPE;
3607 if (async)
3608 subshell_environment |= SUBSHELL_ASYNC;
3610 /* We need to do this before piping to handle some really
3611 pathological cases where one of the pipe file descriptors
3612 is < 2. */
3613 if (fds_to_close)
3614 close_fd_bitmap (fds_to_close);
3616 do_piping (pipe_in, pipe_out);
3617 pipe_in = pipe_out = NO_PIPE;
3618 #if defined (COPROCESS_SUPPORT)
3619 coproc_closeall ();
3620 #endif
3622 last_asynchronous_pid = old_last_async_pid;
3624 else
3626 close_pipes (pipe_in, pipe_out);
3627 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3628 unlink_fifo_list ();
3629 #endif
3630 command_line = (char *)NULL; /* don't free this. */
3631 bind_lastarg ((char *)NULL);
3632 return (result);
3636 /* If we are re-running this as the result of executing the `command'
3637 builtin, do not expand the command words a second time. */
3638 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
3640 current_fds_to_close = fds_to_close;
3641 fix_assignment_words (simple_command->words);
3642 /* Pass the ignore return flag down to command substitutions */
3643 if (simple_command->flags & CMD_IGNORE_RETURN) /* XXX */
3644 comsub_ignore_return++;
3645 words = expand_words (simple_command->words);
3646 if (simple_command->flags & CMD_IGNORE_RETURN)
3647 comsub_ignore_return--;
3648 current_fds_to_close = (struct fd_bitmap *)NULL;
3650 else
3651 words = copy_word_list (simple_command->words);
3653 /* It is possible for WORDS not to have anything left in it.
3654 Perhaps all the words consisted of `$foo', and there was
3655 no variable `$foo'. */
3656 if (words == 0)
3658 this_command_name = 0;
3659 result = execute_null_command (simple_command->redirects,
3660 pipe_in, pipe_out,
3661 already_forked ? 0 : async);
3662 if (already_forked)
3663 exit (result);
3664 else
3666 bind_lastarg ((char *)NULL);
3667 set_pipestatus_from_exit (result);
3668 return (result);
3672 lastarg = (char *)NULL;
3674 begin_unwind_frame ("simple-command");
3676 if (echo_command_at_execute)
3677 xtrace_print_word_list (words, 1);
3679 builtin = (sh_builtin_func_t *)NULL;
3680 func = (SHELL_VAR *)NULL;
3681 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
3683 /* Posix.2 says special builtins are found before functions. We
3684 don't set builtin_is_special anywhere other than here, because
3685 this path is followed only when the `command' builtin is *not*
3686 being used, and we don't want to exit the shell if a special
3687 builtin executed with `command builtin' fails. `command' is not
3688 a special builtin. */
3689 if (posixly_correct)
3691 builtin = find_special_builtin (words->word->word);
3692 if (builtin)
3693 builtin_is_special = 1;
3695 if (builtin == 0)
3696 func = find_function (words->word->word);
3699 /* In POSIX mode, assignment errors in the temporary environment cause a
3700 non-interactive shell to exit. */
3701 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
3703 last_command_exit_value = EXECUTION_FAILURE;
3704 jump_to_top_level (ERREXIT);
3707 add_unwind_protect (dispose_words, words);
3708 QUIT;
3710 /* Bind the last word in this command to "$_" after execution. */
3711 for (lastword = words; lastword->next; lastword = lastword->next)
3713 lastarg = lastword->word->word;
3715 #if defined (JOB_CONTROL)
3716 /* Is this command a job control related thing? */
3717 if (words->word->word[0] == '%' && already_forked == 0)
3719 this_command_name = async ? "bg" : "fg";
3720 last_shell_builtin = this_shell_builtin;
3721 this_shell_builtin = builtin_address (this_command_name);
3722 result = (*this_shell_builtin) (words);
3723 goto return_result;
3726 /* One other possiblilty. The user may want to resume an existing job.
3727 If they do, find out whether this word is a candidate for a running
3728 job. */
3729 if (job_control && already_forked == 0 && async == 0 &&
3730 !first_word_quoted &&
3731 !words->next &&
3732 words->word->word[0] &&
3733 !simple_command->redirects &&
3734 pipe_in == NO_PIPE &&
3735 pipe_out == NO_PIPE &&
3736 (temp = get_string_value ("auto_resume")))
3738 int job, jflags, started_status;
3740 jflags = JM_STOPPED|JM_FIRSTMATCH;
3741 if (STREQ (temp, "exact"))
3742 jflags |= JM_EXACT;
3743 else if (STREQ (temp, "substring"))
3744 jflags |= JM_SUBSTRING;
3745 else
3746 jflags |= JM_PREFIX;
3747 job = get_job_by_name (words->word->word, jflags);
3748 if (job != NO_JOB)
3750 run_unwind_frame ("simple-command");
3751 this_command_name = "fg";
3752 last_shell_builtin = this_shell_builtin;
3753 this_shell_builtin = builtin_address ("fg");
3755 started_status = start_job (job, 1);
3756 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
3759 #endif /* JOB_CONTROL */
3761 run_builtin:
3762 /* Remember the name of this command globally. */
3763 this_command_name = words->word->word;
3765 QUIT;
3767 /* This command could be a shell builtin or a user-defined function.
3768 We have already found special builtins by this time, so we do not
3769 set builtin_is_special. If this is a function or builtin, and we
3770 have pipes, then fork a subshell in here. Otherwise, just execute
3771 the command directly. */
3772 if (func == 0 && builtin == 0)
3773 builtin = find_shell_builtin (this_command_name);
3775 last_shell_builtin = this_shell_builtin;
3776 this_shell_builtin = builtin;
3778 if (builtin || func)
3780 if (builtin)
3781 unwind_protect_int (executing_builtin); /* modified in execute_builtin */
3782 if (already_forked)
3784 /* reset_terminating_signals (); */ /* XXX */
3785 /* Cancel traps, in trap.c. */
3786 restore_original_signals ();
3788 if (async)
3790 if ((simple_command->flags & CMD_STDIN_REDIR) &&
3791 pipe_in == NO_PIPE &&
3792 (stdin_redirects (simple_command->redirects) == 0))
3793 async_redirect_stdin ();
3794 setup_async_signals ();
3797 subshell_level++;
3798 execute_subshell_builtin_or_function
3799 (words, simple_command->redirects, builtin, func,
3800 pipe_in, pipe_out, async, fds_to_close,
3801 simple_command->flags);
3802 subshell_level--;
3804 else
3806 result = execute_builtin_or_function
3807 (words, builtin, func, simple_command->redirects, fds_to_close,
3808 simple_command->flags);
3809 if (builtin)
3811 if (result > EX_SHERRBASE)
3813 result = builtin_status (result);
3814 if (builtin_is_special)
3815 special_builtin_failed = 1;
3817 /* In POSIX mode, if there are assignment statements preceding
3818 a special builtin, they persist after the builtin
3819 completes. */
3820 if (posixly_correct && builtin_is_special && temporary_env)
3821 merge_temporary_env ();
3823 else /* function */
3825 if (result == EX_USAGE)
3826 result = EX_BADUSAGE;
3827 else if (result > EX_SHERRBASE)
3828 result = EXECUTION_FAILURE;
3831 set_pipestatus_from_exit (result);
3833 goto return_result;
3837 if (autocd && interactive && words->word && is_dirname (words->word->word))
3839 words = make_word_list (make_word ("cd"), words);
3840 xtrace_print_word_list (words, 0);
3841 goto run_builtin;
3844 if (command_line == 0)
3845 command_line = savestring (the_printed_command_except_trap);
3847 #if defined (PROCESS_SUBSTITUTION)
3848 if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
3849 simple_command->flags &= ~CMD_NO_FORK;
3850 #endif
3852 execute_disk_command (words, simple_command->redirects, command_line,
3853 pipe_in, pipe_out, async, fds_to_close,
3854 simple_command->flags);
3856 return_result:
3857 bind_lastarg (lastarg);
3858 FREE (command_line);
3859 dispose_words (words);
3860 discard_unwind_frame ("simple-command");
3861 this_command_name = (char *)NULL; /* points to freed memory now */
3862 return (result);
3865 /* Translate the special builtin exit statuses. We don't really need a
3866 function for this; it's a placeholder for future work. */
3867 static int
3868 builtin_status (result)
3869 int result;
3871 int r;
3873 switch (result)
3875 case EX_USAGE:
3876 r = EX_BADUSAGE;
3877 break;
3878 case EX_REDIRFAIL:
3879 case EX_BADSYNTAX:
3880 case EX_BADASSIGN:
3881 case EX_EXPFAIL:
3882 r = EXECUTION_FAILURE;
3883 break;
3884 default:
3885 r = EXECUTION_SUCCESS;
3886 break;
3888 return (r);
3891 static int
3892 execute_builtin (builtin, words, flags, subshell)
3893 sh_builtin_func_t *builtin;
3894 WORD_LIST *words;
3895 int flags, subshell;
3897 int old_e_flag, result, eval_unwind;
3898 int isbltinenv;
3899 char *error_trap;
3901 #if 0
3902 /* XXX -- added 12/11 */
3903 terminate_immediately++;
3904 #endif
3906 error_trap = 0;
3907 old_e_flag = exit_immediately_on_error;
3908 /* The eval builtin calls parse_and_execute, which does not know about
3909 the setting of flags, and always calls the execution functions with
3910 flags that will exit the shell on an error if -e is set. If the
3911 eval builtin is being called, and we're supposed to ignore the exit
3912 value of the command, we turn the -e flag off ourselves and disable
3913 the ERR trap, then restore them when the command completes. This is
3914 also a problem (as below) for the command and source/. builtins. */
3915 if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
3916 (builtin == eval_builtin || builtin == command_builtin || builtin == source_builtin))
3918 begin_unwind_frame ("eval_builtin");
3919 unwind_protect_int (exit_immediately_on_error);
3920 error_trap = TRAP_STRING (ERROR_TRAP);
3921 if (error_trap)
3923 error_trap = savestring (error_trap);
3924 add_unwind_protect (xfree, error_trap);
3925 add_unwind_protect (set_error_trap, error_trap);
3926 restore_default_signal (ERROR_TRAP);
3928 exit_immediately_on_error = 0;
3929 eval_unwind = 1;
3931 else
3932 eval_unwind = 0;
3934 /* The temporary environment for a builtin is supposed to apply to
3935 all commands executed by that builtin. Currently, this is a
3936 problem only with the `unset', `source' and `eval' builtins. */
3938 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
3940 if (isbltinenv)
3942 if (subshell == 0)
3943 begin_unwind_frame ("builtin_env");
3945 if (temporary_env)
3947 push_scope (VC_BLTNENV, temporary_env);
3948 if (subshell == 0)
3949 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
3950 temporary_env = (HASH_TABLE *)NULL;
3954 /* `return' does a longjmp() back to a saved environment in execute_function.
3955 If a variable assignment list preceded the command, and the shell is
3956 running in POSIX mode, we need to merge that into the shell_variables
3957 table, since `return' is a POSIX special builtin. */
3958 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3960 begin_unwind_frame ("return_temp_env");
3961 add_unwind_protect (merge_temporary_env, (char *)NULL);
3964 executing_builtin++;
3965 result = ((*builtin) (words->next));
3967 /* This shouldn't happen, but in case `return' comes back instead of
3968 longjmp'ing, we need to unwind. */
3969 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3970 discard_unwind_frame ("return_temp_env");
3972 if (subshell == 0 && isbltinenv)
3973 run_unwind_frame ("builtin_env");
3975 if (eval_unwind)
3977 exit_immediately_on_error += old_e_flag;
3978 if (error_trap)
3980 set_error_trap (error_trap);
3981 xfree (error_trap);
3983 discard_unwind_frame ("eval_builtin");
3986 #if 0
3987 /* XXX -- added 12/11 */
3988 terminate_immediately--;
3989 #endif
3991 return (result);
3994 static int
3995 execute_function (var, words, flags, fds_to_close, async, subshell)
3996 SHELL_VAR *var;
3997 WORD_LIST *words;
3998 int flags;
3999 struct fd_bitmap *fds_to_close;
4000 int async, subshell;
4002 int return_val, result;
4003 COMMAND *tc, *fc, *save_current;
4004 char *debug_trap, *error_trap, *return_trap;
4005 #if defined (ARRAY_VARS)
4006 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
4007 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
4008 #endif
4009 FUNCTION_DEF *shell_fn;
4010 char *sfile, *t;
4012 USE_VAR(fc);
4014 #if 0 /* for bash-4.2 */
4015 if (funcnest_max > 0 && funcnest >= funcnest_max)
4017 internal_error ("%s: maximum function nesting level exceeded (%d)", var->name, funcnest);
4018 jump_to_top_level (DISCARD);
4020 #endif
4022 #if defined (ARRAY_VARS)
4023 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4024 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4025 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4026 #endif
4028 tc = (COMMAND *)copy_command (function_cell (var));
4029 if (tc && (flags & CMD_IGNORE_RETURN))
4030 tc->flags |= CMD_IGNORE_RETURN;
4032 if (subshell == 0)
4034 begin_unwind_frame ("function_calling");
4035 push_context (var->name, subshell, temporary_env);
4036 add_unwind_protect (pop_context, (char *)NULL);
4037 unwind_protect_int (line_number);
4038 unwind_protect_int (return_catch_flag);
4039 unwind_protect_jmp_buf (return_catch);
4040 add_unwind_protect (dispose_command, (char *)tc);
4041 unwind_protect_pointer (this_shell_function);
4042 unwind_protect_int (loop_level);
4043 unwind_protect_int (funcnest);
4045 else
4046 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
4048 temporary_env = (HASH_TABLE *)NULL;
4050 this_shell_function = var;
4051 make_funcname_visible (1);
4053 debug_trap = TRAP_STRING(DEBUG_TRAP);
4054 error_trap = TRAP_STRING(ERROR_TRAP);
4055 return_trap = TRAP_STRING(RETURN_TRAP);
4057 /* The order of the unwind protects for debug_trap, error_trap and
4058 return_trap is important here! unwind-protect commands are run
4059 in reverse order of registration. If this causes problems, take
4060 out the xfree unwind-protect calls and live with the small memory leak. */
4062 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4063 if the function has the trace attribute set, it inherits the DEBUG trap */
4064 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4066 if (subshell == 0)
4068 debug_trap = savestring (debug_trap);
4069 add_unwind_protect (xfree, debug_trap);
4070 add_unwind_protect (set_debug_trap, debug_trap);
4072 restore_default_signal (DEBUG_TRAP);
4075 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4076 if (error_trap && error_trace_mode == 0)
4078 if (subshell == 0)
4080 error_trap = savestring (error_trap);
4081 add_unwind_protect (xfree, error_trap);
4082 add_unwind_protect (set_error_trap, error_trap);
4084 restore_default_signal (ERROR_TRAP);
4087 /* Shell functions inherit the RETURN trap if function tracing is on
4088 globally or on individually for this function. */
4089 #if 0
4090 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4091 #else
4092 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
4093 #endif
4095 if (subshell == 0)
4097 return_trap = savestring (return_trap);
4098 add_unwind_protect (xfree, return_trap);
4099 add_unwind_protect (set_return_trap, return_trap);
4101 restore_default_signal (RETURN_TRAP);
4104 funcnest++;
4105 #if defined (ARRAY_VARS)
4106 /* This is quite similar to the code in shell.c and elsewhere. */
4107 shell_fn = find_function_def (this_shell_function->name);
4108 sfile = shell_fn ? shell_fn->source_file : "";
4109 array_push (funcname_a, this_shell_function->name);
4111 array_push (bash_source_a, sfile);
4112 t = itos (executing_line_number ());
4113 array_push (bash_lineno_a, t);
4114 free (t);
4115 #endif
4117 /* The temporary environment for a function is supposed to apply to
4118 all commands executed within the function body. */
4120 remember_args (words->next, 1);
4122 /* Update BASH_ARGV and BASH_ARGC */
4123 if (debugging_mode)
4124 push_args (words->next);
4126 /* Number of the line on which the function body starts. */
4127 line_number = function_line_number = tc->line;
4129 #if defined (JOB_CONTROL)
4130 if (subshell)
4131 stop_pipeline (async, (COMMAND *)NULL);
4132 #endif
4134 fc = tc;
4136 return_catch_flag++;
4137 return_val = setjmp (return_catch);
4139 if (return_val)
4141 result = return_catch_value;
4142 /* Run the RETURN trap in the function's context. */
4143 save_current = currently_executing_command;
4144 run_return_trap ();
4145 currently_executing_command = save_current;
4147 else
4149 /* Run the debug trap here so we can trap at the start of a function's
4150 execution rather than the execution of the body's first command. */
4151 showing_function_line = 1;
4152 save_current = currently_executing_command;
4153 result = run_debug_trap ();
4154 #if defined (DEBUGGER)
4155 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4156 skip the command. */
4157 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
4159 showing_function_line = 0;
4160 currently_executing_command = save_current;
4161 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4163 /* Run the RETURN trap in the function's context */
4164 save_current = currently_executing_command;
4165 run_return_trap ();
4166 currently_executing_command = save_current;
4168 #else
4169 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4171 save_current = currently_executing_command;
4172 run_return_trap ();
4173 currently_executing_command = save_current;
4174 #endif
4175 showing_function_line = 0;
4178 /* Restore BASH_ARGC and BASH_ARGV */
4179 if (debugging_mode)
4180 pop_args ();
4182 if (subshell == 0)
4183 run_unwind_frame ("function_calling");
4185 #if defined (ARRAY_VARS)
4186 /* These two variables cannot be unset, and cannot be affected by the
4187 function. */
4188 array_pop (bash_source_a);
4189 array_pop (bash_lineno_a);
4191 /* FUNCNAME can be unset, and so can potentially be changed by the
4192 function. */
4193 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4194 if (nfv == funcname_v)
4195 array_pop (funcname_a);
4196 #endif
4198 if (variable_context == 0 || this_shell_function == 0)
4200 make_funcname_visible (0);
4201 #if defined (PROCESS_SUBSTITUTION)
4202 unlink_fifo_list ();
4203 #endif
4206 return (result);
4209 /* A convenience routine for use by other parts of the shell to execute
4210 a particular shell function. */
4212 execute_shell_function (var, words)
4213 SHELL_VAR *var;
4214 WORD_LIST *words;
4216 int ret;
4217 struct fd_bitmap *bitmap;
4219 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
4220 begin_unwind_frame ("execute-shell-function");
4221 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
4223 ret = execute_function (var, words, 0, bitmap, 0, 0);
4225 dispose_fd_bitmap (bitmap);
4226 discard_unwind_frame ("execute-shell-function");
4228 return ret;
4231 /* Execute a shell builtin or function in a subshell environment. This
4232 routine does not return; it only calls exit(). If BUILTIN is non-null,
4233 it points to a function to call to execute a shell builtin; otherwise
4234 VAR points at the body of a function to execute. WORDS is the arguments
4235 to the command, REDIRECTS specifies redirections to perform before the
4236 command is executed. */
4237 static void
4238 execute_subshell_builtin_or_function (words, redirects, builtin, var,
4239 pipe_in, pipe_out, async, fds_to_close,
4240 flags)
4241 WORD_LIST *words;
4242 REDIRECT *redirects;
4243 sh_builtin_func_t *builtin;
4244 SHELL_VAR *var;
4245 int pipe_in, pipe_out, async;
4246 struct fd_bitmap *fds_to_close;
4247 int flags;
4249 int result, r, funcvalue;
4250 #if defined (JOB_CONTROL)
4251 int jobs_hack;
4253 jobs_hack = (builtin == jobs_builtin) &&
4254 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
4255 #endif
4257 /* A subshell is neither a login shell nor interactive. */
4258 login_shell = interactive = 0;
4260 if (async)
4261 subshell_environment |= SUBSHELL_ASYNC;
4262 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4263 subshell_environment |= SUBSHELL_PIPE;
4265 maybe_make_export_env (); /* XXX - is this needed? */
4267 #if defined (JOB_CONTROL)
4268 /* Eradicate all traces of job control after we fork the subshell, so
4269 all jobs begun by this subshell are in the same process group as
4270 the shell itself. */
4272 /* Allow the output of `jobs' to be piped. */
4273 if (jobs_hack)
4274 kill_current_pipeline ();
4275 else
4276 without_job_control ();
4278 set_sigchld_handler ();
4279 #endif /* JOB_CONTROL */
4281 set_sigint_handler ();
4283 if (fds_to_close)
4284 close_fd_bitmap (fds_to_close);
4286 do_piping (pipe_in, pipe_out);
4288 if (do_redirections (redirects, RX_ACTIVE) != 0)
4289 exit (EXECUTION_FAILURE);
4291 if (builtin)
4293 /* Give builtins a place to jump back to on failure,
4294 so we don't go back up to main(). */
4295 result = setjmp (top_level);
4297 /* Give the return builtin a place to jump to when executed in a subshell
4298 or pipeline */
4299 funcvalue = 0;
4300 if (return_catch_flag && builtin == return_builtin)
4301 funcvalue = setjmp (return_catch);
4303 if (result == EXITPROG)
4304 exit (last_command_exit_value);
4305 else if (result)
4306 exit (EXECUTION_FAILURE);
4307 else if (funcvalue)
4308 exit (return_catch_value);
4309 else
4311 r = execute_builtin (builtin, words, flags, 1);
4312 fflush (stdout);
4313 if (r == EX_USAGE)
4314 r = EX_BADUSAGE;
4315 exit (r);
4318 else
4320 r = execute_function (var, words, flags, fds_to_close, async, 1);
4321 fflush (stdout);
4322 exit (r);
4326 /* Execute a builtin or function in the current shell context. If BUILTIN
4327 is non-null, it is the builtin command to execute, otherwise VAR points
4328 to the body of a function. WORDS are the command's arguments, REDIRECTS
4329 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
4330 file descriptors to close.
4332 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4333 not undone before this function returns. */
4334 static int
4335 execute_builtin_or_function (words, builtin, var, redirects,
4336 fds_to_close, flags)
4337 WORD_LIST *words;
4338 sh_builtin_func_t *builtin;
4339 SHELL_VAR *var;
4340 REDIRECT *redirects;
4341 struct fd_bitmap *fds_to_close;
4342 int flags;
4344 int result;
4345 REDIRECT *saved_undo_list;
4346 sh_builtin_func_t *saved_this_shell_builtin;
4348 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
4350 cleanup_redirects (redirection_undo_list);
4351 redirection_undo_list = (REDIRECT *)NULL;
4352 dispose_exec_redirects ();
4353 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
4356 saved_this_shell_builtin = this_shell_builtin;
4357 saved_undo_list = redirection_undo_list;
4359 /* Calling the "exec" builtin changes redirections forever. */
4360 if (builtin == exec_builtin)
4362 dispose_redirects (saved_undo_list);
4363 saved_undo_list = exec_redirection_undo_list;
4364 exec_redirection_undo_list = (REDIRECT *)NULL;
4366 else
4367 dispose_exec_redirects ();
4369 if (saved_undo_list)
4371 begin_unwind_frame ("saved redirects");
4372 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
4375 redirection_undo_list = (REDIRECT *)NULL;
4377 if (builtin)
4378 result = execute_builtin (builtin, words, flags, 0);
4379 else
4380 result = execute_function (var, words, flags, fds_to_close, 0, 0);
4382 /* We do this before undoing the effects of any redirections. */
4383 fflush (stdout);
4384 fpurge (stdout);
4385 if (ferror (stdout))
4386 clearerr (stdout);
4388 /* If we are executing the `command' builtin, but this_shell_builtin is
4389 set to `exec_builtin', we know that we have something like
4390 `command exec [redirection]', since otherwise `exec' would have
4391 overwritten the shell and we wouldn't get here. In this case, we
4392 want to behave as if the `command' builtin had not been specified
4393 and preserve the redirections. */
4394 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
4396 if (saved_undo_list)
4397 dispose_redirects (saved_undo_list);
4398 redirection_undo_list = exec_redirection_undo_list;
4399 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
4400 discard_unwind_frame ("saved_redirects");
4403 if (saved_undo_list)
4405 redirection_undo_list = saved_undo_list;
4406 discard_unwind_frame ("saved redirects");
4409 if (redirection_undo_list)
4411 cleanup_redirects (redirection_undo_list);
4412 redirection_undo_list = (REDIRECT *)NULL;
4415 return (result);
4418 void
4419 setup_async_signals ()
4421 #if defined (__BEOS__)
4422 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
4423 #endif
4425 #if defined (JOB_CONTROL)
4426 if (job_control == 0)
4427 #endif
4429 set_signal_handler (SIGINT, SIG_IGN);
4430 set_signal_ignored (SIGINT);
4431 set_signal_handler (SIGQUIT, SIG_IGN);
4432 set_signal_ignored (SIGQUIT);
4436 /* Execute a simple command that is hopefully defined in a disk file
4437 somewhere.
4439 1) fork ()
4440 2) connect pipes
4441 3) look up the command
4442 4) do redirections
4443 5) execve ()
4444 6) If the execve failed, see if the file has executable mode set.
4445 If so, and it isn't a directory, then execute its contents as
4446 a shell script.
4448 Note that the filename hashing stuff has to take place up here,
4449 in the parent. This is probably why the Bourne style shells
4450 don't handle it, since that would require them to go through
4451 this gnarly hair, for no good reason.
4453 NOTE: callers expect this to fork or exit(). */
4455 /* Name of a shell function to call when a command name is not found. */
4456 #ifndef NOTFOUND_HOOK
4457 # define NOTFOUND_HOOK "command_not_found_handle"
4458 #endif
4460 static void
4461 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
4462 async, fds_to_close, cmdflags)
4463 WORD_LIST *words;
4464 REDIRECT *redirects;
4465 char *command_line;
4466 int pipe_in, pipe_out, async;
4467 struct fd_bitmap *fds_to_close;
4468 int cmdflags;
4470 char *pathname, *command, **args;
4471 int nofork;
4472 pid_t pid;
4473 SHELL_VAR *hookf;
4474 WORD_LIST *wl;
4476 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
4477 pathname = words->word->word;
4479 #if defined (RESTRICTED_SHELL)
4480 command = (char *)NULL;
4481 if (restricted && mbschr (pathname, '/'))
4483 internal_error (_("%s: restricted: cannot specify `/' in command names"),
4484 pathname);
4485 last_command_exit_value = EXECUTION_FAILURE;
4487 /* If we're not going to fork below, we must already be in a child
4488 process or a context in which it's safe to call exit(2). */
4489 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4490 exit (last_command_exit_value);
4491 else
4492 goto parent_return;
4494 #endif /* RESTRICTED_SHELL */
4496 command = search_for_command (pathname);
4498 if (command)
4500 maybe_make_export_env ();
4501 put_command_name_into_env (command);
4504 /* We have to make the child before we check for the non-existence
4505 of COMMAND, since we want the error messages to be redirected. */
4506 /* If we can get away without forking and there are no pipes to deal with,
4507 don't bother to fork, just directly exec the command. */
4508 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4509 pid = 0;
4510 else
4511 pid = make_child (savestring (command_line), async);
4513 if (pid == 0)
4515 int old_interactive;
4517 #if 0
4518 /* This has been disabled for the time being. */
4519 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4520 if (posixly_correct == 0)
4521 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
4522 #endif
4523 #endif
4525 /* Cancel traps, in trap.c. */
4526 restore_original_signals ();
4528 /* restore_original_signals may have undone the work done
4529 by make_child to ensure that SIGINT and SIGQUIT are ignored
4530 in asynchronous children. */
4531 if (async)
4533 if ((cmdflags & CMD_STDIN_REDIR) &&
4534 pipe_in == NO_PIPE &&
4535 (stdin_redirects (redirects) == 0))
4536 async_redirect_stdin ();
4537 setup_async_signals ();
4540 /* This functionality is now provided by close-on-exec of the
4541 file descriptors manipulated by redirection and piping.
4542 Some file descriptors still need to be closed in all children
4543 because of the way bash does pipes; fds_to_close is a
4544 bitmap of all such file descriptors. */
4545 if (fds_to_close)
4546 close_fd_bitmap (fds_to_close);
4548 do_piping (pipe_in, pipe_out);
4550 old_interactive = interactive;
4551 if (async)
4552 interactive = 0;
4554 subshell_environment = SUBSHELL_FORK;
4556 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
4558 #if defined (PROCESS_SUBSTITUTION)
4559 /* Try to remove named pipes that may have been created as the
4560 result of redirections. */
4561 unlink_fifo_list ();
4562 #endif /* PROCESS_SUBSTITUTION */
4563 exit (EXECUTION_FAILURE);
4566 if (async)
4567 interactive = old_interactive;
4569 if (command == 0)
4571 hookf = find_function (NOTFOUND_HOOK);
4572 if (hookf == 0)
4574 internal_error (_("%s: command not found"), pathname);
4575 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
4578 wl = make_word_list (make_word (NOTFOUND_HOOK), words);
4579 exit (execute_shell_function (hookf, wl));
4582 /* Execve expects the command name to be in args[0]. So we
4583 leave it there, in the same format that the user used to
4584 type it in. */
4585 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
4586 exit (shell_execve (command, args, export_env));
4588 else
4590 parent_return:
4591 /* Make sure that the pipes are closed in the parent. */
4592 close_pipes (pipe_in, pipe_out);
4593 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4594 if (variable_context == 0)
4595 unlink_fifo_list ();
4596 #endif
4597 FREE (command);
4601 /* CPP defines to decide whether a particular index into the #! line
4602 corresponds to a valid interpreter name or argument character, or
4603 whitespace. The MSDOS define is to allow \r to be treated the same
4604 as \n. */
4606 #if !defined (MSDOS)
4607 # define STRINGCHAR(ind) \
4608 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4609 # define WHITECHAR(ind) \
4610 (ind < sample_len && whitespace (sample[ind]))
4611 #else /* MSDOS */
4612 # define STRINGCHAR(ind) \
4613 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4614 # define WHITECHAR(ind) \
4615 (ind < sample_len && whitespace (sample[ind]))
4616 #endif /* MSDOS */
4618 static char *
4619 getinterp (sample, sample_len, endp)
4620 char *sample;
4621 int sample_len, *endp;
4623 register int i;
4624 char *execname;
4625 int start;
4627 /* Find the name of the interpreter to exec. */
4628 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
4631 for (start = i; STRINGCHAR(i); i++)
4634 execname = substring (sample, start, i);
4636 if (endp)
4637 *endp = i;
4638 return execname;
4641 #if !defined (HAVE_HASH_BANG_EXEC)
4642 /* If the operating system on which we're running does not handle
4643 the #! executable format, then help out. SAMPLE is the text read
4644 from the file, SAMPLE_LEN characters. COMMAND is the name of
4645 the script; it and ARGS, the arguments given by the user, will
4646 become arguments to the specified interpreter. ENV is the environment
4647 to pass to the interpreter.
4649 The word immediately following the #! is the interpreter to execute.
4650 A single argument to the interpreter is allowed. */
4652 static int
4653 execute_shell_script (sample, sample_len, command, args, env)
4654 char *sample;
4655 int sample_len;
4656 char *command;
4657 char **args, **env;
4659 char *execname, *firstarg;
4660 int i, start, size_increment, larry;
4662 /* Find the name of the interpreter to exec. */
4663 execname = getinterp (sample, sample_len, &i);
4664 size_increment = 1;
4666 /* Now the argument, if any. */
4667 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
4670 /* If there is more text on the line, then it is an argument for the
4671 interpreter. */
4673 if (STRINGCHAR(i))
4675 for (start = i; STRINGCHAR(i); i++)
4677 firstarg = substring ((char *)sample, start, i);
4678 size_increment = 2;
4681 larry = strvec_len (args) + size_increment;
4682 args = strvec_resize (args, larry + 1);
4684 for (i = larry - 1; i; i--)
4685 args[i] = args[i - size_increment];
4687 args[0] = execname;
4688 if (firstarg)
4690 args[1] = firstarg;
4691 args[2] = command;
4693 else
4694 args[1] = command;
4696 args[larry] = (char *)NULL;
4698 return (shell_execve (execname, args, env));
4700 #undef STRINGCHAR
4701 #undef WHITECHAR
4703 #endif /* !HAVE_HASH_BANG_EXEC */
4705 static void
4706 initialize_subshell ()
4708 #if defined (ALIAS)
4709 /* Forget about any aliases that we knew of. We are in a subshell. */
4710 delete_all_aliases ();
4711 #endif /* ALIAS */
4713 #if defined (HISTORY)
4714 /* Forget about the history lines we have read. This is a non-interactive
4715 subshell. */
4716 history_lines_this_session = 0;
4717 #endif
4719 #if defined (JOB_CONTROL)
4720 /* Forget about the way job control was working. We are in a subshell. */
4721 without_job_control ();
4722 set_sigchld_handler ();
4723 init_job_stats ();
4724 #endif /* JOB_CONTROL */
4726 /* Reset the values of the shell flags and options. */
4727 reset_shell_flags ();
4728 reset_shell_options ();
4729 reset_shopt_options ();
4731 /* Zero out builtin_env, since this could be a shell script run from a
4732 sourced file with a temporary environment supplied to the `source/.'
4733 builtin. Such variables are not supposed to be exported (empirical
4734 testing with sh and ksh). Just throw it away; don't worry about a
4735 memory leak. */
4736 if (vc_isbltnenv (shell_variables))
4737 shell_variables = shell_variables->down;
4739 clear_unwind_protect_list (0);
4740 /* XXX -- are there other things we should be resetting here? */
4741 parse_and_execute_level = 0; /* nothing left to restore it */
4743 /* We're no longer inside a shell function. */
4744 variable_context = return_catch_flag = funcnest = 0;
4746 executing_list = 0; /* XXX */
4748 /* If we're not interactive, close the file descriptor from which we're
4749 reading the current shell script. */
4750 if (interactive_shell == 0)
4751 unset_bash_input (0);
4754 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4755 # define SETOSTYPE(x) __setostype(x)
4756 #else
4757 # define SETOSTYPE(x)
4758 #endif
4760 #define READ_SAMPLE_BUF(file, buf, len) \
4761 do \
4763 fd = open(file, O_RDONLY); \
4764 if (fd >= 0) \
4766 len = read (fd, buf, 80); \
4767 close (fd); \
4769 else \
4770 len = -1; \
4772 while (0)
4774 /* Call execve (), handling interpreting shell scripts, and handling
4775 exec failures. */
4777 shell_execve (command, args, env)
4778 char *command;
4779 char **args, **env;
4781 int larray, i, fd;
4782 char sample[80];
4783 int sample_len;
4785 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
4786 execve (command, args, env);
4787 i = errno; /* error from execve() */
4788 CHECK_TERMSIG;
4789 SETOSTYPE (1);
4791 /* If we get to this point, then start checking out the file.
4792 Maybe it is something we can hack ourselves. */
4793 if (i != ENOEXEC)
4795 if (file_isdir (command))
4796 internal_error (_("%s: is a directory"), command);
4797 else if (executable_file (command) == 0)
4799 errno = i;
4800 file_error (command);
4802 /* errors not involving the path argument to execve. */
4803 else if (i == E2BIG || i == ENOMEM)
4805 errno = i;
4806 file_error (command);
4808 else
4810 /* The file has the execute bits set, but the kernel refuses to
4811 run it for some reason. See why. */
4812 #if defined (HAVE_HASH_BANG_EXEC)
4813 READ_SAMPLE_BUF (command, sample, sample_len);
4814 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4816 char *interp;
4817 int ilen;
4819 interp = getinterp (sample, sample_len, (int *)NULL);
4820 ilen = strlen (interp);
4821 errno = i;
4822 if (interp[ilen - 1] == '\r')
4824 interp = xrealloc (interp, ilen + 2);
4825 interp[ilen - 1] = '^';
4826 interp[ilen] = 'M';
4827 interp[ilen + 1] = '\0';
4829 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
4830 FREE (interp);
4831 return (EX_NOEXEC);
4833 #endif
4834 errno = i;
4835 file_error (command);
4837 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
4840 /* This file is executable.
4841 If it begins with #!, then help out people with losing operating
4842 systems. Otherwise, check to see if it is a binary file by seeing
4843 if the contents of the first line (or up to 80 characters) are in the
4844 ASCII set. If it's a text file, execute the contents as shell commands,
4845 otherwise return 126 (EX_BINARY_FILE). */
4846 READ_SAMPLE_BUF (command, sample, sample_len);
4848 if (sample_len == 0)
4849 return (EXECUTION_SUCCESS);
4851 /* Is this supposed to be an executable script?
4852 If so, the format of the line is "#! interpreter [argument]".
4853 A single argument is allowed. The BSD kernel restricts
4854 the length of the entire line to 32 characters (32 bytes
4855 being the size of the BSD exec header), but we allow 80
4856 characters. */
4857 if (sample_len > 0)
4859 #if !defined (HAVE_HASH_BANG_EXEC)
4860 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4861 return (execute_shell_script (sample, sample_len, command, args, env));
4862 else
4863 #endif
4864 if (check_binary_file (sample, sample_len))
4866 internal_error (_("%s: cannot execute binary file"), command);
4867 return (EX_BINARY_FILE);
4871 /* We have committed to attempting to execute the contents of this file
4872 as shell commands. */
4874 initialize_subshell ();
4876 set_sigint_handler ();
4878 /* Insert the name of this shell into the argument list. */
4879 larray = strvec_len (args) + 1;
4880 args = strvec_resize (args, larray + 1);
4882 for (i = larray - 1; i; i--)
4883 args[i] = args[i - 1];
4885 args[0] = shell_name;
4886 args[1] = command;
4887 args[larray] = (char *)NULL;
4889 if (args[0][0] == '-')
4890 args[0]++;
4892 #if defined (RESTRICTED_SHELL)
4893 if (restricted)
4894 change_flag ('r', FLAG_OFF);
4895 #endif
4897 if (subshell_argv)
4899 /* Can't free subshell_argv[0]; that is shell_name. */
4900 for (i = 1; i < subshell_argc; i++)
4901 free (subshell_argv[i]);
4902 free (subshell_argv);
4905 dispose_command (currently_executing_command); /* XXX */
4906 currently_executing_command = (COMMAND *)NULL;
4908 subshell_argc = larray;
4909 subshell_argv = args;
4910 subshell_envp = env;
4912 unbind_args (); /* remove the positional parameters */
4914 longjmp (subshell_top_level, 1);
4915 /*NOTREACHED*/
4918 static int
4919 execute_intern_function (name, function)
4920 WORD_DESC *name;
4921 COMMAND *function;
4923 SHELL_VAR *var;
4925 if (check_identifier (name, posixly_correct) == 0)
4927 if (posixly_correct && interactive_shell == 0)
4929 last_command_exit_value = EX_BADUSAGE;
4930 jump_to_top_level (ERREXIT);
4932 return (EXECUTION_FAILURE);
4935 var = find_function (name->word);
4936 if (var && (readonly_p (var) || noassign_p (var)))
4938 if (readonly_p (var))
4939 internal_error (_("%s: readonly function"), var->name);
4940 return (EXECUTION_FAILURE);
4943 bind_function (name->word, function);
4944 return (EXECUTION_SUCCESS);
4947 #if defined (INCLUDE_UNUSED)
4948 #if defined (PROCESS_SUBSTITUTION)
4949 void
4950 close_all_files ()
4952 register int i, fd_table_size;
4954 fd_table_size = getdtablesize ();
4955 if (fd_table_size > 256) /* clamp to a reasonable value */
4956 fd_table_size = 256;
4958 for (i = 3; i < fd_table_size; i++)
4959 close (i);
4961 #endif /* PROCESS_SUBSTITUTION */
4962 #endif
4964 static void
4965 close_pipes (in, out)
4966 int in, out;
4968 if (in >= 0)
4969 close (in);
4970 if (out >= 0)
4971 close (out);
4974 static void
4975 dup_error (oldd, newd)
4976 int oldd, newd;
4978 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
4981 /* Redirect input and output to be from and to the specified pipes.
4982 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4983 static void
4984 do_piping (pipe_in, pipe_out)
4985 int pipe_in, pipe_out;
4987 if (pipe_in != NO_PIPE)
4989 if (dup2 (pipe_in, 0) < 0)
4990 dup_error (pipe_in, 0);
4991 if (pipe_in > 0)
4992 close (pipe_in);
4994 if (pipe_out != NO_PIPE)
4996 if (pipe_out != REDIRECT_BOTH)
4998 if (dup2 (pipe_out, 1) < 0)
4999 dup_error (pipe_out, 1);
5000 if (pipe_out == 0 || pipe_out > 1)
5001 close (pipe_out);
5003 else
5005 if (dup2 (1, 2) < 0)
5006 dup_error (1, 2);