Patch-ID: bash32-030
[bash.git] / execute_cmd.c
blobc7a7d3beed9e9dd36c9b6dd4d221d38871407a6e
1 /* execute_cmd.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2007 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
20 #include "config.h"
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
23 #pragma alloca
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
26 #include <stdio.h>
27 #include "chartypes.h"
28 #include "bashtypes.h"
29 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
30 # include <sys/file.h>
31 #endif
32 #include "filecntl.h"
33 #include "posixstat.h"
34 #include <signal.h>
35 #ifndef _MINIX
36 # include <sys/param.h>
37 #endif
39 #if defined (HAVE_UNISTD_H)
40 # include <unistd.h>
41 #endif
43 #include "posixtime.h"
45 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
46 # include <sys/resource.h>
47 #endif
49 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
50 # include <sys/times.h>
51 #endif
53 #include <errno.h>
55 #if !defined (errno)
56 extern int errno;
57 #endif
59 #include "bashansi.h"
60 #include "bashintl.h"
62 #include "memalloc.h"
63 #include "shell.h"
64 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
65 #include "flags.h"
66 #include "builtins.h"
67 #include "hashlib.h"
68 #include "jobs.h"
69 #include "execute_cmd.h"
70 #include "findcmd.h"
71 #include "redir.h"
72 #include "trap.h"
73 #include "pathexp.h"
74 #include "hashcmd.h"
76 #if defined (COND_COMMAND)
77 # include "test.h"
78 #endif
80 #include "builtins/common.h"
81 #include "builtins/builtext.h" /* list of builtins */
83 #include <glob/strmatch.h>
84 #include <tilde/tilde.h>
86 #if defined (BUFFERED_INPUT)
87 # include "input.h"
88 #endif
90 #if defined (ALIAS)
91 # include "alias.h"
92 #endif
94 #if defined (HISTORY)
95 # include "bashhist.h"
96 #endif
98 extern int posixly_correct;
99 extern int breaking, continuing, loop_level;
100 extern int expand_aliases;
101 extern int parse_and_execute_level, running_trap;
102 extern int command_string_index, line_number;
103 extern int dot_found_in_search;
104 extern int already_making_children;
105 extern int tempenv_assign_error;
106 extern char *the_printed_command, *shell_name;
107 extern pid_t last_command_subst_pid;
108 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
109 extern char **subshell_argv, **subshell_envp;
110 extern int subshell_argc;
111 #if 0
112 extern char *glob_argv_flags;
113 #endif
115 extern int close __P((int));
117 /* Static functions defined and used in this file. */
118 static void close_pipes __P((int, int));
119 static void do_piping __P((int, int));
120 static void bind_lastarg __P((char *));
121 static int shell_control_structure __P((enum command_type));
122 static void cleanup_redirects __P((REDIRECT *));
124 #if defined (JOB_CONTROL)
125 static int restore_signal_mask __P((sigset_t *));
126 #endif
128 static void async_redirect_stdin __P((void));
130 static int builtin_status __P((int));
132 static int execute_for_command __P((FOR_COM *));
133 #if defined (SELECT_COMMAND)
134 static int print_index_and_element __P((int, int, WORD_LIST *));
135 static void indent __P((int, int));
136 static void print_select_list __P((WORD_LIST *, int, int, int));
137 static char *select_query __P((WORD_LIST *, int, char *, int));
138 static int execute_select_command __P((SELECT_COM *));
139 #endif
140 #if defined (DPAREN_ARITHMETIC)
141 static int execute_arith_command __P((ARITH_COM *));
142 #endif
143 #if defined (COND_COMMAND)
144 static int execute_cond_node __P((COND_COM *));
145 static int execute_cond_command __P((COND_COM *));
146 #endif
147 #if defined (COMMAND_TIMING)
148 static int mkfmt __P((char *, int, int, time_t, int));
149 static void print_formatted_time __P((FILE *, char *,
150 time_t, int, time_t, int,
151 time_t, int, int));
152 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
153 #endif
154 #if defined (ARITH_FOR_COMMAND)
155 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
156 static int execute_arith_for_command __P((ARITH_FOR_COM *));
157 #endif
158 static int execute_case_command __P((CASE_COM *));
159 static int execute_while_command __P((WHILE_COM *));
160 static int execute_until_command __P((WHILE_COM *));
161 static int execute_while_or_until __P((WHILE_COM *, int));
162 static int execute_if_command __P((IF_COM *));
163 static int execute_null_command __P((REDIRECT *, int, int, int));
164 static void fix_assignment_words __P((WORD_LIST *));
165 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
166 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
167 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
168 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
169 SHELL_VAR *,
170 REDIRECT *, struct fd_bitmap *, int));
171 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
172 sh_builtin_func_t *,
173 SHELL_VAR *,
174 int, int, int,
175 struct fd_bitmap *,
176 int));
177 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
178 int, int, int, struct fd_bitmap *, int));
180 static char *getinterp __P((char *, int, int *));
181 static void initialize_subshell __P((void));
182 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
184 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
186 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
188 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
190 /* The line number that the currently executing function starts on. */
191 static int function_line_number;
193 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
194 so that reader_loop can set it to zero before executing a command. */
195 int stdin_redir;
197 /* The name of the command that is currently being executed.
198 `test' needs this, for example. */
199 char *this_command_name;
201 /* The printed representation of the currently-executing command (same as
202 the_printed_command), except when a trap is being executed. Useful for
203 a debugger to know where exactly the program is currently executing. */
204 char *the_printed_command_except_trap;
206 static COMMAND *currently_executing_command;
208 struct stat SB; /* used for debugging */
210 static int special_builtin_failed;
212 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
213 number containing the function name. Used by executing_line_number to
214 report the correct line number. Kind of a hack. */
215 static int showing_function_line;
217 static int line_number_for_err_trap;
219 /* For catching RETURN in a function. */
220 int return_catch_flag;
221 int return_catch_value;
222 procenv_t return_catch;
224 /* The value returned by the last synchronous command. */
225 int last_command_exit_value;
227 /* Whether or not the last command (corresponding to last_command_exit_value)
228 was terminated by a signal, and, if so, which one. */
229 int last_command_exit_signal;
231 /* The list of redirections to perform which will undo the redirections
232 that I made in the shell. */
233 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
235 /* The list of redirections to perform which will undo the internal
236 redirections performed by the `exec' builtin. These are redirections
237 that must be undone even when exec discards redirection_undo_list. */
238 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
240 /* Non-zero if we have just forked and are currently running in a subshell
241 environment. */
242 int subshell_environment;
244 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
245 int subshell_level = 0;
247 /* Currently-executing shell function. */
248 SHELL_VAR *this_shell_function;
250 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
251 int match_ignore_case = 0;
253 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
255 #define FD_BITMAP_DEFAULT_SIZE 32
257 /* Functions to allocate and deallocate the structures used to pass
258 information from the shell to its children about file descriptors
259 to close. */
260 struct fd_bitmap *
261 new_fd_bitmap (size)
262 int size;
264 struct fd_bitmap *ret;
266 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
268 ret->size = size;
270 if (size)
272 ret->bitmap = (char *)xmalloc (size);
273 memset (ret->bitmap, '\0', size);
275 else
276 ret->bitmap = (char *)NULL;
277 return (ret);
280 void
281 dispose_fd_bitmap (fdbp)
282 struct fd_bitmap *fdbp;
284 FREE (fdbp->bitmap);
285 free (fdbp);
288 void
289 close_fd_bitmap (fdbp)
290 struct fd_bitmap *fdbp;
292 register int i;
294 if (fdbp)
296 for (i = 0; i < fdbp->size; i++)
297 if (fdbp->bitmap[i])
299 close (i);
300 fdbp->bitmap[i] = 0;
305 /* Return the line number of the currently executing command. */
307 executing_line_number ()
309 if (executing && showing_function_line == 0 &&
310 (variable_context == 0 || interactive_shell == 0) &&
311 currently_executing_command)
313 #if defined (COND_COMMAND)
314 if (currently_executing_command->type == cm_cond)
315 return currently_executing_command->value.Cond->line;
316 #endif
317 #if defined (DPAREN_ARITHMETIC)
318 else if (currently_executing_command->type == cm_arith)
319 return currently_executing_command->value.Arith->line;
320 #endif
321 #if defined (ARITH_FOR_COMMAND)
322 else if (currently_executing_command->type == cm_arith_for)
323 return currently_executing_command->value.ArithFor->line;
324 #endif
326 return line_number;
328 else
329 return line_number;
332 /* Execute the command passed in COMMAND. COMMAND is exactly what
333 read_command () places into GLOBAL_COMMAND. See "command.h" for the
334 details of the command structure.
336 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
337 return values. Executing a command with nothing in it returns
338 EXECUTION_SUCCESS. */
340 execute_command (command)
341 COMMAND *command;
343 struct fd_bitmap *bitmap;
344 int result;
346 current_fds_to_close = (struct fd_bitmap *)NULL;
347 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
348 begin_unwind_frame ("execute-command");
349 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
351 /* Just do the command, but not asynchronously. */
352 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
354 dispose_fd_bitmap (bitmap);
355 discard_unwind_frame ("execute-command");
357 #if defined (PROCESS_SUBSTITUTION)
358 /* don't unlink fifos if we're in a shell function; wait until the function
359 returns. */
360 if (variable_context == 0)
361 unlink_fifo_list ();
362 #endif /* PROCESS_SUBSTITUTION */
364 QUIT;
365 return (result);
368 /* Return 1 if TYPE is a shell control structure type. */
369 static int
370 shell_control_structure (type)
371 enum command_type type;
373 switch (type)
375 #if defined (ARITH_FOR_COMMAND)
376 case cm_arith_for:
377 #endif
378 #if defined (SELECT_COMMAND)
379 case cm_select:
380 #endif
381 #if defined (DPAREN_ARITHMETIC)
382 case cm_arith:
383 #endif
384 #if defined (COND_COMMAND)
385 case cm_cond:
386 #endif
387 case cm_case:
388 case cm_while:
389 case cm_until:
390 case cm_if:
391 case cm_for:
392 case cm_group:
393 case cm_function_def:
394 return (1);
396 default:
397 return (0);
401 /* A function to use to unwind_protect the redirection undo list
402 for loops. */
403 static void
404 cleanup_redirects (list)
405 REDIRECT *list;
407 do_redirections (list, RX_ACTIVE);
408 dispose_redirects (list);
411 #if 0
412 /* Function to unwind_protect the redirections for functions and builtins. */
413 static void
414 cleanup_func_redirects (list)
415 REDIRECT *list;
417 do_redirections (list, RX_ACTIVE);
419 #endif
421 void
422 dispose_exec_redirects ()
424 if (exec_redirection_undo_list)
426 dispose_redirects (exec_redirection_undo_list);
427 exec_redirection_undo_list = (REDIRECT *)NULL;
431 #if defined (JOB_CONTROL)
432 /* A function to restore the signal mask to its proper value when the shell
433 is interrupted or errors occur while creating a pipeline. */
434 static int
435 restore_signal_mask (set)
436 sigset_t *set;
438 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
440 #endif /* JOB_CONTROL */
442 #ifdef DEBUG
443 /* A debugging function that can be called from gdb, for instance. */
444 void
445 open_files ()
447 register int i;
448 int f, fd_table_size;
450 fd_table_size = getdtablesize ();
452 fprintf (stderr, "pid %ld open files:", (long)getpid ());
453 for (i = 3; i < fd_table_size; i++)
455 if ((f = fcntl (i, F_GETFD, 0)) != -1)
456 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
458 fprintf (stderr, "\n");
460 #endif
462 static void
463 async_redirect_stdin ()
465 int fd;
467 fd = open ("/dev/null", O_RDONLY);
468 if (fd > 0)
470 dup2 (fd, 0);
471 close (fd);
473 else if (fd < 0)
474 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
477 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
479 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
480 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
481 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
482 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
483 from and where it goes. They can have the value of NO_PIPE, which means
484 I/O is stdin/stdout.
485 FDS_TO_CLOSE is a list of file descriptors to close once the child has
486 been forked. This list often contains the unusable sides of pipes, etc.
488 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
489 return values. Executing a command with nothing in it returns
490 EXECUTION_SUCCESS. */
492 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
493 fds_to_close)
494 COMMAND *command;
495 int asynchronous;
496 int pipe_in, pipe_out;
497 struct fd_bitmap *fds_to_close;
499 int exec_result, invert, ignore_return, was_error_trap;
500 REDIRECT *my_undo_list, *exec_undo_list;
501 volatile int last_pid;
502 volatile int save_line_number;
504 if (command == 0 || breaking || continuing || read_but_dont_execute)
505 return (EXECUTION_SUCCESS);
507 QUIT;
508 run_pending_traps ();
510 #if 0
511 if (running_trap == 0)
512 #endif
513 currently_executing_command = command;
515 invert = (command->flags & CMD_INVERT_RETURN) != 0;
517 /* If we're inverting the return value and `set -e' has been executed,
518 we don't want a failing command to inadvertently cause the shell
519 to exit. */
520 if (exit_immediately_on_error && invert) /* XXX */
521 command->flags |= CMD_IGNORE_RETURN; /* XXX */
523 exec_result = EXECUTION_SUCCESS;
525 /* If a command was being explicitly run in a subshell, or if it is
526 a shell control-structure, and it has a pipe, then we do the command
527 in a subshell. */
528 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
529 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
531 if (command->type == cm_subshell ||
532 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
533 (shell_control_structure (command->type) &&
534 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
536 pid_t paren_pid;
538 /* Fork a subshell, turn off the subshell bit, turn off job
539 control and call execute_command () on the command again. */
540 paren_pid = make_child (savestring (make_command_string (command)),
541 asynchronous);
542 if (paren_pid == 0)
543 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
544 /* NOTREACHED */
545 else
547 close_pipes (pipe_in, pipe_out);
549 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
550 unlink_fifo_list ();
551 #endif
552 /* If we are part of a pipeline, and not the end of the pipeline,
553 then we should simply return and let the last command in the
554 pipe be waited for. If we are not in a pipeline, or are the
555 last command in the pipeline, then we wait for the subshell
556 and return its exit status as usual. */
557 if (pipe_out != NO_PIPE)
558 return (EXECUTION_SUCCESS);
560 stop_pipeline (asynchronous, (COMMAND *)NULL);
562 if (asynchronous == 0)
564 last_command_exit_value = wait_for (paren_pid);
566 /* If we have to, invert the return value. */
567 if (invert)
568 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
569 ? EXECUTION_FAILURE
570 : EXECUTION_SUCCESS);
571 else
572 exec_result = last_command_exit_value;
574 return (last_command_exit_value = exec_result);
576 else
578 DESCRIBE_PID (paren_pid);
580 run_pending_traps ();
582 return (EXECUTION_SUCCESS);
587 #if defined (COMMAND_TIMING)
588 if (command->flags & CMD_TIME_PIPELINE)
590 if (asynchronous)
592 command->flags |= CMD_FORCE_SUBSHELL;
593 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
595 else
597 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
598 #if 0
599 if (running_trap == 0)
600 #endif
601 currently_executing_command = (COMMAND *)NULL;
603 return (exec_result);
605 #endif /* COMMAND_TIMING */
607 if (shell_control_structure (command->type) && command->redirects)
608 stdin_redir = stdin_redirects (command->redirects);
610 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
611 redirection.) */
612 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
614 cleanup_redirects (redirection_undo_list);
615 redirection_undo_list = (REDIRECT *)NULL;
616 dispose_exec_redirects ();
617 return (last_command_exit_value = EXECUTION_FAILURE);
620 if (redirection_undo_list)
622 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
623 dispose_redirects (redirection_undo_list);
624 redirection_undo_list = (REDIRECT *)NULL;
626 else
627 my_undo_list = (REDIRECT *)NULL;
629 if (exec_redirection_undo_list)
631 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
632 dispose_redirects (exec_redirection_undo_list);
633 exec_redirection_undo_list = (REDIRECT *)NULL;
635 else
636 exec_undo_list = (REDIRECT *)NULL;
638 if (my_undo_list || exec_undo_list)
639 begin_unwind_frame ("loop_redirections");
641 if (my_undo_list)
642 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
644 if (exec_undo_list)
645 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
647 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
649 QUIT;
651 switch (command->type)
653 case cm_simple:
655 save_line_number = line_number;
656 /* We can't rely on variables retaining their values across a
657 call to execute_simple_command if a longjmp occurs as the
658 result of a `return' builtin. This is true for sure with gcc. */
659 #if defined (RECYCLES_PIDS)
660 last_made_pid = NO_PID;
661 #endif
662 last_pid = last_made_pid;
663 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
665 if (ignore_return && command->value.Simple)
666 command->value.Simple->flags |= CMD_IGNORE_RETURN;
667 if (command->flags & CMD_STDIN_REDIR)
668 command->value.Simple->flags |= CMD_STDIN_REDIR;
670 line_number_for_err_trap = line_number = command->value.Simple->line;
671 exec_result =
672 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
673 asynchronous, fds_to_close);
674 line_number = save_line_number;
676 /* The temporary environment should be used for only the simple
677 command immediately following its definition. */
678 dispose_used_env_vars ();
680 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
681 /* Reclaim memory allocated with alloca () on machines which
682 may be using the alloca emulation code. */
683 (void) alloca (0);
684 #endif /* (ultrix && mips) || C_ALLOCA */
686 /* If we forked to do the command, then we must wait_for ()
687 the child. */
689 /* XXX - this is something to watch out for if there are problems
690 when the shell is compiled without job control. */
691 if (already_making_children && pipe_out == NO_PIPE &&
692 last_made_pid != last_pid)
694 stop_pipeline (asynchronous, (COMMAND *)NULL);
696 if (asynchronous)
698 DESCRIBE_PID (last_made_pid);
700 else
701 #if !defined (JOB_CONTROL)
702 /* Do not wait for asynchronous processes started from
703 startup files. */
704 if (last_made_pid != last_asynchronous_pid)
705 #endif
706 /* When executing a shell function that executes other
707 commands, this causes the last simple command in
708 the function to be waited for twice. This also causes
709 subshells forked to execute builtin commands (e.g., in
710 pipelines) to be waited for twice. */
711 exec_result = wait_for (last_made_pid);
715 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
717 last_command_exit_value = exec_result;
718 run_error_trap ();
721 if (ignore_return == 0 && invert == 0 &&
722 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
723 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
725 last_command_exit_value = exec_result;
726 run_pending_traps ();
727 jump_to_top_level (ERREXIT);
730 break;
732 case cm_for:
733 if (ignore_return)
734 command->value.For->flags |= CMD_IGNORE_RETURN;
735 exec_result = execute_for_command (command->value.For);
736 break;
738 #if defined (ARITH_FOR_COMMAND)
739 case cm_arith_for:
740 if (ignore_return)
741 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
742 exec_result = execute_arith_for_command (command->value.ArithFor);
743 break;
744 #endif
746 #if defined (SELECT_COMMAND)
747 case cm_select:
748 if (ignore_return)
749 command->value.Select->flags |= CMD_IGNORE_RETURN;
750 exec_result = execute_select_command (command->value.Select);
751 break;
752 #endif
754 case cm_case:
755 if (ignore_return)
756 command->value.Case->flags |= CMD_IGNORE_RETURN;
757 exec_result = execute_case_command (command->value.Case);
758 break;
760 case cm_while:
761 if (ignore_return)
762 command->value.While->flags |= CMD_IGNORE_RETURN;
763 exec_result = execute_while_command (command->value.While);
764 break;
766 case cm_until:
767 if (ignore_return)
768 command->value.While->flags |= CMD_IGNORE_RETURN;
769 exec_result = execute_until_command (command->value.While);
770 break;
772 case cm_if:
773 if (ignore_return)
774 command->value.If->flags |= CMD_IGNORE_RETURN;
775 exec_result = execute_if_command (command->value.If);
776 break;
778 case cm_group:
780 /* This code can be executed from either of two paths: an explicit
781 '{}' command, or via a function call. If we are executed via a
782 function call, we have already taken care of the function being
783 executed in the background (down there in execute_simple_command ()),
784 and this command should *not* be marked as asynchronous. If we
785 are executing a regular '{}' group command, and asynchronous == 1,
786 we must want to execute the whole command in the background, so we
787 need a subshell, and we want the stuff executed in that subshell
788 (this group command) to be executed in the foreground of that
789 subshell (i.e. there will not be *another* subshell forked).
791 What we do is to force a subshell if asynchronous, and then call
792 execute_command_internal again with asynchronous still set to 1,
793 but with the original group command, so the printed command will
794 look right.
796 The code above that handles forking off subshells will note that
797 both subshell and async are on, and turn off async in the child
798 after forking the subshell (but leave async set in the parent, so
799 the normal call to describe_pid is made). This turning off
800 async is *crucial*; if it is not done, this will fall into an
801 infinite loop of executions through this spot in subshell after
802 subshell until the process limit is exhausted. */
804 if (asynchronous)
806 command->flags |= CMD_FORCE_SUBSHELL;
807 exec_result =
808 execute_command_internal (command, 1, pipe_in, pipe_out,
809 fds_to_close);
811 else
813 if (ignore_return && command->value.Group->command)
814 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
815 exec_result =
816 execute_command_internal (command->value.Group->command,
817 asynchronous, pipe_in, pipe_out,
818 fds_to_close);
820 break;
822 case cm_connection:
823 exec_result = execute_connection (command, asynchronous,
824 pipe_in, pipe_out, fds_to_close);
825 break;
827 #if defined (DPAREN_ARITHMETIC)
828 case cm_arith:
829 if (ignore_return)
830 command->value.Arith->flags |= CMD_IGNORE_RETURN;
831 exec_result = execute_arith_command (command->value.Arith);
832 break;
833 #endif
835 #if defined (COND_COMMAND)
836 case cm_cond:
837 if (ignore_return)
838 command->value.Cond->flags |= CMD_IGNORE_RETURN;
839 save_line_number = line_number;
840 exec_result = execute_cond_command (command->value.Cond);
841 line_number = save_line_number;
842 break;
843 #endif
845 case cm_function_def:
846 exec_result = execute_intern_function (command->value.Function_def->name,
847 command->value.Function_def->command);
848 break;
850 default:
851 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
854 if (my_undo_list)
856 do_redirections (my_undo_list, RX_ACTIVE);
857 dispose_redirects (my_undo_list);
860 if (exec_undo_list)
861 dispose_redirects (exec_undo_list);
863 if (my_undo_list || exec_undo_list)
864 discard_unwind_frame ("loop_redirections");
866 /* Invert the return value if we have to */
867 if (invert)
868 exec_result = (exec_result == EXECUTION_SUCCESS)
869 ? EXECUTION_FAILURE
870 : EXECUTION_SUCCESS;
872 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
873 /* This is where we set PIPESTATUS from the exit status of the appropriate
874 compound commands (the ones that look enough like simple commands to
875 cause confusion). We might be able to optimize by not doing this if
876 subshell_environment != 0. */
877 switch (command->type)
879 # if defined (DPAREN_ARITHMETIC)
880 case cm_arith:
881 # endif
882 # if defined (COND_COMMAND)
883 case cm_cond:
884 # endif
885 set_pipestatus_from_exit (exec_result);
886 break;
888 #endif
890 last_command_exit_value = exec_result;
891 run_pending_traps ();
892 #if 0
893 if (running_trap == 0)
894 #endif
895 currently_executing_command = (COMMAND *)NULL;
896 return (last_command_exit_value);
899 #if defined (COMMAND_TIMING)
901 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
902 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
903 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
904 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
905 #endif
907 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
908 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
910 static int precs[] = { 0, 100, 10, 1 };
912 /* Expand one `%'-prefixed escape sequence from a time format string. */
913 static int
914 mkfmt (buf, prec, lng, sec, sec_fraction)
915 char *buf;
916 int prec, lng;
917 time_t sec;
918 int sec_fraction;
920 time_t min;
921 char abuf[INT_STRLEN_BOUND(time_t) + 1];
922 int ind, aind;
924 ind = 0;
925 abuf[sizeof(abuf) - 1] = '\0';
927 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
928 if (lng)
930 min = sec / 60;
931 sec %= 60;
932 aind = sizeof(abuf) - 2;
934 abuf[aind--] = (min % 10) + '0';
935 while (min /= 10);
936 aind++;
937 while (abuf[aind])
938 buf[ind++] = abuf[aind++];
939 buf[ind++] = 'm';
942 /* Now add the seconds. */
943 aind = sizeof (abuf) - 2;
945 abuf[aind--] = (sec % 10) + '0';
946 while (sec /= 10);
947 aind++;
948 while (abuf[aind])
949 buf[ind++] = abuf[aind++];
951 /* We want to add a decimal point and PREC places after it if PREC is
952 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
953 and 999. */
954 if (prec != 0)
956 buf[ind++] = '.';
957 for (aind = 1; aind <= prec; aind++)
959 buf[ind++] = (sec_fraction / precs[aind]) + '0';
960 sec_fraction %= precs[aind];
964 if (lng)
965 buf[ind++] = 's';
966 buf[ind] = '\0';
968 return (ind);
971 /* Interpret the format string FORMAT, interpolating the following escape
972 sequences:
973 %[prec][l][RUS]
975 where the optional `prec' is a precision, meaning the number of
976 characters after the decimal point, the optional `l' means to format
977 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
978 and the last character is one of
980 R number of seconds of `real' time
981 U number of seconds of `user' time
982 S number of seconds of `system' time
984 An occurrence of `%%' in the format string is translated to a `%'. The
985 result is printed to FP, a pointer to a FILE. The other variables are
986 the seconds and thousandths of a second of real, user, and system time,
987 resectively. */
988 static void
989 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
990 FILE *fp;
991 char *format;
992 time_t rs;
993 int rsf;
994 time_t us;
995 int usf;
996 time_t ss;
997 int ssf, cpu;
999 int prec, lng, len;
1000 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1001 time_t sum;
1002 int sum_frac;
1003 int sindex, ssize;
1005 len = strlen (format);
1006 ssize = (len + 64) - (len % 64);
1007 str = (char *)xmalloc (ssize);
1008 sindex = 0;
1010 for (s = format; *s; s++)
1012 if (*s != '%' || s[1] == '\0')
1014 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1015 str[sindex++] = *s;
1017 else if (s[1] == '%')
1019 s++;
1020 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1021 str[sindex++] = *s;
1023 else if (s[1] == 'P')
1025 s++;
1026 if (cpu > 10000)
1027 cpu = 10000;
1028 sum = cpu / 100;
1029 sum_frac = (cpu % 100) * 10;
1030 len = mkfmt (ts, 2, 0, sum, sum_frac);
1031 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1032 strcpy (str + sindex, ts);
1033 sindex += len;
1035 else
1037 prec = 3; /* default is three places past the decimal point. */
1038 lng = 0; /* default is to not use minutes or append `s' */
1039 s++;
1040 if (DIGIT (*s)) /* `precision' */
1042 prec = *s++ - '0';
1043 if (prec > 3) prec = 3;
1045 if (*s == 'l') /* `length extender' */
1047 lng = 1;
1048 s++;
1050 if (*s == 'R' || *s == 'E')
1051 len = mkfmt (ts, prec, lng, rs, rsf);
1052 else if (*s == 'U')
1053 len = mkfmt (ts, prec, lng, us, usf);
1054 else if (*s == 'S')
1055 len = mkfmt (ts, prec, lng, ss, ssf);
1056 else
1058 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1059 free (str);
1060 return;
1062 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1063 strcpy (str + sindex, ts);
1064 sindex += len;
1068 str[sindex] = '\0';
1069 fprintf (fp, "%s\n", str);
1070 fflush (fp);
1072 free (str);
1075 static int
1076 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1077 COMMAND *command;
1078 int asynchronous, pipe_in, pipe_out;
1079 struct fd_bitmap *fds_to_close;
1081 int rv, posix_time, old_flags;
1082 time_t rs, us, ss;
1083 int rsf, usf, ssf;
1084 int cpu;
1085 char *time_format;
1087 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1088 struct timeval real, user, sys;
1089 struct timeval before, after;
1090 # if defined (HAVE_STRUCT_TIMEZONE)
1091 struct timezone dtz; /* posix doesn't define this */
1092 # endif
1093 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1094 #else
1095 # if defined (HAVE_TIMES)
1096 clock_t tbefore, tafter, real, user, sys;
1097 struct tms before, after;
1098 # endif
1099 #endif
1101 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1102 # if defined (HAVE_STRUCT_TIMEZONE)
1103 gettimeofday (&before, &dtz);
1104 # else
1105 gettimeofday (&before, (void *)NULL);
1106 # endif /* !HAVE_STRUCT_TIMEZONE */
1107 getrusage (RUSAGE_SELF, &selfb);
1108 getrusage (RUSAGE_CHILDREN, &kidsb);
1109 #else
1110 # if defined (HAVE_TIMES)
1111 tbefore = times (&before);
1112 # endif
1113 #endif
1115 posix_time = (command->flags & CMD_TIME_POSIX);
1117 old_flags = command->flags;
1118 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1119 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1120 command->flags = old_flags;
1122 rs = us = ss = 0;
1123 rsf = usf = ssf = cpu = 0;
1125 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1126 # if defined (HAVE_STRUCT_TIMEZONE)
1127 gettimeofday (&after, &dtz);
1128 # else
1129 gettimeofday (&after, (void *)NULL);
1130 # endif /* !HAVE_STRUCT_TIMEZONE */
1131 getrusage (RUSAGE_SELF, &selfa);
1132 getrusage (RUSAGE_CHILDREN, &kidsa);
1134 difftimeval (&real, &before, &after);
1135 timeval_to_secs (&real, &rs, &rsf);
1137 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1138 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1139 timeval_to_secs (&user, &us, &usf);
1141 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1142 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1143 timeval_to_secs (&sys, &ss, &ssf);
1145 cpu = timeval_to_cpu (&real, &user, &sys);
1146 #else
1147 # if defined (HAVE_TIMES)
1148 tafter = times (&after);
1150 real = tafter - tbefore;
1151 clock_t_to_secs (real, &rs, &rsf);
1153 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1154 clock_t_to_secs (user, &us, &usf);
1156 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1157 clock_t_to_secs (sys, &ss, &ssf);
1159 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1161 # else
1162 rs = us = ss = 0;
1163 rsf = usf = ssf = cpu = 0;
1164 # endif
1165 #endif
1167 if (posix_time)
1168 time_format = POSIX_TIMEFORMAT;
1169 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1170 time_format = BASH_TIMEFORMAT;
1172 if (time_format && *time_format)
1173 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1175 return rv;
1177 #endif /* COMMAND_TIMING */
1179 /* Execute a command that's supposed to be in a subshell. This must be
1180 called after make_child and we must be running in the child process.
1181 The caller will return or exit() immediately with the value this returns. */
1182 static int
1183 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1184 COMMAND *command;
1185 int asynchronous;
1186 int pipe_in, pipe_out;
1187 struct fd_bitmap *fds_to_close;
1189 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1190 int ois;
1191 COMMAND *tcom;
1193 USE_VAR(user_subshell);
1194 USE_VAR(invert);
1195 USE_VAR(tcom);
1196 USE_VAR(asynchronous);
1198 subshell_level++;
1199 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1200 pipe_in == NO_PIPE &&
1201 stdin_redirects (command->redirects) == 0);
1203 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1204 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1206 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1208 /* If a command is asynchronous in a subshell (like ( foo ) & or
1209 the special case of an asynchronous GROUP command where the
1210 the subshell bit is turned on down in case cm_group: below),
1211 turn off `asynchronous', so that two subshells aren't spawned.
1212 XXX - asynchronous used to be set to 0 in this block, but that
1213 means that setup_async_signals was never run. Now it's set to
1214 0 after subshell_environment is set appropriately and setup_async_signals
1215 is run.
1217 This seems semantically correct to me. For example,
1218 ( foo ) & seems to say ``do the command `foo' in a subshell
1219 environment, but don't wait for that subshell to finish'',
1220 and "{ foo ; bar ; } &" seems to me to be like functions or
1221 builtins in the background, which executed in a subshell
1222 environment. I just don't see the need to fork two subshells. */
1224 /* Don't fork again, we are already in a subshell. A `doubly
1225 async' shell is not interactive, however. */
1226 if (asynchronous)
1228 #if defined (JOB_CONTROL)
1229 /* If a construct like ( exec xxx yyy ) & is given while job
1230 control is active, we want to prevent exec from putting the
1231 subshell back into the original process group, carefully
1232 undoing all the work we just did in make_child. */
1233 original_pgrp = -1;
1234 #endif /* JOB_CONTROL */
1235 ois = interactive_shell;
1236 interactive_shell = 0;
1237 /* This test is to prevent alias expansion by interactive shells that
1238 run `(command) &' but to allow scripts that have enabled alias
1239 expansion with `shopt -s expand_alias' to continue to expand
1240 aliases. */
1241 if (ois != interactive_shell)
1242 expand_aliases = 0;
1245 /* Subshells are neither login nor interactive. */
1246 login_shell = interactive = 0;
1248 if (user_subshell)
1249 subshell_environment = SUBSHELL_PAREN;
1250 else
1252 subshell_environment = 0; /* XXX */
1253 if (asynchronous)
1254 subshell_environment |= SUBSHELL_ASYNC;
1255 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1256 subshell_environment |= SUBSHELL_PIPE;
1259 reset_terminating_signals (); /* in sig.c */
1260 /* Cancel traps, in trap.c. */
1261 restore_original_signals ();
1263 /* Make sure restore_original_signals doesn't undo the work done by
1264 make_child to ensure that asynchronous children are immune to SIGINT
1265 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1266 not spawned. */
1267 if (asynchronous)
1269 setup_async_signals ();
1270 asynchronous = 0;
1273 #if defined (JOB_CONTROL)
1274 set_sigchld_handler ();
1275 #endif /* JOB_CONTROL */
1277 set_sigint_handler ();
1279 #if defined (JOB_CONTROL)
1280 /* Delete all traces that there were any jobs running. This is
1281 only for subshells. */
1282 without_job_control ();
1283 #endif /* JOB_CONTROL */
1285 if (fds_to_close)
1286 close_fd_bitmap (fds_to_close);
1288 do_piping (pipe_in, pipe_out);
1290 /* If this is a user subshell, set a flag if stdin was redirected.
1291 This is used later to decide whether to redirect fd 0 to
1292 /dev/null for async commands in the subshell. This adds more
1293 sh compatibility, but I'm not sure it's the right thing to do. */
1294 if (user_subshell)
1296 stdin_redir = stdin_redirects (command->redirects);
1297 restore_default_signal (0);
1300 /* If this is an asynchronous command (command &), we want to
1301 redirect the standard input from /dev/null in the absence of
1302 any specific redirection involving stdin. */
1303 if (should_redir_stdin && stdin_redir == 0)
1304 async_redirect_stdin ();
1306 /* Do redirections, then dispose of them before recursive call. */
1307 if (command->redirects)
1309 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1310 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1312 dispose_redirects (command->redirects);
1313 command->redirects = (REDIRECT *)NULL;
1316 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1318 if (command->flags & CMD_TIME_PIPELINE)
1319 tcom->flags |= CMD_TIME_PIPELINE;
1320 if (command->flags & CMD_TIME_POSIX)
1321 tcom->flags |= CMD_TIME_POSIX;
1323 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1324 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1325 tcom->flags |= CMD_IGNORE_RETURN;
1327 /* If this is a simple command, tell execute_disk_command that it
1328 might be able to get away without forking and simply exec.
1329 This means things like ( sleep 10 ) will only cause one fork.
1330 If we're timing the command or inverting its return value, however,
1331 we cannot do this optimization. */
1332 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1333 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1334 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1336 tcom->flags |= CMD_NO_FORK;
1337 if (tcom->type == cm_simple)
1338 tcom->value.Simple->flags |= CMD_NO_FORK;
1341 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1342 tcom->flags &= ~CMD_INVERT_RETURN;
1344 /* If we're inside a function while executing this subshell, we
1345 need to handle a possible `return'. */
1346 function_value = 0;
1347 if (return_catch_flag)
1348 function_value = setjmp (return_catch);
1350 if (function_value)
1351 return_code = return_catch_value;
1352 else
1353 return_code = execute_command_internal (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1355 /* If we are asked to, invert the return value. */
1356 if (invert)
1357 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1358 : EXECUTION_SUCCESS;
1360 /* If we were explicitly placed in a subshell with (), we need
1361 to do the `shell cleanup' things, such as running traps[0]. */
1362 if (user_subshell && signal_is_trapped (0))
1364 last_command_exit_value = return_code;
1365 return_code = run_exit_trap ();
1368 subshell_level--;
1369 return (return_code);
1370 /* NOTREACHED */
1373 static int
1374 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1375 COMMAND *command;
1376 int asynchronous, pipe_in, pipe_out;
1377 struct fd_bitmap *fds_to_close;
1379 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1380 COMMAND *cmd;
1381 struct fd_bitmap *fd_bitmap;
1383 #if defined (JOB_CONTROL)
1384 sigset_t set, oset;
1385 BLOCK_CHILD (set, oset);
1386 #endif /* JOB_CONTROL */
1388 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1390 prev = pipe_in;
1391 cmd = command;
1393 while (cmd && cmd->type == cm_connection &&
1394 cmd->value.Connection && cmd->value.Connection->connector == '|')
1396 /* Make a pipeline between the two commands. */
1397 if (pipe (fildes) < 0)
1399 sys_error ("pipe error");
1400 #if defined (JOB_CONTROL)
1401 terminate_current_pipeline ();
1402 kill_current_pipeline ();
1403 UNBLOCK_CHILD (oset);
1404 #endif /* JOB_CONTROL */
1405 last_command_exit_value = EXECUTION_FAILURE;
1406 /* The unwind-protects installed below will take care
1407 of closing all of the open file descriptors. */
1408 throw_to_top_level ();
1409 return (EXECUTION_FAILURE); /* XXX */
1412 /* Here is a problem: with the new file close-on-exec
1413 code, the read end of the pipe (fildes[0]) stays open
1414 in the first process, so that process will never get a
1415 SIGPIPE. There is no way to signal the first process
1416 that it should close fildes[0] after forking, so it
1417 remains open. No SIGPIPE is ever sent because there
1418 is still a file descriptor open for reading connected
1419 to the pipe. We take care of that here. This passes
1420 around a bitmap of file descriptors that must be
1421 closed after making a child process in execute_simple_command. */
1423 /* We need fd_bitmap to be at least as big as fildes[0].
1424 If fildes[0] is less than fds_to_close->size, then
1425 use fds_to_close->size. */
1426 new_bitmap_size = (fildes[0] < fds_to_close->size)
1427 ? fds_to_close->size
1428 : fildes[0] + 8;
1430 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1432 /* Now copy the old information into the new bitmap. */
1433 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1435 /* And mark the pipe file descriptors to be closed. */
1436 fd_bitmap->bitmap[fildes[0]] = 1;
1438 /* In case there are pipe or out-of-processes errors, we
1439 want all these file descriptors to be closed when
1440 unwind-protects are run, and the storage used for the
1441 bitmaps freed up. */
1442 begin_unwind_frame ("pipe-file-descriptors");
1443 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1444 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1445 if (prev >= 0)
1446 add_unwind_protect (close, prev);
1447 dummyfd = fildes[1];
1448 add_unwind_protect (close, dummyfd);
1450 #if defined (JOB_CONTROL)
1451 add_unwind_protect (restore_signal_mask, &oset);
1452 #endif /* JOB_CONTROL */
1454 if (ignore_return && cmd->value.Connection->first)
1455 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1456 execute_command_internal (cmd->value.Connection->first, asynchronous,
1457 prev, fildes[1], fd_bitmap);
1459 if (prev >= 0)
1460 close (prev);
1462 prev = fildes[0];
1463 close (fildes[1]);
1465 dispose_fd_bitmap (fd_bitmap);
1466 discard_unwind_frame ("pipe-file-descriptors");
1468 cmd = cmd->value.Connection->second;
1471 /* Now execute the rightmost command in the pipeline. */
1472 if (ignore_return && cmd)
1473 cmd->flags |= CMD_IGNORE_RETURN;
1474 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1476 if (prev >= 0)
1477 close (prev);
1479 #if defined (JOB_CONTROL)
1480 UNBLOCK_CHILD (oset);
1481 #endif
1483 return (exec_result);
1486 static int
1487 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1488 COMMAND *command;
1489 int asynchronous, pipe_in, pipe_out;
1490 struct fd_bitmap *fds_to_close;
1492 REDIRECT *rp;
1493 COMMAND *tc, *second;
1494 int ignore_return, exec_result;
1496 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1498 switch (command->value.Connection->connector)
1500 /* Do the first command asynchronously. */
1501 case '&':
1502 tc = command->value.Connection->first;
1503 if (tc == 0)
1504 return (EXECUTION_SUCCESS);
1506 rp = tc->redirects;
1508 if (ignore_return)
1509 tc->flags |= CMD_IGNORE_RETURN;
1510 tc->flags |= CMD_AMPERSAND;
1512 /* If this shell was compiled without job control support,
1513 if we are currently in a subshell via `( xxx )', or if job
1514 control is not active then the standard input for an
1515 asynchronous command is forced to /dev/null. */
1516 #if defined (JOB_CONTROL)
1517 if ((subshell_environment || !job_control) && !stdin_redir)
1518 #else
1519 if (!stdin_redir)
1520 #endif /* JOB_CONTROL */
1521 tc->flags |= CMD_STDIN_REDIR;
1523 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1525 if (tc->flags & CMD_STDIN_REDIR)
1526 tc->flags &= ~CMD_STDIN_REDIR;
1528 second = command->value.Connection->second;
1529 if (second)
1531 if (ignore_return)
1532 second->flags |= CMD_IGNORE_RETURN;
1534 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1537 break;
1539 /* Just call execute command on both sides. */
1540 case ';':
1541 if (ignore_return)
1543 if (command->value.Connection->first)
1544 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1545 if (command->value.Connection->second)
1546 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1548 QUIT;
1549 execute_command (command->value.Connection->first);
1550 QUIT;
1551 exec_result = execute_command_internal (command->value.Connection->second,
1552 asynchronous, pipe_in, pipe_out,
1553 fds_to_close);
1554 break;
1556 case '|':
1557 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1558 break;
1560 case AND_AND:
1561 case OR_OR:
1562 if (asynchronous)
1564 /* If we have something like `a && b &' or `a || b &', run the
1565 && or || stuff in a subshell. Force a subshell and just call
1566 execute_command_internal again. Leave asynchronous on
1567 so that we get a report from the parent shell about the
1568 background job. */
1569 command->flags |= CMD_FORCE_SUBSHELL;
1570 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1571 break;
1574 /* Execute the first command. If the result of that is successful
1575 and the connector is AND_AND, or the result is not successful
1576 and the connector is OR_OR, then execute the second command,
1577 otherwise return. */
1579 if (command->value.Connection->first)
1580 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1582 exec_result = execute_command (command->value.Connection->first);
1583 QUIT;
1584 if (((command->value.Connection->connector == AND_AND) &&
1585 (exec_result == EXECUTION_SUCCESS)) ||
1586 ((command->value.Connection->connector == OR_OR) &&
1587 (exec_result != EXECUTION_SUCCESS)))
1589 if (ignore_return && command->value.Connection->second)
1590 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1592 exec_result = execute_command (command->value.Connection->second);
1594 break;
1596 default:
1597 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1598 jump_to_top_level (DISCARD);
1599 exec_result = EXECUTION_FAILURE;
1602 return exec_result;
1605 #define REAP() \
1606 do \
1608 if (!interactive_shell) \
1609 reap_dead_jobs (); \
1611 while (0)
1613 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1614 DO command; DONE */
1615 static int
1616 execute_for_command (for_command)
1617 FOR_COM *for_command;
1619 register WORD_LIST *releaser, *list;
1620 SHELL_VAR *v;
1621 char *identifier;
1622 int retval, save_line_number;
1623 #if 0
1624 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1625 #endif
1627 save_line_number = line_number;
1628 if (check_identifier (for_command->name, 1) == 0)
1630 if (posixly_correct && interactive_shell == 0)
1632 last_command_exit_value = EX_USAGE;
1633 jump_to_top_level (ERREXIT);
1635 return (EXECUTION_FAILURE);
1638 loop_level++;
1639 identifier = for_command->name->word;
1641 list = releaser = expand_words_no_vars (for_command->map_list);
1643 begin_unwind_frame ("for");
1644 add_unwind_protect (dispose_words, releaser);
1646 #if 0
1647 if (lexical_scoping)
1649 old_value = copy_variable (find_variable (identifier));
1650 if (old_value)
1651 add_unwind_protect (dispose_variable, old_value);
1653 #endif
1655 if (for_command->flags & CMD_IGNORE_RETURN)
1656 for_command->action->flags |= CMD_IGNORE_RETURN;
1658 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1660 QUIT;
1662 line_number = for_command->line;
1664 /* Remember what this command looks like, for debugger. */
1665 command_string_index = 0;
1666 print_for_command_head (for_command);
1668 if (echo_command_at_execute)
1669 xtrace_print_for_command_head (for_command);
1671 /* Save this command unless it's a trap command and we're not running
1672 a debug trap. */
1673 #if 0
1674 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
1675 #else
1676 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
1677 #endif
1679 FREE (the_printed_command_except_trap);
1680 the_printed_command_except_trap = savestring (the_printed_command);
1683 retval = run_debug_trap ();
1684 #if defined (DEBUGGER)
1685 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1686 skip the command. */
1687 if (debugging_mode && retval != EXECUTION_SUCCESS)
1688 continue;
1689 #endif
1691 this_command_name = (char *)NULL;
1692 v = bind_variable (identifier, list->word->word, 0);
1693 if (readonly_p (v) || noassign_p (v))
1695 line_number = save_line_number;
1696 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1698 last_command_exit_value = EXECUTION_FAILURE;
1699 jump_to_top_level (FORCE_EOF);
1701 else
1703 dispose_words (releaser);
1704 discard_unwind_frame ("for");
1705 loop_level--;
1706 return (EXECUTION_FAILURE);
1709 retval = execute_command (for_command->action);
1710 REAP ();
1711 QUIT;
1713 if (breaking)
1715 breaking--;
1716 break;
1719 if (continuing)
1721 continuing--;
1722 if (continuing)
1723 break;
1727 loop_level--;
1728 line_number = save_line_number;
1730 #if 0
1731 if (lexical_scoping)
1733 if (!old_value)
1734 unbind_variable (identifier);
1735 else
1737 SHELL_VAR *new_value;
1739 new_value = bind_variable (identifier, value_cell(old_value), 0);
1740 new_value->attributes = old_value->attributes;
1741 dispose_variable (old_value);
1744 #endif
1746 dispose_words (releaser);
1747 discard_unwind_frame ("for");
1748 return (retval);
1751 #if defined (ARITH_FOR_COMMAND)
1752 /* Execute an arithmetic for command. The syntax is
1754 for (( init ; step ; test ))
1756 body
1757 done
1759 The execution should be exactly equivalent to
1761 eval \(\( init \)\)
1762 while eval \(\( test \)\) ; do
1763 body;
1764 eval \(\( step \)\)
1765 done
1767 static intmax_t
1768 eval_arith_for_expr (l, okp)
1769 WORD_LIST *l;
1770 int *okp;
1772 WORD_LIST *new;
1773 intmax_t expresult;
1774 int r;
1776 new = expand_words_no_vars (l);
1777 if (new)
1779 if (echo_command_at_execute)
1780 xtrace_print_arith_cmd (new);
1781 this_command_name = "(("; /* )) for expression error messages */
1783 command_string_index = 0;
1784 print_arith_command (new);
1785 if (signal_in_progress (DEBUG_TRAP) == 0)
1787 FREE (the_printed_command_except_trap);
1788 the_printed_command_except_trap = savestring (the_printed_command);
1791 r = run_debug_trap ();
1792 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1793 skip the command. */
1794 #if defined (DEBUGGER)
1795 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
1796 expresult = evalexp (new->word->word, okp);
1797 else
1799 expresult = 0;
1800 if (okp)
1801 *okp = 1;
1803 #else
1804 expresult = evalexp (new->word->word, okp);
1805 #endif
1806 dispose_words (new);
1808 else
1810 expresult = 0;
1811 if (okp)
1812 *okp = 1;
1814 return (expresult);
1817 static int
1818 execute_arith_for_command (arith_for_command)
1819 ARITH_FOR_COM *arith_for_command;
1821 intmax_t expresult;
1822 int expok, body_status, arith_lineno, save_lineno;
1824 body_status = EXECUTION_SUCCESS;
1825 loop_level++;
1826 save_lineno = line_number;
1828 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1829 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1831 this_command_name = "(("; /* )) for expression error messages */
1833 /* save the starting line number of the command so we can reset
1834 line_number before executing each expression -- for $LINENO
1835 and the DEBUG trap. */
1836 line_number = arith_lineno = arith_for_command->line;
1837 if (variable_context && interactive_shell)
1838 line_number -= function_line_number;
1840 /* Evaluate the initialization expression. */
1841 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1842 if (expok == 0)
1844 line_number = save_lineno;
1845 return (EXECUTION_FAILURE);
1848 while (1)
1850 /* Evaluate the test expression. */
1851 line_number = arith_lineno;
1852 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1853 line_number = save_lineno;
1855 if (expok == 0)
1857 body_status = EXECUTION_FAILURE;
1858 break;
1860 REAP ();
1861 if (expresult == 0)
1862 break;
1864 /* Execute the body of the arithmetic for command. */
1865 QUIT;
1866 body_status = execute_command (arith_for_command->action);
1867 QUIT;
1869 /* Handle any `break' or `continue' commands executed by the body. */
1870 if (breaking)
1872 breaking--;
1873 break;
1876 if (continuing)
1878 continuing--;
1879 if (continuing)
1880 break;
1883 /* Evaluate the step expression. */
1884 line_number = arith_lineno;
1885 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1886 line_number = save_lineno;
1888 if (expok == 0)
1890 body_status = EXECUTION_FAILURE;
1891 break;
1895 loop_level--;
1896 line_number = save_lineno;
1898 return (body_status);
1900 #endif
1902 #if defined (SELECT_COMMAND)
1903 static int LINES, COLS, tabsize;
1905 #define RP_SPACE ") "
1906 #define RP_SPACE_LEN 2
1908 /* XXX - does not handle numbers > 1000000 at all. */
1909 #define NUMBER_LEN(s) \
1910 ((s < 10) ? 1 \
1911 : ((s < 100) ? 2 \
1912 : ((s < 1000) ? 3 \
1913 : ((s < 10000) ? 4 \
1914 : ((s < 100000) ? 5 \
1915 : 6)))))
1917 static int
1918 print_index_and_element (len, ind, list)
1919 int len, ind;
1920 WORD_LIST *list;
1922 register WORD_LIST *l;
1923 register int i;
1925 if (list == 0)
1926 return (0);
1927 for (i = ind, l = list; l && --i; l = l->next)
1929 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1930 return (STRLEN (l->word->word));
1933 static void
1934 indent (from, to)
1935 int from, to;
1937 while (from < to)
1939 if ((to / tabsize) > (from / tabsize))
1941 putc ('\t', stderr);
1942 from += tabsize - from % tabsize;
1944 else
1946 putc (' ', stderr);
1947 from++;
1952 static void
1953 print_select_list (list, list_len, max_elem_len, indices_len)
1954 WORD_LIST *list;
1955 int list_len, max_elem_len, indices_len;
1957 int ind, row, elem_len, pos, cols, rows;
1958 int first_column_indices_len, other_indices_len;
1960 if (list == 0)
1962 putc ('\n', stderr);
1963 return;
1966 cols = max_elem_len ? COLS / max_elem_len : 1;
1967 if (cols == 0)
1968 cols = 1;
1969 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1970 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1972 if (rows == 1)
1974 rows = cols;
1975 cols = 1;
1978 first_column_indices_len = NUMBER_LEN (rows);
1979 other_indices_len = indices_len;
1981 for (row = 0; row < rows; row++)
1983 ind = row;
1984 pos = 0;
1985 while (1)
1987 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1988 elem_len = print_index_and_element (indices_len, ind + 1, list);
1989 elem_len += indices_len + RP_SPACE_LEN;
1990 ind += rows;
1991 if (ind >= list_len)
1992 break;
1993 indent (pos + elem_len, pos + max_elem_len);
1994 pos += max_elem_len;
1996 putc ('\n', stderr);
2000 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2001 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
2002 If the number is between 1 and LIST_LEN, return that selection. If EOF
2003 is read, return a null string. If a blank line is entered, or an invalid
2004 number is entered, the loop is executed again. */
2005 static char *
2006 select_query (list, list_len, prompt, print_menu)
2007 WORD_LIST *list;
2008 int list_len;
2009 char *prompt;
2010 int print_menu;
2012 int max_elem_len, indices_len, len;
2013 intmax_t reply;
2014 WORD_LIST *l;
2015 char *repl_string, *t;
2017 t = get_string_value ("LINES");
2018 LINES = (t && *t) ? atoi (t) : 24;
2019 t = get_string_value ("COLUMNS");
2020 COLS = (t && *t) ? atoi (t) : 80;
2022 #if 0
2023 t = get_string_value ("TABSIZE");
2024 tabsize = (t && *t) ? atoi (t) : 8;
2025 if (tabsize <= 0)
2026 tabsize = 8;
2027 #else
2028 tabsize = 8;
2029 #endif
2031 max_elem_len = 0;
2032 for (l = list; l; l = l->next)
2034 len = STRLEN (l->word->word);
2035 if (len > max_elem_len)
2036 max_elem_len = len;
2038 indices_len = NUMBER_LEN (list_len);
2039 max_elem_len += indices_len + RP_SPACE_LEN + 2;
2041 while (1)
2043 if (print_menu)
2044 print_select_list (list, list_len, max_elem_len, indices_len);
2045 fprintf (stderr, "%s", prompt);
2046 fflush (stderr);
2047 QUIT;
2049 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
2051 putchar ('\n');
2052 return ((char *)NULL);
2054 repl_string = get_string_value ("REPLY");
2055 if (*repl_string == 0)
2057 print_menu = 1;
2058 continue;
2060 if (legal_number (repl_string, &reply) == 0)
2061 return "";
2062 if (reply < 1 || reply > list_len)
2063 return "";
2065 for (l = list; l && --reply; l = l->next)
2067 return (l->word->word);
2071 /* Execute a SELECT command. The syntax is:
2072 SELECT word IN list DO command_list DONE
2073 Only `break' or `return' in command_list will terminate
2074 the command. */
2075 static int
2076 execute_select_command (select_command)
2077 SELECT_COM *select_command;
2079 WORD_LIST *releaser, *list;
2080 SHELL_VAR *v;
2081 char *identifier, *ps3_prompt, *selection;
2082 int retval, list_len, show_menu, save_line_number;
2084 if (check_identifier (select_command->name, 1) == 0)
2085 return (EXECUTION_FAILURE);
2087 save_line_number = line_number;
2088 line_number = select_command->line;
2090 command_string_index = 0;
2091 print_select_command_head (select_command);
2093 if (echo_command_at_execute)
2094 xtrace_print_select_command_head (select_command);
2096 #if 0
2097 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2098 #else
2099 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2100 #endif
2102 FREE (the_printed_command_except_trap);
2103 the_printed_command_except_trap = savestring (the_printed_command);
2106 retval = run_debug_trap ();
2107 #if defined (DEBUGGER)
2108 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2109 skip the command. */
2110 if (debugging_mode && retval != EXECUTION_SUCCESS)
2111 return (EXECUTION_SUCCESS);
2112 #endif
2114 loop_level++;
2115 identifier = select_command->name->word;
2117 /* command and arithmetic substitution, parameter and variable expansion,
2118 word splitting, pathname expansion, and quote removal. */
2119 list = releaser = expand_words_no_vars (select_command->map_list);
2120 list_len = list_length (list);
2121 if (list == 0 || list_len == 0)
2123 if (list)
2124 dispose_words (list);
2125 line_number = save_line_number;
2126 return (EXECUTION_SUCCESS);
2129 begin_unwind_frame ("select");
2130 add_unwind_protect (dispose_words, releaser);
2132 if (select_command->flags & CMD_IGNORE_RETURN)
2133 select_command->action->flags |= CMD_IGNORE_RETURN;
2135 retval = EXECUTION_SUCCESS;
2136 show_menu = 1;
2138 while (1)
2140 line_number = select_command->line;
2141 ps3_prompt = get_string_value ("PS3");
2142 if (ps3_prompt == 0)
2143 ps3_prompt = "#? ";
2145 QUIT;
2146 selection = select_query (list, list_len, ps3_prompt, show_menu);
2147 QUIT;
2148 if (selection == 0)
2150 /* select_query returns EXECUTION_FAILURE if the read builtin
2151 fails, so we want to return failure in this case. */
2152 retval = EXECUTION_FAILURE;
2153 break;
2156 v = bind_variable (identifier, selection, 0);
2157 if (readonly_p (v) || noassign_p (v))
2159 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2161 last_command_exit_value = EXECUTION_FAILURE;
2162 jump_to_top_level (FORCE_EOF);
2164 else
2166 dispose_words (releaser);
2167 discard_unwind_frame ("select");
2168 loop_level--;
2169 line_number = save_line_number;
2170 return (EXECUTION_FAILURE);
2174 retval = execute_command (select_command->action);
2176 REAP ();
2177 QUIT;
2179 if (breaking)
2181 breaking--;
2182 break;
2185 if (continuing)
2187 continuing--;
2188 if (continuing)
2189 break;
2192 #if defined (KSH_COMPATIBLE_SELECT)
2193 show_menu = 0;
2194 selection = get_string_value ("REPLY");
2195 if (selection && *selection == '\0')
2196 show_menu = 1;
2197 #endif
2200 loop_level--;
2201 line_number = save_line_number;
2203 dispose_words (releaser);
2204 discard_unwind_frame ("select");
2205 return (retval);
2207 #endif /* SELECT_COMMAND */
2209 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2210 The pattern_list is a linked list of pattern clauses; each clause contains
2211 some patterns to compare word_desc against, and an associated command to
2212 execute. */
2213 static int
2214 execute_case_command (case_command)
2215 CASE_COM *case_command;
2217 register WORD_LIST *list;
2218 WORD_LIST *wlist, *es;
2219 PATTERN_LIST *clauses;
2220 char *word, *pattern;
2221 int retval, match, ignore_return, save_line_number;
2223 save_line_number = line_number;
2224 line_number = case_command->line;
2226 command_string_index = 0;
2227 print_case_command_head (case_command);
2229 if (echo_command_at_execute)
2230 xtrace_print_case_command_head (case_command);
2232 #if 0
2233 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2234 #else
2235 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2236 #endif
2238 FREE (the_printed_command_except_trap);
2239 the_printed_command_except_trap = savestring (the_printed_command);
2242 retval = run_debug_trap();
2243 #if defined (DEBUGGER)
2244 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2245 skip the command. */
2246 if (debugging_mode && retval != EXECUTION_SUCCESS)
2248 line_number = save_line_number;
2249 return (EXECUTION_SUCCESS);
2251 #endif
2253 wlist = expand_word_unsplit (case_command->word, 0);
2254 word = wlist ? string_list (wlist) : savestring ("");
2255 dispose_words (wlist);
2257 retval = EXECUTION_SUCCESS;
2258 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2260 begin_unwind_frame ("case");
2261 add_unwind_protect ((Function *)xfree, word);
2263 #define EXIT_CASE() goto exit_case_command
2265 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2267 QUIT;
2268 for (list = clauses->patterns; list; list = list->next)
2270 es = expand_word_leave_quoted (list->word, 0);
2272 if (es && es->word && es->word->word && *(es->word->word))
2273 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2274 else
2276 pattern = (char *)xmalloc (1);
2277 pattern[0] = '\0';
2280 /* Since the pattern does not undergo quote removal (as per
2281 Posix.2, section 3.9.4.3), the strmatch () call must be able
2282 to recognize backslashes as escape characters. */
2283 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
2284 free (pattern);
2286 dispose_words (es);
2288 if (match)
2290 if (clauses->action && ignore_return)
2291 clauses->action->flags |= CMD_IGNORE_RETURN;
2292 retval = execute_command (clauses->action);
2293 EXIT_CASE ();
2296 QUIT;
2300 exit_case_command:
2301 free (word);
2302 discard_unwind_frame ("case");
2303 line_number = save_line_number;
2304 return (retval);
2307 #define CMD_WHILE 0
2308 #define CMD_UNTIL 1
2310 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2311 Repeatedly execute action while executing test produces
2312 EXECUTION_SUCCESS. */
2313 static int
2314 execute_while_command (while_command)
2315 WHILE_COM *while_command;
2317 return (execute_while_or_until (while_command, CMD_WHILE));
2320 /* UNTIL is just like WHILE except that the test result is negated. */
2321 static int
2322 execute_until_command (while_command)
2323 WHILE_COM *while_command;
2325 return (execute_while_or_until (while_command, CMD_UNTIL));
2328 /* The body for both while and until. The only difference between the
2329 two is that the test value is treated differently. TYPE is
2330 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2331 be EXECUTION_SUCCESS if no commands in the body are executed, and
2332 the status of the last command executed in the body otherwise. */
2333 static int
2334 execute_while_or_until (while_command, type)
2335 WHILE_COM *while_command;
2336 int type;
2338 int return_value, body_status;
2340 body_status = EXECUTION_SUCCESS;
2341 loop_level++;
2343 while_command->test->flags |= CMD_IGNORE_RETURN;
2344 if (while_command->flags & CMD_IGNORE_RETURN)
2345 while_command->action->flags |= CMD_IGNORE_RETURN;
2347 while (1)
2349 return_value = execute_command (while_command->test);
2350 REAP ();
2352 /* Need to handle `break' in the test when we would break out of the
2353 loop. The job control code will set `breaking' to loop_level
2354 when a job in a loop is stopped with SIGTSTP. If the stopped job
2355 is in the loop test, `breaking' will not be reset unless we do
2356 this, and the shell will cease to execute commands. */
2357 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2359 if (breaking)
2360 breaking--;
2361 break;
2363 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2365 if (breaking)
2366 breaking--;
2367 break;
2370 QUIT;
2371 body_status = execute_command (while_command->action);
2372 QUIT;
2374 if (breaking)
2376 breaking--;
2377 break;
2380 if (continuing)
2382 continuing--;
2383 if (continuing)
2384 break;
2387 loop_level--;
2389 return (body_status);
2392 /* IF test THEN command [ELSE command].
2393 IF also allows ELIF in the place of ELSE IF, but
2394 the parser makes *that* stupidity transparent. */
2395 static int
2396 execute_if_command (if_command)
2397 IF_COM *if_command;
2399 int return_value, save_line_number;
2401 save_line_number = line_number;
2402 if_command->test->flags |= CMD_IGNORE_RETURN;
2403 return_value = execute_command (if_command->test);
2404 line_number = save_line_number;
2406 if (return_value == EXECUTION_SUCCESS)
2408 QUIT;
2410 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2411 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2413 return (execute_command (if_command->true_case));
2415 else
2417 QUIT;
2419 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2420 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2422 return (execute_command (if_command->false_case));
2426 #if defined (DPAREN_ARITHMETIC)
2427 static int
2428 execute_arith_command (arith_command)
2429 ARITH_COM *arith_command;
2431 int expok, save_line_number, retval;
2432 intmax_t expresult;
2433 WORD_LIST *new;
2434 char *exp;
2436 expresult = 0;
2438 save_line_number = line_number;
2439 this_command_name = "(("; /* )) */
2440 line_number = arith_command->line;
2441 /* If we're in a function, update the line number information. */
2442 if (variable_context && interactive_shell)
2443 line_number -= function_line_number;
2445 command_string_index = 0;
2446 print_arith_command (arith_command->exp);
2448 if (signal_in_progress (DEBUG_TRAP) == 0)
2450 FREE (the_printed_command_except_trap);
2451 the_printed_command_except_trap = savestring (the_printed_command);
2454 /* Run the debug trap before each arithmetic command, but do it after we
2455 update the line number information and before we expand the various
2456 words in the expression. */
2457 retval = run_debug_trap ();
2458 #if defined (DEBUGGER)
2459 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2460 skip the command. */
2461 if (debugging_mode && retval != EXECUTION_SUCCESS)
2463 line_number = save_line_number;
2464 return (EXECUTION_SUCCESS);
2466 #endif
2468 new = expand_words_no_vars (arith_command->exp);
2470 /* If we're tracing, make a new word list with `((' at the front and `))'
2471 at the back and print it. */
2472 if (echo_command_at_execute)
2473 xtrace_print_arith_cmd (new);
2475 if (new)
2477 exp = new->next ? string_list (new) : new->word->word;
2478 expresult = evalexp (exp, &expok);
2479 line_number = save_line_number;
2480 if (exp != new->word->word)
2481 free (exp);
2482 dispose_words (new);
2484 else
2486 expresult = 0;
2487 expok = 1;
2490 if (expok == 0)
2491 return (EXECUTION_FAILURE);
2493 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2495 #endif /* DPAREN_ARITHMETIC */
2497 #if defined (COND_COMMAND)
2499 static char *nullstr = "";
2501 static int
2502 execute_cond_node (cond)
2503 COND_COM *cond;
2505 int result, invert, patmatch, rmatch, mflags;
2506 char *arg1, *arg2;
2508 invert = (cond->flags & CMD_INVERT_RETURN);
2510 if (cond->type == COND_EXPR)
2511 result = execute_cond_node (cond->left);
2512 else if (cond->type == COND_OR)
2514 result = execute_cond_node (cond->left);
2515 if (result != EXECUTION_SUCCESS)
2516 result = execute_cond_node (cond->right);
2518 else if (cond->type == COND_AND)
2520 result = execute_cond_node (cond->left);
2521 if (result == EXECUTION_SUCCESS)
2522 result = execute_cond_node (cond->right);
2524 else if (cond->type == COND_UNARY)
2526 arg1 = cond_expand_word (cond->left->op, 0);
2527 if (arg1 == 0)
2528 arg1 = nullstr;
2529 if (echo_command_at_execute)
2530 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2531 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2532 if (arg1 != nullstr)
2533 free (arg1);
2535 else if (cond->type == COND_BINARY)
2537 rmatch = 0;
2538 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2539 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2540 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2541 #if defined (COND_REGEXP)
2542 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
2543 cond->op->word[2] == '\0');
2544 #endif
2546 arg1 = cond_expand_word (cond->left->op, 0);
2547 if (arg1 == 0)
2548 arg1 = nullstr;
2549 arg2 = cond_expand_word (cond->right->op, rmatch ? 2 : (patmatch ? 1 : 0));
2550 if (arg2 == 0)
2551 arg2 = nullstr;
2553 if (echo_command_at_execute)
2554 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2556 #if defined (COND_REGEXP)
2557 if (rmatch)
2559 mflags = SHMAT_PWARN;
2560 #if defined (ARRAY_VARS)
2561 mflags |= SHMAT_SUBEXP;
2562 #endif
2564 result = sh_regmatch (arg1, arg2, mflags);
2566 else
2567 #endif /* COND_REGEXP */
2569 int oe;
2570 oe = extended_glob;
2571 extended_glob = 1;
2572 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2573 ? EXECUTION_SUCCESS
2574 : EXECUTION_FAILURE;
2575 extended_glob = oe;
2577 if (arg1 != nullstr)
2578 free (arg1);
2579 if (arg2 != nullstr)
2580 free (arg2);
2582 else
2584 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2585 jump_to_top_level (DISCARD);
2586 result = EXECUTION_FAILURE;
2589 if (invert)
2590 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2592 return result;
2595 static int
2596 execute_cond_command (cond_command)
2597 COND_COM *cond_command;
2599 int retval, save_line_number;
2601 retval = EXECUTION_SUCCESS;
2602 save_line_number = line_number;
2604 this_command_name = "[[";
2605 line_number = cond_command->line;
2606 /* If we're in a function, update the line number information. */
2607 if (variable_context && interactive_shell)
2608 line_number -= function_line_number;
2610 command_string_index = 0;
2611 print_cond_command (cond_command);
2613 if (signal_in_progress (DEBUG_TRAP) == 0)
2615 FREE (the_printed_command_except_trap);
2616 the_printed_command_except_trap = savestring (the_printed_command);
2619 /* Run the debug trap before each conditional command, but do it after we
2620 update the line number information. */
2621 retval = run_debug_trap ();
2622 #if defined (DEBUGGER)
2623 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2624 skip the command. */
2625 if (debugging_mode && retval != EXECUTION_SUCCESS)
2627 line_number = save_line_number;
2628 return (EXECUTION_SUCCESS);
2630 #endif
2632 #if 0
2633 debug_print_cond_command (cond_command);
2634 #endif
2636 last_command_exit_value = retval = execute_cond_node (cond_command);
2637 line_number = save_line_number;
2638 return (retval);
2640 #endif /* COND_COMMAND */
2642 static void
2643 bind_lastarg (arg)
2644 char *arg;
2646 SHELL_VAR *var;
2648 if (arg == 0)
2649 arg = "";
2650 var = bind_variable ("_", arg, 0);
2651 VUNSETATTR (var, att_exported);
2654 /* Execute a null command. Fork a subshell if the command uses pipes or is
2655 to be run asynchronously. This handles all the side effects that are
2656 supposed to take place. */
2657 static int
2658 execute_null_command (redirects, pipe_in, pipe_out, async)
2659 REDIRECT *redirects;
2660 int pipe_in, pipe_out, async;
2662 int r;
2664 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2666 /* We have a null command, but we really want a subshell to take
2667 care of it. Just fork, do piping and redirections, and exit. */
2668 if (make_child ((char *)NULL, async) == 0)
2670 /* Cancel traps, in trap.c. */
2671 restore_original_signals (); /* XXX */
2673 do_piping (pipe_in, pipe_out);
2675 if (async)
2676 subshell_environment |= SUBSHELL_ASYNC;
2677 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2678 subshell_environment |= SUBSHELL_PIPE;
2680 if (do_redirections (redirects, RX_ACTIVE) == 0)
2681 exit (EXECUTION_SUCCESS);
2682 else
2683 exit (EXECUTION_FAILURE);
2685 else
2687 close_pipes (pipe_in, pipe_out);
2688 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2689 unlink_fifo_list ();
2690 #endif
2691 return (EXECUTION_SUCCESS);
2694 else
2696 /* Even if there aren't any command names, pretend to do the
2697 redirections that are specified. The user expects the side
2698 effects to take place. If the redirections fail, then return
2699 failure. Otherwise, if a command substitution took place while
2700 expanding the command or a redirection, return the value of that
2701 substitution. Otherwise, return EXECUTION_SUCCESS. */
2703 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
2704 cleanup_redirects (redirection_undo_list);
2705 redirection_undo_list = (REDIRECT *)NULL;
2707 if (r != 0)
2708 return (EXECUTION_FAILURE);
2709 else if (last_command_subst_pid != NO_PID)
2710 return (last_command_exit_value);
2711 else
2712 return (EXECUTION_SUCCESS);
2716 /* This is a hack to suppress word splitting for assignment statements
2717 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2718 static void
2719 fix_assignment_words (words)
2720 WORD_LIST *words;
2722 WORD_LIST *w;
2723 struct builtin *b;
2725 if (words == 0)
2726 return;
2728 b = 0;
2730 for (w = words; w; w = w->next)
2731 if (w->word->flags & W_ASSIGNMENT)
2733 if (b == 0)
2735 b = builtin_address_internal (words->word->word, 0);
2736 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2737 return;
2738 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
2739 words->word->flags |= W_ASSNBLTIN;
2741 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
2745 /* The meaty part of all the executions. We have to start hacking the
2746 real execution of commands here. Fork a process, set things up,
2747 execute the command. */
2748 static int
2749 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2750 SIMPLE_COM *simple_command;
2751 int pipe_in, pipe_out, async;
2752 struct fd_bitmap *fds_to_close;
2754 WORD_LIST *words, *lastword;
2755 char *command_line, *lastarg, *temp;
2756 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2757 pid_t old_last_async_pid;
2758 sh_builtin_func_t *builtin;
2759 SHELL_VAR *func;
2761 result = EXECUTION_SUCCESS;
2762 special_builtin_failed = builtin_is_special = 0;
2763 command_line = (char *)0;
2765 /* If we're in a function, update the line number information. */
2766 if (variable_context && interactive_shell)
2767 line_number -= function_line_number;
2769 /* Remember what this command line looks like at invocation. */
2770 command_string_index = 0;
2771 print_simple_command (simple_command);
2773 #if 0
2774 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2775 #else
2776 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2777 #endif
2779 FREE (the_printed_command_except_trap);
2780 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
2783 /* Run the debug trap before each simple command, but do it after we
2784 update the line number information. */
2785 result = run_debug_trap ();
2786 #if defined (DEBUGGER)
2787 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2788 skip the command. */
2789 if (debugging_mode && result != EXECUTION_SUCCESS)
2790 return (EXECUTION_SUCCESS);
2791 #endif
2793 first_word_quoted =
2794 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2796 last_command_subst_pid = NO_PID;
2797 old_last_async_pid = last_asynchronous_pid;
2799 already_forked = dofork = 0;
2801 /* If we're in a pipeline or run in the background, set DOFORK so we
2802 make the child early, before word expansion. This keeps assignment
2803 statements from affecting the parent shell's environment when they
2804 should not. */
2805 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2807 /* Something like `%2 &' should restart job 2 in the background, not cause
2808 the shell to fork here. */
2809 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2810 simple_command->words && simple_command->words->word &&
2811 simple_command->words->word->word &&
2812 (simple_command->words->word->word[0] == '%'))
2813 dofork = 0;
2815 if (dofork)
2817 /* Do this now, because execute_disk_command will do it anyway in the
2818 vast majority of cases. */
2819 maybe_make_export_env ();
2821 /* Don't let a DEBUG trap overwrite the command string to be saved with
2822 the process/job associated with this child. */
2823 if (make_child (savestring (the_printed_command_except_trap), async) == 0)
2825 already_forked = 1;
2826 simple_command->flags |= CMD_NO_FORK;
2828 subshell_environment = SUBSHELL_FORK;
2829 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2830 subshell_environment |= SUBSHELL_PIPE;
2831 if (async)
2832 subshell_environment |= SUBSHELL_ASYNC;
2834 /* We need to do this before piping to handle some really
2835 pathological cases where one of the pipe file descriptors
2836 is < 2. */
2837 if (fds_to_close)
2838 close_fd_bitmap (fds_to_close);
2840 do_piping (pipe_in, pipe_out);
2841 pipe_in = pipe_out = NO_PIPE;
2843 last_asynchronous_pid = old_last_async_pid;
2845 else
2847 close_pipes (pipe_in, pipe_out);
2848 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2849 unlink_fifo_list ();
2850 #endif
2851 command_line = (char *)NULL; /* don't free this. */
2852 bind_lastarg ((char *)NULL);
2853 return (result);
2857 /* If we are re-running this as the result of executing the `command'
2858 builtin, do not expand the command words a second time. */
2859 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2861 current_fds_to_close = fds_to_close;
2862 fix_assignment_words (simple_command->words);
2863 words = expand_words (simple_command->words);
2864 current_fds_to_close = (struct fd_bitmap *)NULL;
2866 else
2867 words = copy_word_list (simple_command->words);
2869 /* It is possible for WORDS not to have anything left in it.
2870 Perhaps all the words consisted of `$foo', and there was
2871 no variable `$foo'. */
2872 if (words == 0)
2874 this_command_name = 0;
2875 result = execute_null_command (simple_command->redirects,
2876 pipe_in, pipe_out,
2877 already_forked ? 0 : async);
2878 if (already_forked)
2879 exit (result);
2880 else
2882 bind_lastarg ((char *)NULL);
2883 set_pipestatus_from_exit (result);
2884 return (result);
2888 lastarg = (char *)NULL;
2890 begin_unwind_frame ("simple-command");
2892 if (echo_command_at_execute)
2893 xtrace_print_word_list (words, 1);
2895 builtin = (sh_builtin_func_t *)NULL;
2896 func = (SHELL_VAR *)NULL;
2897 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2899 /* Posix.2 says special builtins are found before functions. We
2900 don't set builtin_is_special anywhere other than here, because
2901 this path is followed only when the `command' builtin is *not*
2902 being used, and we don't want to exit the shell if a special
2903 builtin executed with `command builtin' fails. `command' is not
2904 a special builtin. */
2905 if (posixly_correct)
2907 builtin = find_special_builtin (words->word->word);
2908 if (builtin)
2909 builtin_is_special = 1;
2911 if (builtin == 0)
2912 func = find_function (words->word->word);
2915 /* In POSIX mode, assignment errors in the temporary environment cause a
2916 non-interactive shell to exit. */
2917 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
2919 last_command_exit_value = EXECUTION_FAILURE;
2920 jump_to_top_level (ERREXIT);
2923 add_unwind_protect (dispose_words, words);
2924 QUIT;
2926 /* Bind the last word in this command to "$_" after execution. */
2927 for (lastword = words; lastword->next; lastword = lastword->next)
2929 lastarg = lastword->word->word;
2931 #if defined (JOB_CONTROL)
2932 /* Is this command a job control related thing? */
2933 if (words->word->word[0] == '%' && already_forked == 0)
2935 this_command_name = async ? "bg" : "fg";
2936 last_shell_builtin = this_shell_builtin;
2937 this_shell_builtin = builtin_address (this_command_name);
2938 result = (*this_shell_builtin) (words);
2939 goto return_result;
2942 /* One other possiblilty. The user may want to resume an existing job.
2943 If they do, find out whether this word is a candidate for a running
2944 job. */
2945 if (job_control && already_forked == 0 && async == 0 &&
2946 !first_word_quoted &&
2947 !words->next &&
2948 words->word->word[0] &&
2949 !simple_command->redirects &&
2950 pipe_in == NO_PIPE &&
2951 pipe_out == NO_PIPE &&
2952 (temp = get_string_value ("auto_resume")))
2954 int job, jflags, started_status;
2956 jflags = JM_STOPPED|JM_FIRSTMATCH;
2957 if (STREQ (temp, "exact"))
2958 jflags |= JM_EXACT;
2959 else if (STREQ (temp, "substring"))
2960 jflags |= JM_SUBSTRING;
2961 else
2962 jflags |= JM_PREFIX;
2963 job = get_job_by_name (words->word->word, jflags);
2964 if (job != NO_JOB)
2966 run_unwind_frame ("simple-command");
2967 this_command_name = "fg";
2968 last_shell_builtin = this_shell_builtin;
2969 this_shell_builtin = builtin_address ("fg");
2971 started_status = start_job (job, 1);
2972 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2975 #endif /* JOB_CONTROL */
2977 /* Remember the name of this command globally. */
2978 this_command_name = words->word->word;
2980 QUIT;
2982 /* This command could be a shell builtin or a user-defined function.
2983 We have already found special builtins by this time, so we do not
2984 set builtin_is_special. If this is a function or builtin, and we
2985 have pipes, then fork a subshell in here. Otherwise, just execute
2986 the command directly. */
2987 if (func == 0 && builtin == 0)
2988 builtin = find_shell_builtin (this_command_name);
2990 last_shell_builtin = this_shell_builtin;
2991 this_shell_builtin = builtin;
2993 if (builtin || func)
2995 if (already_forked)
2997 /* reset_terminating_signals (); */ /* XXX */
2998 /* Cancel traps, in trap.c. */
2999 restore_original_signals ();
3001 if (async)
3003 if ((simple_command->flags & CMD_STDIN_REDIR) &&
3004 pipe_in == NO_PIPE &&
3005 (stdin_redirects (simple_command->redirects) == 0))
3006 async_redirect_stdin ();
3007 setup_async_signals ();
3010 subshell_level++;
3011 execute_subshell_builtin_or_function
3012 (words, simple_command->redirects, builtin, func,
3013 pipe_in, pipe_out, async, fds_to_close,
3014 simple_command->flags);
3015 subshell_level--;
3017 else
3019 result = execute_builtin_or_function
3020 (words, builtin, func, simple_command->redirects, fds_to_close,
3021 simple_command->flags);
3022 if (builtin)
3024 if (result > EX_SHERRBASE)
3026 result = builtin_status (result);
3027 if (builtin_is_special)
3028 special_builtin_failed = 1;
3030 /* In POSIX mode, if there are assignment statements preceding
3031 a special builtin, they persist after the builtin
3032 completes. */
3033 if (posixly_correct && builtin_is_special && temporary_env)
3034 merge_temporary_env ();
3036 else /* function */
3038 if (result == EX_USAGE)
3039 result = EX_BADUSAGE;
3040 else if (result > EX_SHERRBASE)
3041 result = EXECUTION_FAILURE;
3044 set_pipestatus_from_exit (result);
3046 goto return_result;
3050 if (command_line == 0)
3051 command_line = savestring (the_printed_command_except_trap);
3053 #if defined (PROCESS_SUBSTITUTION)
3054 if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
3055 simple_command->flags &= ~CMD_NO_FORK;
3056 #endif
3058 execute_disk_command (words, simple_command->redirects, command_line,
3059 pipe_in, pipe_out, async, fds_to_close,
3060 simple_command->flags);
3062 return_result:
3063 bind_lastarg (lastarg);
3064 FREE (command_line);
3065 dispose_words (words);
3066 discard_unwind_frame ("simple-command");
3067 this_command_name = (char *)NULL; /* points to freed memory now */
3068 return (result);
3071 /* Translate the special builtin exit statuses. We don't really need a
3072 function for this; it's a placeholder for future work. */
3073 static int
3074 builtin_status (result)
3075 int result;
3077 int r;
3079 switch (result)
3081 case EX_USAGE:
3082 r = EX_BADUSAGE;
3083 break;
3084 case EX_REDIRFAIL:
3085 case EX_BADSYNTAX:
3086 case EX_BADASSIGN:
3087 case EX_EXPFAIL:
3088 r = EXECUTION_FAILURE;
3089 break;
3090 default:
3091 r = EXECUTION_SUCCESS;
3092 break;
3094 return (r);
3097 static int
3098 execute_builtin (builtin, words, flags, subshell)
3099 sh_builtin_func_t *builtin;
3100 WORD_LIST *words;
3101 int flags, subshell;
3103 int old_e_flag, result, eval_unwind;
3104 int isbltinenv;
3106 old_e_flag = exit_immediately_on_error;
3107 /* The eval builtin calls parse_and_execute, which does not know about
3108 the setting of flags, and always calls the execution functions with
3109 flags that will exit the shell on an error if -e is set. If the
3110 eval builtin is being called, and we're supposed to ignore the exit
3111 value of the command, we turn the -e flag off ourselves, then
3112 restore it when the command completes. */
3113 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
3115 begin_unwind_frame ("eval_builtin");
3116 unwind_protect_int (exit_immediately_on_error);
3117 exit_immediately_on_error = 0;
3118 eval_unwind = 1;
3120 else
3121 eval_unwind = 0;
3123 /* The temporary environment for a builtin is supposed to apply to
3124 all commands executed by that builtin. Currently, this is a
3125 problem only with the `unset', `source' and `eval' builtins. */
3127 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
3129 if (isbltinenv)
3131 if (subshell == 0)
3132 begin_unwind_frame ("builtin_env");
3134 if (temporary_env)
3136 push_scope (VC_BLTNENV, temporary_env);
3137 if (subshell == 0)
3138 add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
3139 temporary_env = (HASH_TABLE *)NULL;
3143 /* `return' does a longjmp() back to a saved environment in execute_function.
3144 If a variable assignment list preceded the command, and the shell is
3145 running in POSIX mode, we need to merge that into the shell_variables
3146 table, since `return' is a POSIX special builtin. */
3147 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3149 begin_unwind_frame ("return_temp_env");
3150 add_unwind_protect (merge_temporary_env, (char *)NULL);
3153 result = ((*builtin) (words->next));
3155 /* This shouldn't happen, but in case `return' comes back instead of
3156 longjmp'ing, we need to unwind. */
3157 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3158 discard_unwind_frame ("return_temp_env");
3160 if (subshell == 0 && isbltinenv)
3161 run_unwind_frame ("builtin_env");
3163 if (eval_unwind)
3165 exit_immediately_on_error += old_e_flag;
3166 discard_unwind_frame ("eval_builtin");
3169 return (result);
3172 static int
3173 execute_function (var, words, flags, fds_to_close, async, subshell)
3174 SHELL_VAR *var;
3175 WORD_LIST *words;
3176 int flags;
3177 struct fd_bitmap *fds_to_close;
3178 int async, subshell;
3180 int return_val, result;
3181 COMMAND *tc, *fc, *save_current;
3182 char *debug_trap, *error_trap, *return_trap;
3183 #if defined (ARRAY_VARS)
3184 SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
3185 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
3186 #endif
3187 FUNCTION_DEF *shell_fn;
3188 char *sfile, *t;
3189 static int funcnest = 0;
3191 USE_VAR(fc);
3193 #if defined (ARRAY_VARS)
3194 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
3195 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
3196 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
3197 #endif
3199 tc = (COMMAND *)copy_command (function_cell (var));
3200 if (tc && (flags & CMD_IGNORE_RETURN))
3201 tc->flags |= CMD_IGNORE_RETURN;
3203 if (subshell == 0)
3205 begin_unwind_frame ("function_calling");
3206 push_context (var->name, subshell, temporary_env);
3207 add_unwind_protect (pop_context, (char *)NULL);
3208 unwind_protect_int (line_number);
3209 unwind_protect_int (return_catch_flag);
3210 unwind_protect_jmp_buf (return_catch);
3211 add_unwind_protect (dispose_command, (char *)tc);
3212 unwind_protect_pointer (this_shell_function);
3213 unwind_protect_int (loop_level);
3215 else
3216 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
3218 temporary_env = (HASH_TABLE *)NULL;
3220 this_shell_function = var;
3221 make_funcname_visible (1);
3223 debug_trap = TRAP_STRING(DEBUG_TRAP);
3224 error_trap = TRAP_STRING(ERROR_TRAP);
3225 return_trap = TRAP_STRING(RETURN_TRAP);
3227 /* The order of the unwind protects for debug_trap, error_trap and
3228 return_trap is important here! unwind-protect commands are run
3229 in reverse order of registration. If this causes problems, take
3230 out the xfree unwind-protect calls and live with the small memory leak. */
3232 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3233 if the function has the trace attribute set, it inherits the DEBUG trap */
3234 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3236 if (subshell == 0)
3238 debug_trap = savestring (debug_trap);
3239 add_unwind_protect (xfree, debug_trap);
3240 add_unwind_protect (set_debug_trap, debug_trap);
3242 restore_default_signal (DEBUG_TRAP);
3245 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3246 if (error_trap && error_trace_mode == 0)
3248 if (subshell == 0)
3250 error_trap = savestring (error_trap);
3251 add_unwind_protect (xfree, error_trap);
3252 add_unwind_protect (set_error_trap, error_trap);
3254 restore_default_signal (ERROR_TRAP);
3257 /* Shell functions inherit the RETURN trap if function tracing is on
3258 globally or on individually for this function. */
3259 #if 0
3260 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3261 #else
3262 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
3263 #endif
3265 if (subshell == 0)
3267 return_trap = savestring (return_trap);
3268 add_unwind_protect (xfree, return_trap);
3269 add_unwind_protect (set_return_trap, return_trap);
3271 restore_default_signal (RETURN_TRAP);
3274 funcnest++;
3275 #if defined (ARRAY_VARS)
3276 /* This is quite similar to the code in shell.c and elsewhere. */
3277 shell_fn = find_function_def (this_shell_function->name);
3278 sfile = shell_fn ? shell_fn->source_file : "";
3279 array_push (funcname_a, this_shell_function->name);
3281 array_push (bash_source_a, sfile);
3282 t = itos (executing_line_number ());
3283 array_push (bash_lineno_a, t);
3284 free (t);
3285 #endif
3287 /* The temporary environment for a function is supposed to apply to
3288 all commands executed within the function body. */
3290 remember_args (words->next, 1);
3292 /* Update BASH_ARGV and BASH_ARGC */
3293 if (debugging_mode)
3294 push_args (words->next);
3296 /* Number of the line on which the function body starts. */
3297 line_number = function_line_number = tc->line;
3299 #if defined (JOB_CONTROL)
3300 if (subshell)
3301 stop_pipeline (async, (COMMAND *)NULL);
3302 #endif
3304 fc = tc;
3306 return_catch_flag++;
3307 return_val = setjmp (return_catch);
3309 if (return_val)
3311 result = return_catch_value;
3312 /* Run the RETURN trap in the function's context. */
3313 save_current = currently_executing_command;
3314 run_return_trap ();
3315 currently_executing_command = save_current;
3317 else
3319 /* Run the debug trap here so we can trap at the start of a function's
3320 execution rather than the execution of the body's first command. */
3321 showing_function_line = 1;
3322 save_current = currently_executing_command;
3323 result = run_debug_trap ();
3324 #if defined (DEBUGGER)
3325 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3326 skip the command. */
3327 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
3329 showing_function_line = 0;
3330 currently_executing_command = save_current;
3331 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3333 /* Run the RETURN trap in the function's context */
3334 save_current = currently_executing_command;
3335 run_return_trap ();
3336 currently_executing_command = save_current;
3338 #else
3339 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3341 save_current = currently_executing_command;
3342 run_return_trap ();
3343 currently_executing_command = save_current;
3344 #endif
3345 showing_function_line = 0;
3348 /* Restore BASH_ARGC and BASH_ARGV */
3349 if (debugging_mode)
3350 pop_args ();
3352 if (subshell == 0)
3353 run_unwind_frame ("function_calling");
3355 funcnest--;
3356 #if defined (ARRAY_VARS)
3357 /* These two variables cannot be unset, and cannot be affected by the
3358 function. */
3359 array_pop (bash_source_a);
3360 array_pop (bash_lineno_a);
3362 /* FUNCNAME can be unset, and so can potentially be changed by the
3363 function. */
3364 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
3365 if (nfv == funcname_v)
3366 array_pop (funcname_a);
3367 #endif
3369 if (variable_context == 0 || this_shell_function == 0)
3370 make_funcname_visible (0);
3372 return (result);
3375 /* A convenience routine for use by other parts of the shell to execute
3376 a particular shell function. */
3378 execute_shell_function (var, words)
3379 SHELL_VAR *var;
3380 WORD_LIST *words;
3382 int ret;
3383 struct fd_bitmap *bitmap;
3385 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
3386 begin_unwind_frame ("execute-shell-function");
3387 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
3389 ret = execute_function (var, words, 0, bitmap, 0, 0);
3391 dispose_fd_bitmap (bitmap);
3392 discard_unwind_frame ("execute-shell-function");
3394 return ret;
3397 /* Execute a shell builtin or function in a subshell environment. This
3398 routine does not return; it only calls exit(). If BUILTIN is non-null,
3399 it points to a function to call to execute a shell builtin; otherwise
3400 VAR points at the body of a function to execute. WORDS is the arguments
3401 to the command, REDIRECTS specifies redirections to perform before the
3402 command is executed. */
3403 static void
3404 execute_subshell_builtin_or_function (words, redirects, builtin, var,
3405 pipe_in, pipe_out, async, fds_to_close,
3406 flags)
3407 WORD_LIST *words;
3408 REDIRECT *redirects;
3409 sh_builtin_func_t *builtin;
3410 SHELL_VAR *var;
3411 int pipe_in, pipe_out, async;
3412 struct fd_bitmap *fds_to_close;
3413 int flags;
3415 int result, r, funcvalue;
3416 #if defined (JOB_CONTROL)
3417 int jobs_hack;
3419 jobs_hack = (builtin == jobs_builtin) &&
3420 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
3421 #endif
3423 /* A subshell is neither a login shell nor interactive. */
3424 login_shell = interactive = 0;
3426 if (async)
3427 subshell_environment |= SUBSHELL_ASYNC;
3428 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3429 subshell_environment |= SUBSHELL_PIPE;
3431 maybe_make_export_env (); /* XXX - is this needed? */
3433 #if defined (JOB_CONTROL)
3434 /* Eradicate all traces of job control after we fork the subshell, so
3435 all jobs begun by this subshell are in the same process group as
3436 the shell itself. */
3438 /* Allow the output of `jobs' to be piped. */
3439 if (jobs_hack)
3440 kill_current_pipeline ();
3441 else
3442 without_job_control ();
3444 set_sigchld_handler ();
3445 #endif /* JOB_CONTROL */
3447 set_sigint_handler ();
3449 if (fds_to_close)
3450 close_fd_bitmap (fds_to_close);
3452 do_piping (pipe_in, pipe_out);
3454 if (do_redirections (redirects, RX_ACTIVE) != 0)
3455 exit (EXECUTION_FAILURE);
3457 if (builtin)
3459 /* Give builtins a place to jump back to on failure,
3460 so we don't go back up to main(). */
3461 result = setjmp (top_level);
3463 /* Give the return builtin a place to jump to when executed in a subshell
3464 or pipeline */
3465 funcvalue = 0;
3466 if (return_catch_flag && builtin == return_builtin)
3467 funcvalue = setjmp (return_catch);
3469 if (result == EXITPROG)
3470 exit (last_command_exit_value);
3471 else if (result)
3472 exit (EXECUTION_FAILURE);
3473 else if (funcvalue)
3474 exit (return_catch_value);
3475 else
3477 r = execute_builtin (builtin, words, flags, 1);
3478 if (r == EX_USAGE)
3479 r = EX_BADUSAGE;
3480 exit (r);
3483 else
3484 exit (execute_function (var, words, flags, fds_to_close, async, 1));
3487 /* Execute a builtin or function in the current shell context. If BUILTIN
3488 is non-null, it is the builtin command to execute, otherwise VAR points
3489 to the body of a function. WORDS are the command's arguments, REDIRECTS
3490 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3491 file descriptors to close.
3493 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3494 not undone before this function returns. */
3495 static int
3496 execute_builtin_or_function (words, builtin, var, redirects,
3497 fds_to_close, flags)
3498 WORD_LIST *words;
3499 sh_builtin_func_t *builtin;
3500 SHELL_VAR *var;
3501 REDIRECT *redirects;
3502 struct fd_bitmap *fds_to_close;
3503 int flags;
3505 int result;
3506 REDIRECT *saved_undo_list;
3507 sh_builtin_func_t *saved_this_shell_builtin;
3509 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
3511 cleanup_redirects (redirection_undo_list);
3512 redirection_undo_list = (REDIRECT *)NULL;
3513 dispose_exec_redirects ();
3514 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3517 saved_this_shell_builtin = this_shell_builtin;
3518 saved_undo_list = redirection_undo_list;
3520 /* Calling the "exec" builtin changes redirections forever. */
3521 if (builtin == exec_builtin)
3523 dispose_redirects (saved_undo_list);
3524 saved_undo_list = exec_redirection_undo_list;
3525 exec_redirection_undo_list = (REDIRECT *)NULL;
3527 else
3528 dispose_exec_redirects ();
3530 if (saved_undo_list)
3532 begin_unwind_frame ("saved redirects");
3533 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3536 redirection_undo_list = (REDIRECT *)NULL;
3538 if (builtin)
3539 result = execute_builtin (builtin, words, flags, 0);
3540 else
3541 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3543 /* We do this before undoing the effects of any redirections. */
3544 if (ferror (stdout))
3545 clearerr (stdout);
3547 /* If we are executing the `command' builtin, but this_shell_builtin is
3548 set to `exec_builtin', we know that we have something like
3549 `command exec [redirection]', since otherwise `exec' would have
3550 overwritten the shell and we wouldn't get here. In this case, we
3551 want to behave as if the `command' builtin had not been specified
3552 and preserve the redirections. */
3553 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3555 if (saved_undo_list)
3556 dispose_redirects (saved_undo_list);
3557 redirection_undo_list = exec_redirection_undo_list;
3558 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3559 discard_unwind_frame ("saved_redirects");
3562 if (saved_undo_list)
3564 redirection_undo_list = saved_undo_list;
3565 discard_unwind_frame ("saved redirects");
3568 if (redirection_undo_list)
3570 cleanup_redirects (redirection_undo_list);
3571 redirection_undo_list = (REDIRECT *)NULL;
3574 return (result);
3577 void
3578 setup_async_signals ()
3580 #if defined (__BEOS__)
3581 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3582 #endif
3584 #if defined (JOB_CONTROL)
3585 if (job_control == 0)
3586 #endif
3588 set_signal_handler (SIGINT, SIG_IGN);
3589 set_signal_ignored (SIGINT);
3590 set_signal_handler (SIGQUIT, SIG_IGN);
3591 set_signal_ignored (SIGQUIT);
3595 /* Execute a simple command that is hopefully defined in a disk file
3596 somewhere.
3598 1) fork ()
3599 2) connect pipes
3600 3) look up the command
3601 4) do redirections
3602 5) execve ()
3603 6) If the execve failed, see if the file has executable mode set.
3604 If so, and it isn't a directory, then execute its contents as
3605 a shell script.
3607 Note that the filename hashing stuff has to take place up here,
3608 in the parent. This is probably why the Bourne style shells
3609 don't handle it, since that would require them to go through
3610 this gnarly hair, for no good reason.
3612 NOTE: callers expect this to fork or exit(). */
3613 static void
3614 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3615 async, fds_to_close, cmdflags)
3616 WORD_LIST *words;
3617 REDIRECT *redirects;
3618 char *command_line;
3619 int pipe_in, pipe_out, async;
3620 struct fd_bitmap *fds_to_close;
3621 int cmdflags;
3623 char *pathname, *command, **args;
3624 int nofork;
3625 pid_t pid;
3627 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3628 pathname = words->word->word;
3630 #if defined (RESTRICTED_SHELL)
3631 command = (char *)NULL;
3632 if (restricted && xstrchr (pathname, '/'))
3634 internal_error (_("%s: restricted: cannot specify `/' in command names"),
3635 pathname);
3636 last_command_exit_value = EXECUTION_FAILURE;
3638 /* If we're not going to fork below, we must already be in a child
3639 process or a context in which it's safe to call exit(2). */
3640 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3641 exit (last_command_exit_value);
3642 else
3643 goto parent_return;
3645 #endif /* RESTRICTED_SHELL */
3647 command = search_for_command (pathname);
3649 if (command)
3651 maybe_make_export_env ();
3652 put_command_name_into_env (command);
3655 /* We have to make the child before we check for the non-existence
3656 of COMMAND, since we want the error messages to be redirected. */
3657 /* If we can get away without forking and there are no pipes to deal with,
3658 don't bother to fork, just directly exec the command. */
3659 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3660 pid = 0;
3661 else
3662 pid = make_child (savestring (command_line), async);
3664 if (pid == 0)
3666 int old_interactive;
3668 #if 0
3669 /* This has been disabled for the time being. */
3670 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3671 if (posixly_correct == 0)
3672 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
3673 #endif
3674 #endif
3676 /* Cancel traps, in trap.c. */
3677 restore_original_signals ();
3679 /* restore_original_signals may have undone the work done
3680 by make_child to ensure that SIGINT and SIGQUIT are ignored
3681 in asynchronous children. */
3682 if (async)
3684 if ((cmdflags & CMD_STDIN_REDIR) &&
3685 pipe_in == NO_PIPE &&
3686 (stdin_redirects (redirects) == 0))
3687 async_redirect_stdin ();
3688 setup_async_signals ();
3691 /* This functionality is now provided by close-on-exec of the
3692 file descriptors manipulated by redirection and piping.
3693 Some file descriptors still need to be closed in all children
3694 because of the way bash does pipes; fds_to_close is a
3695 bitmap of all such file descriptors. */
3696 if (fds_to_close)
3697 close_fd_bitmap (fds_to_close);
3699 do_piping (pipe_in, pipe_out);
3701 old_interactive = interactive;
3702 if (async)
3703 interactive = 0;
3705 subshell_environment = SUBSHELL_FORK;
3707 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
3709 #if defined (PROCESS_SUBSTITUTION)
3710 /* Try to remove named pipes that may have been created as the
3711 result of redirections. */
3712 unlink_fifo_list ();
3713 #endif /* PROCESS_SUBSTITUTION */
3714 exit (EXECUTION_FAILURE);
3717 if (async)
3718 interactive = old_interactive;
3720 if (command == 0)
3722 internal_error (_("%s: command not found"), pathname);
3723 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3726 /* Execve expects the command name to be in args[0]. So we
3727 leave it there, in the same format that the user used to
3728 type it in. */
3729 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
3730 exit (shell_execve (command, args, export_env));
3732 else
3734 parent_return:
3735 /* Make sure that the pipes are closed in the parent. */
3736 close_pipes (pipe_in, pipe_out);
3737 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3738 unlink_fifo_list ();
3739 #endif
3740 FREE (command);
3744 /* CPP defines to decide whether a particular index into the #! line
3745 corresponds to a valid interpreter name or argument character, or
3746 whitespace. The MSDOS define is to allow \r to be treated the same
3747 as \n. */
3749 #if !defined (MSDOS)
3750 # define STRINGCHAR(ind) \
3751 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3752 # define WHITECHAR(ind) \
3753 (ind < sample_len && whitespace (sample[ind]))
3754 #else /* MSDOS */
3755 # define STRINGCHAR(ind) \
3756 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3757 # define WHITECHAR(ind) \
3758 (ind < sample_len && whitespace (sample[ind]))
3759 #endif /* MSDOS */
3761 static char *
3762 getinterp (sample, sample_len, endp)
3763 char *sample;
3764 int sample_len, *endp;
3766 register int i;
3767 char *execname;
3768 int start;
3770 /* Find the name of the interpreter to exec. */
3771 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
3774 for (start = i; STRINGCHAR(i); i++)
3777 execname = substring (sample, start, i);
3779 if (endp)
3780 *endp = i;
3781 return execname;
3784 #if !defined (HAVE_HASH_BANG_EXEC)
3785 /* If the operating system on which we're running does not handle
3786 the #! executable format, then help out. SAMPLE is the text read
3787 from the file, SAMPLE_LEN characters. COMMAND is the name of
3788 the script; it and ARGS, the arguments given by the user, will
3789 become arguments to the specified interpreter. ENV is the environment
3790 to pass to the interpreter.
3792 The word immediately following the #! is the interpreter to execute.
3793 A single argument to the interpreter is allowed. */
3795 static int
3796 execute_shell_script (sample, sample_len, command, args, env)
3797 char *sample;
3798 int sample_len;
3799 char *command;
3800 char **args, **env;
3802 char *execname, *firstarg;
3803 int i, start, size_increment, larry;
3805 /* Find the name of the interpreter to exec. */
3806 execname = getinterp (sample, sample_len, &i);
3807 size_increment = 1;
3809 /* Now the argument, if any. */
3810 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3813 /* If there is more text on the line, then it is an argument for the
3814 interpreter. */
3816 if (STRINGCHAR(i))
3818 for (start = i; STRINGCHAR(i); i++)
3820 firstarg = substring ((char *)sample, start, i);
3821 size_increment = 2;
3824 larry = strvec_len (args) + size_increment;
3825 args = strvec_resize (args, larry + 1);
3827 for (i = larry - 1; i; i--)
3828 args[i] = args[i - size_increment];
3830 args[0] = execname;
3831 if (firstarg)
3833 args[1] = firstarg;
3834 args[2] = command;
3836 else
3837 args[1] = command;
3839 args[larry] = (char *)NULL;
3841 return (shell_execve (execname, args, env));
3843 #undef STRINGCHAR
3844 #undef WHITECHAR
3846 #endif /* !HAVE_HASH_BANG_EXEC */
3848 static void
3849 initialize_subshell ()
3851 #if defined (ALIAS)
3852 /* Forget about any aliases that we knew of. We are in a subshell. */
3853 delete_all_aliases ();
3854 #endif /* ALIAS */
3856 #if defined (HISTORY)
3857 /* Forget about the history lines we have read. This is a non-interactive
3858 subshell. */
3859 history_lines_this_session = 0;
3860 #endif
3862 #if defined (JOB_CONTROL)
3863 /* Forget about the way job control was working. We are in a subshell. */
3864 without_job_control ();
3865 set_sigchld_handler ();
3866 init_job_stats ();
3867 #endif /* JOB_CONTROL */
3869 /* Reset the values of the shell flags and options. */
3870 reset_shell_flags ();
3871 reset_shell_options ();
3872 reset_shopt_options ();
3874 /* Zero out builtin_env, since this could be a shell script run from a
3875 sourced file with a temporary environment supplied to the `source/.'
3876 builtin. Such variables are not supposed to be exported (empirical
3877 testing with sh and ksh). Just throw it away; don't worry about a
3878 memory leak. */
3879 if (vc_isbltnenv (shell_variables))
3880 shell_variables = shell_variables->down;
3882 clear_unwind_protect_list (0);
3884 /* We're no longer inside a shell function. */
3885 variable_context = return_catch_flag = 0;
3887 /* If we're not interactive, close the file descriptor from which we're
3888 reading the current shell script. */
3889 if (interactive_shell == 0)
3890 unset_bash_input (0);
3893 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3894 # define SETOSTYPE(x) __setostype(x)
3895 #else
3896 # define SETOSTYPE(x)
3897 #endif
3899 #define READ_SAMPLE_BUF(file, buf, len) \
3900 do \
3902 fd = open(file, O_RDONLY); \
3903 if (fd >= 0) \
3905 len = read (fd, buf, 80); \
3906 close (fd); \
3908 else \
3909 len = -1; \
3911 while (0)
3913 /* Call execve (), handling interpreting shell scripts, and handling
3914 exec failures. */
3916 shell_execve (command, args, env)
3917 char *command;
3918 char **args, **env;
3920 struct stat finfo;
3921 int larray, i, fd;
3922 char sample[80];
3923 int sample_len;
3925 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3926 execve (command, args, env);
3927 i = errno; /* error from execve() */
3928 SETOSTYPE (1);
3930 /* If we get to this point, then start checking out the file.
3931 Maybe it is something we can hack ourselves. */
3932 if (i != ENOEXEC)
3934 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3935 internal_error (_("%s: is a directory"), command);
3936 else if (executable_file (command) == 0)
3938 errno = i;
3939 file_error (command);
3941 /* errors not involving the path argument to execve. */
3942 else if (i == E2BIG || i == ENOMEM)
3944 errno = i;
3945 file_error (command);
3947 else
3949 /* The file has the execute bits set, but the kernel refuses to
3950 run it for some reason. See why. */
3951 #if defined (HAVE_HASH_BANG_EXEC)
3952 READ_SAMPLE_BUF (command, sample, sample_len);
3953 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3955 char *interp;
3956 int ilen;
3958 interp = getinterp (sample, sample_len, (int *)NULL);
3959 ilen = strlen (interp);
3960 errno = i;
3961 if (interp[ilen - 1] == '\r')
3963 interp = xrealloc (interp, ilen + 2);
3964 interp[ilen - 1] = '^';
3965 interp[ilen] = 'M';
3966 interp[ilen + 1] = '\0';
3968 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
3969 FREE (interp);
3970 return (EX_NOEXEC);
3972 #endif
3973 errno = i;
3974 file_error (command);
3976 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3979 /* This file is executable.
3980 If it begins with #!, then help out people with losing operating
3981 systems. Otherwise, check to see if it is a binary file by seeing
3982 if the contents of the first line (or up to 80 characters) are in the
3983 ASCII set. If it's a text file, execute the contents as shell commands,
3984 otherwise return 126 (EX_BINARY_FILE). */
3985 READ_SAMPLE_BUF (command, sample, sample_len);
3987 if (sample_len == 0)
3988 return (EXECUTION_SUCCESS);
3990 /* Is this supposed to be an executable script?
3991 If so, the format of the line is "#! interpreter [argument]".
3992 A single argument is allowed. The BSD kernel restricts
3993 the length of the entire line to 32 characters (32 bytes
3994 being the size of the BSD exec header), but we allow 80
3995 characters. */
3996 if (sample_len > 0)
3998 #if !defined (HAVE_HASH_BANG_EXEC)
3999 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4000 return (execute_shell_script (sample, sample_len, command, args, env));
4001 else
4002 #endif
4003 if (check_binary_file (sample, sample_len))
4005 internal_error (_("%s: cannot execute binary file"), command);
4006 return (EX_BINARY_FILE);
4010 /* We have committed to attempting to execute the contents of this file
4011 as shell commands. */
4013 initialize_subshell ();
4015 set_sigint_handler ();
4017 /* Insert the name of this shell into the argument list. */
4018 larray = strvec_len (args) + 1;
4019 args = strvec_resize (args, larray + 1);
4021 for (i = larray - 1; i; i--)
4022 args[i] = args[i - 1];
4024 args[0] = shell_name;
4025 args[1] = command;
4026 args[larray] = (char *)NULL;
4028 if (args[0][0] == '-')
4029 args[0]++;
4031 #if defined (RESTRICTED_SHELL)
4032 if (restricted)
4033 change_flag ('r', FLAG_OFF);
4034 #endif
4036 if (subshell_argv)
4038 /* Can't free subshell_argv[0]; that is shell_name. */
4039 for (i = 1; i < subshell_argc; i++)
4040 free (subshell_argv[i]);
4041 free (subshell_argv);
4044 dispose_command (currently_executing_command); /* XXX */
4045 currently_executing_command = (COMMAND *)NULL;
4047 subshell_argc = larray;
4048 subshell_argv = args;
4049 subshell_envp = env;
4051 unbind_args (); /* remove the positional parameters */
4053 longjmp (subshell_top_level, 1);
4054 /*NOTREACHED*/
4057 static int
4058 execute_intern_function (name, function)
4059 WORD_DESC *name;
4060 COMMAND *function;
4062 SHELL_VAR *var;
4064 if (check_identifier (name, posixly_correct) == 0)
4066 if (posixly_correct && interactive_shell == 0)
4068 last_command_exit_value = EX_USAGE;
4069 jump_to_top_level (ERREXIT);
4071 return (EXECUTION_FAILURE);
4074 var = find_function (name->word);
4075 if (var && (readonly_p (var) || noassign_p (var)))
4077 if (readonly_p (var))
4078 internal_error (_("%s: readonly function"), var->name);
4079 return (EXECUTION_FAILURE);
4082 bind_function (name->word, function);
4083 return (EXECUTION_SUCCESS);
4086 #if defined (INCLUDE_UNUSED)
4087 #if defined (PROCESS_SUBSTITUTION)
4088 void
4089 close_all_files ()
4091 register int i, fd_table_size;
4093 fd_table_size = getdtablesize ();
4094 if (fd_table_size > 256) /* clamp to a reasonable value */
4095 fd_table_size = 256;
4097 for (i = 3; i < fd_table_size; i++)
4098 close (i);
4100 #endif /* PROCESS_SUBSTITUTION */
4101 #endif
4103 static void
4104 close_pipes (in, out)
4105 int in, out;
4107 if (in >= 0)
4108 close (in);
4109 if (out >= 0)
4110 close (out);
4113 static void
4114 dup_error (oldd, newd)
4115 int oldd, newd;
4117 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
4120 /* Redirect input and output to be from and to the specified pipes.
4121 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4122 static void
4123 do_piping (pipe_in, pipe_out)
4124 int pipe_in, pipe_out;
4126 if (pipe_in != NO_PIPE)
4128 if (dup2 (pipe_in, 0) < 0)
4129 dup_error (pipe_in, 0);
4130 if (pipe_in > 0)
4131 close (pipe_in);
4133 if (pipe_out != NO_PIPE)
4135 if (pipe_out != REDIRECT_BOTH)
4137 if (dup2 (pipe_out, 1) < 0)
4138 dup_error (pipe_out, 1);
4139 if (pipe_out == 0 || pipe_out > 1)
4140 close (pipe_out);
4142 else
4144 if (dup2 (1, 2) < 0)
4145 dup_error (1, 2);