Upload Tizen:Base source
[external/bash.git] / execute_cmd.c
1 /* execute_cmd.c -- Execute a COMMAND structure. */
2
3 /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
4
5    This file is part of GNU Bash, the Bourne Again SHell.
6
7    Bash is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation, either version 3 of the License, or
10    (at your option) any later version.
11
12    Bash is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "config.h"
22
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24   #pragma alloca
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
26
27 #include <stdio.h>
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 #  include <sys/file.h>
32 #endif
33 #include "filecntl.h"
34 #include "posixstat.h"
35 #include <signal.h>
36 #ifndef _MINIX
37 #  include <sys/param.h>
38 #endif
39
40 #if defined (HAVE_UNISTD_H)
41 #  include <unistd.h>
42 #endif
43
44 #include "posixtime.h"
45
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 #  include <sys/resource.h>
48 #endif
49
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 #  include <sys/times.h>
52 #endif
53
54 #include <errno.h>
55
56 #if !defined (errno)
57 extern int errno;
58 #endif
59
60 #define NEED_FPURGE_DECL
61
62 #include "bashansi.h"
63 #include "bashintl.h"
64
65 #include "memalloc.h"
66 #include "shell.h"
67 #include <y.tab.h>      /* use <...> so we pick it up from the build directory */
68 #include "flags.h"
69 #include "builtins.h"
70 #include "hashlib.h"
71 #include "jobs.h"
72 #include "execute_cmd.h"
73 #include "findcmd.h"
74 #include "redir.h"
75 #include "trap.h"
76 #include "pathexp.h"
77 #include "hashcmd.h"
78
79 #if defined (COND_COMMAND)
80 #  include "test.h"
81 #endif
82
83 #include "builtins/common.h"
84 #include "builtins/builtext.h"  /* list of builtins */
85
86 #include <glob/strmatch.h>
87 #include <tilde/tilde.h>
88
89 #if defined (BUFFERED_INPUT)
90 #  include "input.h"
91 #endif
92
93 #if defined (ALIAS)
94 #  include "alias.h"
95 #endif
96
97 #if defined (HISTORY)
98 #  include "bashhist.h"
99 #endif
100
101 extern int posixly_correct;
102 extern int expand_aliases;
103 extern int autocd;
104 extern int breaking, continuing, loop_level;
105 extern int parse_and_execute_level, running_trap, sourcelevel;
106 extern int command_string_index, line_number;
107 extern int dot_found_in_search;
108 extern int already_making_children;
109 extern int tempenv_assign_error;
110 extern char *the_printed_command, *shell_name;
111 extern pid_t last_command_subst_pid;
112 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
113 extern char **subshell_argv, **subshell_envp;
114 extern int subshell_argc;
115 #if 0
116 extern char *glob_argv_flags;
117 #endif
118
119 extern int close __P((int));
120
121 /* Static functions defined and used in this file. */
122 static void close_pipes __P((int, int));
123 static void do_piping __P((int, int));
124 static void bind_lastarg __P((char *));
125 static int shell_control_structure __P((enum command_type));
126 static void cleanup_redirects __P((REDIRECT *));
127
128 #if defined (JOB_CONTROL)
129 static int restore_signal_mask __P((sigset_t *));
130 #endif
131
132 static void async_redirect_stdin __P((void));
133
134 static int builtin_status __P((int));
135
136 static int execute_for_command __P((FOR_COM *));
137 #if defined (SELECT_COMMAND)
138 static int print_index_and_element __P((int, int, WORD_LIST *));
139 static void indent __P((int, int));
140 static void print_select_list __P((WORD_LIST *, int, int, int));
141 static char *select_query __P((WORD_LIST *, int, char *, int));
142 static int execute_select_command __P((SELECT_COM *));
143 #endif
144 #if defined (DPAREN_ARITHMETIC)
145 static int execute_arith_command __P((ARITH_COM *));
146 #endif
147 #if defined (COND_COMMAND)
148 static int execute_cond_node __P((COND_COM *));
149 static int execute_cond_command __P((COND_COM *));
150 #endif
151 #if defined (COMMAND_TIMING)
152 static int mkfmt __P((char *, int, int, time_t, int));
153 static void print_formatted_time __P((FILE *, char *,
154                                       time_t, int, time_t, int,
155                                       time_t, int, int));
156 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
157 #endif
158 #if defined (ARITH_FOR_COMMAND)
159 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
160 static int execute_arith_for_command __P((ARITH_FOR_COM *));
161 #endif
162 static int execute_case_command __P((CASE_COM *));
163 static int execute_while_command __P((WHILE_COM *));
164 static int execute_until_command __P((WHILE_COM *));
165 static int execute_while_or_until __P((WHILE_COM *, int));
166 static int execute_if_command __P((IF_COM *));
167 static int execute_null_command __P((REDIRECT *, int, int, int));
168 static void fix_assignment_words __P((WORD_LIST *));
169 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
170 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
171 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
172 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
173                                             SHELL_VAR *,
174                                             REDIRECT *, struct fd_bitmap *, int));
175 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
176                                                       sh_builtin_func_t *,
177                                                       SHELL_VAR *,
178                                                       int, int, int,
179                                                       struct fd_bitmap *,
180                                                       int));
181 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
182                                       int, int, int, struct fd_bitmap *, int));
183
184 static char *getinterp __P((char *, int, int *));
185 static void initialize_subshell __P((void));
186 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
187 #if defined (COPROCESS_SUPPORT)
188 static int execute_coproc __P((COMMAND *, int, int, struct fd_bitmap *));
189 #endif
190
191 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
192
193 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
194
195 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
196
197 /* Set to 1 if fd 0 was the subject of redirection to a subshell.  Global
198    so that reader_loop can set it to zero before executing a command. */
199 int stdin_redir;
200
201 /* The name of the command that is currently being executed.
202    `test' needs this, for example. */
203 char *this_command_name;
204
205 /* The printed representation of the currently-executing command (same as
206    the_printed_command), except when a trap is being executed.  Useful for
207    a debugger to know where exactly the program is currently executing. */
208 char *the_printed_command_except_trap;
209
210 /* For catching RETURN in a function. */
211 int return_catch_flag;
212 int return_catch_value;
213 procenv_t return_catch;
214
215 /* The value returned by the last synchronous command. */
216 int last_command_exit_value;
217
218 /* Whether or not the last command (corresponding to last_command_exit_value)
219    was terminated by a signal, and, if so, which one. */
220 int last_command_exit_signal;
221
222 /* The list of redirections to perform which will undo the redirections
223    that I made in the shell. */
224 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
225
226 /* The list of redirections to perform which will undo the internal
227    redirections performed by the `exec' builtin.  These are redirections
228    that must be undone even when exec discards redirection_undo_list. */
229 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
230
231 /* When greater than zero, value is the `level' of builtins we are
232    currently executing (e.g. `eval echo a' would have it set to 2). */
233 int executing_builtin = 0;
234
235 /* Non-zero if we are executing a command list (a;b;c, etc.) */
236 int executing_list = 0;
237
238 /* Non-zero if failing commands in a command substitution should not exit the
239    shell even if -e is set.  Used to pass the CMD_IGNORE_RETURN flag down to
240    commands run in command substitutions by parse_and_execute. */
241 int comsub_ignore_return = 0;
242
243 /* Non-zero if we have just forked and are currently running in a subshell
244    environment. */
245 int subshell_environment;
246
247 /* Count of nested subshells, like SHLVL.  Available via $BASH_SUBSHELL */
248 int subshell_level = 0;
249
250 /* Currently-executing shell function. */
251 SHELL_VAR *this_shell_function;
252
253 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
254 int match_ignore_case = 0;
255
256 struct stat SB;         /* used for debugging */
257
258 static int special_builtin_failed;
259
260 static COMMAND *currently_executing_command;
261
262 /* The line number that the currently executing function starts on. */
263 static int function_line_number;
264
265 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
266    number containing the function name.  Used by executing_line_number to
267    report the correct line number.  Kind of a hack. */
268 static int showing_function_line;
269
270 static int line_number_for_err_trap;
271
272 /* A sort of function nesting level counter */
273 static int funcnest = 0;
274 int funcnest_max = 0;           /* XXX - for bash-4.2 */
275
276 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
277
278 #define FD_BITMAP_DEFAULT_SIZE 32
279
280 /* Functions to allocate and deallocate the structures used to pass
281    information from the shell to its children about file descriptors
282    to close. */
283 struct fd_bitmap *
284 new_fd_bitmap (size)
285      int size;
286 {
287   struct fd_bitmap *ret;
288
289   ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
290
291   ret->size = size;
292
293   if (size)
294     {
295       ret->bitmap = (char *)xmalloc (size);
296       memset (ret->bitmap, '\0', size);
297     }
298   else
299     ret->bitmap = (char *)NULL;
300   return (ret);
301 }
302
303 void
304 dispose_fd_bitmap (fdbp)
305      struct fd_bitmap *fdbp;
306 {
307   FREE (fdbp->bitmap);
308   free (fdbp);
309 }
310
311 void
312 close_fd_bitmap (fdbp)
313      struct fd_bitmap *fdbp;
314 {
315   register int i;
316
317   if (fdbp)
318     {
319       for (i = 0; i < fdbp->size; i++)
320         if (fdbp->bitmap[i])
321           {
322             close (i);
323             fdbp->bitmap[i] = 0;
324           }
325     }
326 }
327
328 /* Return the line number of the currently executing command. */
329 int
330 executing_line_number ()
331 {
332   if (executing && showing_function_line == 0 &&
333       (variable_context == 0 || interactive_shell == 0) &&
334       currently_executing_command)
335     {
336 #if defined (COND_COMMAND)
337       if (currently_executing_command->type == cm_cond)
338         return currently_executing_command->value.Cond->line;
339 #endif
340 #if defined (DPAREN_ARITHMETIC)
341       else if (currently_executing_command->type == cm_arith)
342         return currently_executing_command->value.Arith->line;
343 #endif
344 #if defined (ARITH_FOR_COMMAND)
345       else if (currently_executing_command->type == cm_arith_for)
346         return currently_executing_command->value.ArithFor->line;
347 #endif
348
349         return line_number;
350     }
351   else
352     return line_number;
353 }
354
355 /* Execute the command passed in COMMAND.  COMMAND is exactly what
356    read_command () places into GLOBAL_COMMAND.  See "command.h" for the
357    details of the command structure.
358
359    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
360    return values.  Executing a command with nothing in it returns
361    EXECUTION_SUCCESS. */
362 int
363 execute_command (command)
364      COMMAND *command;
365 {
366   struct fd_bitmap *bitmap;
367   int result;
368
369   current_fds_to_close = (struct fd_bitmap *)NULL;
370   bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
371   begin_unwind_frame ("execute-command");
372   add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
373
374   /* Just do the command, but not asynchronously. */
375   result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
376
377   dispose_fd_bitmap (bitmap);
378   discard_unwind_frame ("execute-command");
379
380 #if defined (PROCESS_SUBSTITUTION)
381   /* don't unlink fifos if we're in a shell function; wait until the function
382      returns. */
383   if (variable_context == 0)
384     unlink_fifo_list ();
385 #endif /* PROCESS_SUBSTITUTION */
386
387   QUIT;
388   return (result);
389 }
390
391 /* Return 1 if TYPE is a shell control structure type. */
392 static int
393 shell_control_structure (type)
394      enum command_type type;
395 {
396   switch (type)
397     {
398 #if defined (ARITH_FOR_COMMAND)
399     case cm_arith_for:
400 #endif
401 #if defined (SELECT_COMMAND)
402     case cm_select:
403 #endif
404 #if defined (DPAREN_ARITHMETIC)
405     case cm_arith:
406 #endif
407 #if defined (COND_COMMAND)
408     case cm_cond:
409 #endif
410     case cm_case:
411     case cm_while:
412     case cm_until:
413     case cm_if:
414     case cm_for:
415     case cm_group:
416     case cm_function_def:
417       return (1);
418
419     default:
420       return (0);
421     }
422 }
423
424 /* A function to use to unwind_protect the redirection undo list
425    for loops. */
426 static void
427 cleanup_redirects (list)
428      REDIRECT *list;
429 {
430   do_redirections (list, RX_ACTIVE);
431   dispose_redirects (list);
432 }
433
434 #if 0
435 /* Function to unwind_protect the redirections for functions and builtins. */
436 static void
437 cleanup_func_redirects (list)
438      REDIRECT *list;
439 {
440   do_redirections (list, RX_ACTIVE);
441 }
442 #endif
443
444 void
445 dispose_exec_redirects ()
446 {
447   if (exec_redirection_undo_list)
448     {
449       dispose_redirects (exec_redirection_undo_list);
450       exec_redirection_undo_list = (REDIRECT *)NULL;
451     }
452 }
453
454 #if defined (JOB_CONTROL)
455 /* A function to restore the signal mask to its proper value when the shell
456    is interrupted or errors occur while creating a pipeline. */
457 static int
458 restore_signal_mask (set)
459      sigset_t *set;
460 {
461   return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
462 }
463 #endif /* JOB_CONTROL */
464
465 #ifdef DEBUG
466 /* A debugging function that can be called from gdb, for instance. */
467 void
468 open_files ()
469 {
470   register int i;
471   int f, fd_table_size;
472
473   fd_table_size = getdtablesize ();
474
475   fprintf (stderr, "pid %ld open files:", (long)getpid ());
476   for (i = 3; i < fd_table_size; i++)
477     {
478       if ((f = fcntl (i, F_GETFD, 0)) != -1)
479         fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
480     }
481   fprintf (stderr, "\n");
482 }
483 #endif
484
485 static void
486 async_redirect_stdin ()
487 {
488   int fd;
489
490   fd = open ("/dev/null", O_RDONLY);
491   if (fd > 0)
492     {
493       dup2 (fd, 0);
494       close (fd);
495     }
496   else if (fd < 0)
497     internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
498 }
499
500 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
501
502 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
503    COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
504    ASYNCHROUNOUS, if non-zero, says to do this command in the background.
505    PIPE_IN and PIPE_OUT are file descriptors saying where input comes
506    from and where it goes.  They can have the value of NO_PIPE, which means
507    I/O is stdin/stdout.
508    FDS_TO_CLOSE is a list of file descriptors to close once the child has
509    been forked.  This list often contains the unusable sides of pipes, etc.
510
511    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
512    return values.  Executing a command with nothing in it returns
513    EXECUTION_SUCCESS. */
514 int
515 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
516                           fds_to_close)
517      COMMAND *command;
518      int asynchronous;
519      int pipe_in, pipe_out;
520      struct fd_bitmap *fds_to_close;
521 {
522   int exec_result, user_subshell, invert, ignore_return, was_error_trap;
523   REDIRECT *my_undo_list, *exec_undo_list;
524   volatile int last_pid;
525   volatile int save_line_number;
526
527 #if 0
528   if (command == 0 || breaking || continuing || read_but_dont_execute)
529     return (EXECUTION_SUCCESS);
530 #else
531   if (breaking || continuing)
532     return (last_command_exit_value);
533   if (command == 0 || read_but_dont_execute)
534     return (EXECUTION_SUCCESS);
535 #endif
536
537   QUIT;
538   run_pending_traps ();
539
540 #if 0
541   if (running_trap == 0)
542 #endif
543     currently_executing_command = command;
544
545   invert = (command->flags & CMD_INVERT_RETURN) != 0;
546
547   /* If we're inverting the return value and `set -e' has been executed,
548      we don't want a failing command to inadvertently cause the shell
549      to exit. */
550   if (exit_immediately_on_error && invert)      /* XXX */
551     command->flags |= CMD_IGNORE_RETURN;        /* XXX */
552
553   exec_result = EXECUTION_SUCCESS;
554
555   /* If a command was being explicitly run in a subshell, or if it is
556      a shell control-structure, and it has a pipe, then we do the command
557      in a subshell. */
558   if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
559     return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
560
561 #if defined (COPROCESS_SUPPORT)
562   if (command->type == cm_coproc)
563     return (execute_coproc (command, pipe_in, pipe_out, fds_to_close));
564 #endif
565
566   user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
567
568   if (command->type == cm_subshell ||
569       (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
570       (shell_control_structure (command->type) &&
571        (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
572     {
573       pid_t paren_pid;
574
575       /* Fork a subshell, turn off the subshell bit, turn off job
576          control and call execute_command () on the command again. */
577       line_number_for_err_trap = line_number;
578       paren_pid = make_child (savestring (make_command_string (command)),
579                               asynchronous);
580       if (paren_pid == 0)
581         exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
582         /* NOTREACHED */
583       else
584         {
585           close_pipes (pipe_in, pipe_out);
586
587 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
588           unlink_fifo_list ();
589 #endif
590           /* If we are part of a pipeline, and not the end of the pipeline,
591              then we should simply return and let the last command in the
592              pipe be waited for.  If we are not in a pipeline, or are the
593              last command in the pipeline, then we wait for the subshell
594              and return its exit status as usual. */
595           if (pipe_out != NO_PIPE)
596             return (EXECUTION_SUCCESS);
597
598           stop_pipeline (asynchronous, (COMMAND *)NULL);
599
600           if (asynchronous == 0)
601             {
602               was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
603               invert = (command->flags & CMD_INVERT_RETURN) != 0;
604               ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
605
606               last_command_exit_value = wait_for (paren_pid);
607
608               /* If we have to, invert the return value. */
609               if (invert)
610                 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
611                                 ? EXECUTION_FAILURE
612                                 : EXECUTION_SUCCESS);
613               else
614                 exec_result = last_command_exit_value;
615
616               if (user_subshell && was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
617                 {
618                   last_command_exit_value = exec_result;
619                   save_line_number = line_number;
620                   line_number = line_number_for_err_trap;
621                   run_error_trap ();
622                   line_number = save_line_number;
623                 }
624
625               if (user_subshell && ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
626                 {
627                   last_command_exit_value = exec_result;
628                   run_pending_traps ();
629                   jump_to_top_level (ERREXIT);
630                 }
631
632               return (last_command_exit_value = exec_result);
633             }
634           else
635             {
636               DESCRIBE_PID (paren_pid);
637
638               run_pending_traps ();
639
640               return (EXECUTION_SUCCESS);
641             }
642         }
643     }
644
645 #if defined (COMMAND_TIMING)
646   if (command->flags & CMD_TIME_PIPELINE)
647     {
648       if (asynchronous)
649         {
650           command->flags |= CMD_FORCE_SUBSHELL;
651           exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
652         }
653       else
654         {
655           exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
656 #if 0
657           if (running_trap == 0)
658 #endif
659             currently_executing_command = (COMMAND *)NULL;
660         }
661       return (exec_result);
662     }
663 #endif /* COMMAND_TIMING */
664
665   if (shell_control_structure (command->type) && command->redirects)
666     stdin_redir = stdin_redirects (command->redirects);
667
668   /* Handle WHILE FOR CASE etc. with redirections.  (Also '&' input
669      redirection.)  */
670   if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
671     {
672       cleanup_redirects (redirection_undo_list);
673       redirection_undo_list = (REDIRECT *)NULL;
674       dispose_exec_redirects ();
675       return (last_command_exit_value = EXECUTION_FAILURE);
676     }
677
678   if (redirection_undo_list)
679     {
680       my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
681       dispose_redirects (redirection_undo_list);
682       redirection_undo_list = (REDIRECT *)NULL;
683     }
684   else
685     my_undo_list = (REDIRECT *)NULL;
686
687   if (exec_redirection_undo_list)
688     {
689       exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
690       dispose_redirects (exec_redirection_undo_list);
691       exec_redirection_undo_list = (REDIRECT *)NULL;
692     }
693   else
694     exec_undo_list = (REDIRECT *)NULL;
695
696   if (my_undo_list || exec_undo_list)
697     begin_unwind_frame ("loop_redirections");
698
699   if (my_undo_list)
700     add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
701
702   if (exec_undo_list)
703     add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
704
705   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
706
707   QUIT;
708
709   switch (command->type)
710     {
711     case cm_simple:
712       {
713         save_line_number = line_number;
714         /* We can't rely on variables retaining their values across a
715            call to execute_simple_command if a longjmp occurs as the
716            result of a `return' builtin.  This is true for sure with gcc. */
717 #if defined (RECYCLES_PIDS)
718         last_made_pid = NO_PID;
719 #endif
720         last_pid = last_made_pid;
721         was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
722
723         if (ignore_return && command->value.Simple)
724           command->value.Simple->flags |= CMD_IGNORE_RETURN;
725         if (command->flags & CMD_STDIN_REDIR)
726           command->value.Simple->flags |= CMD_STDIN_REDIR;
727
728         line_number_for_err_trap = line_number = command->value.Simple->line;
729         exec_result =
730           execute_simple_command (command->value.Simple, pipe_in, pipe_out,
731                                   asynchronous, fds_to_close);
732         line_number = save_line_number;
733
734         /* The temporary environment should be used for only the simple
735            command immediately following its definition. */
736         dispose_used_env_vars ();
737
738 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
739         /* Reclaim memory allocated with alloca () on machines which
740            may be using the alloca emulation code. */
741         (void) alloca (0);
742 #endif /* (ultrix && mips) || C_ALLOCA */
743
744         /* If we forked to do the command, then we must wait_for ()
745            the child. */
746
747         /* XXX - this is something to watch out for if there are problems
748            when the shell is compiled without job control. */
749         if (already_making_children && pipe_out == NO_PIPE &&
750             last_made_pid != last_pid)
751           {
752             stop_pipeline (asynchronous, (COMMAND *)NULL);
753
754             if (asynchronous)
755               {
756                 DESCRIBE_PID (last_made_pid);
757               }
758             else
759 #if !defined (JOB_CONTROL)
760               /* Do not wait for asynchronous processes started from
761                  startup files. */
762             if (last_made_pid != last_asynchronous_pid)
763 #endif
764             /* When executing a shell function that executes other
765                commands, this causes the last simple command in
766                the function to be waited for twice.  This also causes
767                subshells forked to execute builtin commands (e.g., in
768                pipelines) to be waited for twice. */
769               exec_result = wait_for (last_made_pid);
770           }
771       }
772
773       /* 2009/02/13 -- pipeline failure is processed elsewhere.  This handles
774          only the failure of a simple command. */
775       if (was_error_trap && ignore_return == 0 && invert == 0 && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)
776         {
777           last_command_exit_value = exec_result;
778           line_number = line_number_for_err_trap;
779           run_error_trap ();
780           line_number = save_line_number;
781         }
782
783       if (ignore_return == 0 && invert == 0 &&
784           ((posixly_correct && interactive == 0 && special_builtin_failed) ||
785            (exit_immediately_on_error && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)))
786         {
787           last_command_exit_value = exec_result;
788           run_pending_traps ();
789           jump_to_top_level (ERREXIT);
790         }
791
792       break;
793
794     case cm_for:
795       if (ignore_return)
796         command->value.For->flags |= CMD_IGNORE_RETURN;
797       exec_result = execute_for_command (command->value.For);
798       break;
799
800 #if defined (ARITH_FOR_COMMAND)
801     case cm_arith_for:
802       if (ignore_return)
803         command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
804       exec_result = execute_arith_for_command (command->value.ArithFor);
805       break;
806 #endif
807
808 #if defined (SELECT_COMMAND)
809     case cm_select:
810       if (ignore_return)
811         command->value.Select->flags |= CMD_IGNORE_RETURN;
812       exec_result = execute_select_command (command->value.Select);
813       break;
814 #endif
815
816     case cm_case:
817       if (ignore_return)
818         command->value.Case->flags |= CMD_IGNORE_RETURN;
819       exec_result = execute_case_command (command->value.Case);
820       break;
821
822     case cm_while:
823       if (ignore_return)
824         command->value.While->flags |= CMD_IGNORE_RETURN;
825       exec_result = execute_while_command (command->value.While);
826       break;
827
828     case cm_until:
829       if (ignore_return)
830         command->value.While->flags |= CMD_IGNORE_RETURN;
831       exec_result = execute_until_command (command->value.While);
832       break;
833
834     case cm_if:
835       if (ignore_return)
836         command->value.If->flags |= CMD_IGNORE_RETURN;
837       exec_result = execute_if_command (command->value.If);
838       break;
839
840     case cm_group:
841
842       /* This code can be executed from either of two paths: an explicit
843          '{}' command, or via a function call.  If we are executed via a
844          function call, we have already taken care of the function being
845          executed in the background (down there in execute_simple_command ()),
846          and this command should *not* be marked as asynchronous.  If we
847          are executing a regular '{}' group command, and asynchronous == 1,
848          we must want to execute the whole command in the background, so we
849          need a subshell, and we want the stuff executed in that subshell
850          (this group command) to be executed in the foreground of that
851          subshell (i.e. there will not be *another* subshell forked).
852
853          What we do is to force a subshell if asynchronous, and then call
854          execute_command_internal again with asynchronous still set to 1,
855          but with the original group command, so the printed command will
856          look right.
857
858          The code above that handles forking off subshells will note that
859          both subshell and async are on, and turn off async in the child
860          after forking the subshell (but leave async set in the parent, so
861          the normal call to describe_pid is made).  This turning off
862          async is *crucial*; if it is not done, this will fall into an
863          infinite loop of executions through this spot in subshell after
864          subshell until the process limit is exhausted. */
865
866       if (asynchronous)
867         {
868           command->flags |= CMD_FORCE_SUBSHELL;
869           exec_result =
870             execute_command_internal (command, 1, pipe_in, pipe_out,
871                                       fds_to_close);
872         }
873       else
874         {
875           if (ignore_return && command->value.Group->command)
876             command->value.Group->command->flags |= CMD_IGNORE_RETURN;
877           exec_result =
878             execute_command_internal (command->value.Group->command,
879                                       asynchronous, pipe_in, pipe_out,
880                                       fds_to_close);
881         }
882       break;
883
884     case cm_connection:
885       exec_result = execute_connection (command, asynchronous,
886                                         pipe_in, pipe_out, fds_to_close);
887       break;
888
889 #if defined (DPAREN_ARITHMETIC)
890     case cm_arith:
891       was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
892       if (ignore_return)
893         command->value.Arith->flags |= CMD_IGNORE_RETURN;
894       line_number_for_err_trap = save_line_number = line_number;
895       exec_result = execute_arith_command (command->value.Arith);
896       line_number = save_line_number;
897
898       if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
899         {
900           last_command_exit_value = exec_result;
901           save_line_number = line_number;
902           line_number = line_number_for_err_trap;
903           run_error_trap ();
904           line_number = save_line_number;
905         }
906
907       if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
908         {
909           last_command_exit_value = exec_result;
910           run_pending_traps ();
911           jump_to_top_level (ERREXIT);
912         }
913
914       break;
915 #endif
916
917 #if defined (COND_COMMAND)
918     case cm_cond:
919       was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
920       if (ignore_return)
921         command->value.Cond->flags |= CMD_IGNORE_RETURN;
922
923       line_number_for_err_trap = save_line_number = line_number;
924       exec_result = execute_cond_command (command->value.Cond);
925       line_number = save_line_number;
926
927       if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
928         {
929           last_command_exit_value = exec_result;
930           save_line_number = line_number;
931           line_number = line_number_for_err_trap;
932           run_error_trap ();
933           line_number = save_line_number;
934         }
935
936       if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
937         {
938           last_command_exit_value = exec_result;
939           run_pending_traps ();
940           jump_to_top_level (ERREXIT);
941         }
942
943       break;
944 #endif
945     
946     case cm_function_def:
947       exec_result = execute_intern_function (command->value.Function_def->name,
948                                              command->value.Function_def->command);
949       break;
950
951     default:
952       command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
953     }
954
955   if (my_undo_list)
956     {
957       do_redirections (my_undo_list, RX_ACTIVE);
958       dispose_redirects (my_undo_list);
959     }
960
961   if (exec_undo_list)
962     dispose_redirects (exec_undo_list);
963
964   if (my_undo_list || exec_undo_list)
965     discard_unwind_frame ("loop_redirections");
966
967   /* Invert the return value if we have to */
968   if (invert)
969     exec_result = (exec_result == EXECUTION_SUCCESS)
970                     ? EXECUTION_FAILURE
971                     : EXECUTION_SUCCESS;
972
973 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
974   /* This is where we set PIPESTATUS from the exit status of the appropriate
975      compound commands (the ones that look enough like simple commands to
976      cause confusion).  We might be able to optimize by not doing this if
977      subshell_environment != 0. */
978   switch (command->type)
979     {
980 #  if defined (DPAREN_ARITHMETIC)
981     case cm_arith:
982 #  endif
983 #  if defined (COND_COMMAND)
984     case cm_cond:
985 #  endif
986       set_pipestatus_from_exit (exec_result);
987       break;
988     }
989 #endif
990
991   last_command_exit_value = exec_result;
992   run_pending_traps ();
993 #if 0
994   if (running_trap == 0)
995 #endif
996     currently_executing_command = (COMMAND *)NULL;
997   return (last_command_exit_value);
998 }
999
1000 #if defined (COMMAND_TIMING)
1001
1002 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1003 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
1004 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
1005 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
1006 #endif
1007
1008 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1009 #define BASH_TIMEFORMAT  "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1010
1011 static const int precs[] = { 0, 100, 10, 1 };
1012
1013 /* Expand one `%'-prefixed escape sequence from a time format string. */
1014 static int
1015 mkfmt (buf, prec, lng, sec, sec_fraction)
1016      char *buf;
1017      int prec, lng;
1018      time_t sec;
1019      int sec_fraction;
1020 {
1021   time_t min;
1022   char abuf[INT_STRLEN_BOUND(time_t) + 1];
1023   int ind, aind;
1024
1025   ind = 0;
1026   abuf[sizeof(abuf) - 1] = '\0';
1027
1028   /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1029   if (lng)
1030     {
1031       min = sec / 60;
1032       sec %= 60;
1033       aind = sizeof(abuf) - 2;
1034       do
1035         abuf[aind--] = (min % 10) + '0';
1036       while (min /= 10);
1037       aind++;
1038       while (abuf[aind])
1039         buf[ind++] = abuf[aind++];
1040       buf[ind++] = 'm';
1041     }
1042
1043   /* Now add the seconds. */
1044   aind = sizeof (abuf) - 2;
1045   do
1046     abuf[aind--] = (sec % 10) + '0';
1047   while (sec /= 10);
1048   aind++;
1049   while (abuf[aind])
1050     buf[ind++] = abuf[aind++];
1051
1052   /* We want to add a decimal point and PREC places after it if PREC is
1053      nonzero.  PREC is not greater than 3.  SEC_FRACTION is between 0
1054      and 999. */
1055   if (prec != 0)
1056     {
1057       buf[ind++] = '.';
1058       for (aind = 1; aind <= prec; aind++)
1059         {
1060           buf[ind++] = (sec_fraction / precs[aind]) + '0';
1061           sec_fraction %= precs[aind];
1062         }
1063     }
1064
1065   if (lng)
1066     buf[ind++] = 's';
1067   buf[ind] = '\0';
1068
1069   return (ind);
1070 }
1071
1072 /* Interpret the format string FORMAT, interpolating the following escape
1073    sequences:
1074                 %[prec][l][RUS]
1075
1076    where the optional `prec' is a precision, meaning the number of
1077    characters after the decimal point, the optional `l' means to format
1078    using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1079    and the last character is one of
1080    
1081                 R       number of seconds of `real' time
1082                 U       number of seconds of `user' time
1083                 S       number of seconds of `system' time
1084
1085    An occurrence of `%%' in the format string is translated to a `%'.  The
1086    result is printed to FP, a pointer to a FILE.  The other variables are
1087    the seconds and thousandths of a second of real, user, and system time,
1088    resectively. */
1089 static void
1090 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1091      FILE *fp;
1092      char *format;
1093      time_t rs;
1094      int rsf;
1095      time_t us;
1096      int usf;
1097      time_t ss;
1098      int ssf, cpu;
1099 {
1100   int prec, lng, len;
1101   char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1102   time_t sum;
1103   int sum_frac;
1104   int sindex, ssize;
1105
1106   len = strlen (format);
1107   ssize = (len + 64) - (len % 64);
1108   str = (char *)xmalloc (ssize);
1109   sindex = 0;
1110
1111   for (s = format; *s; s++)
1112     {
1113       if (*s != '%' || s[1] == '\0')
1114         {
1115           RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1116           str[sindex++] = *s;
1117         }
1118       else if (s[1] == '%')
1119         {
1120           s++;
1121           RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1122           str[sindex++] = *s;
1123         }
1124       else if (s[1] == 'P')
1125         {
1126           s++;
1127 #if 0
1128           /* clamp CPU usage at 100% */
1129           if (cpu > 10000)
1130             cpu = 10000;
1131 #endif
1132           sum = cpu / 100;
1133           sum_frac = (cpu % 100) * 10;
1134           len = mkfmt (ts, 2, 0, sum, sum_frac);
1135           RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1136           strcpy (str + sindex, ts);
1137           sindex += len;
1138         }
1139       else
1140         {
1141           prec = 3;     /* default is three places past the decimal point. */
1142           lng = 0;      /* default is to not use minutes or append `s' */
1143           s++;
1144           if (DIGIT (*s))               /* `precision' */
1145             {
1146               prec = *s++ - '0';
1147               if (prec > 3) prec = 3;
1148             }
1149           if (*s == 'l')                /* `length extender' */
1150             {
1151               lng = 1;
1152               s++;
1153             }
1154           if (*s == 'R' || *s == 'E')
1155             len = mkfmt (ts, prec, lng, rs, rsf);
1156           else if (*s == 'U')
1157             len = mkfmt (ts, prec, lng, us, usf);
1158           else if (*s == 'S')
1159             len = mkfmt (ts, prec, lng, ss, ssf);
1160           else
1161             {
1162               internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1163               free (str);
1164               return;
1165             }
1166           RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1167           strcpy (str + sindex, ts);
1168           sindex += len;
1169         }
1170     }
1171
1172   str[sindex] = '\0';
1173   fprintf (fp, "%s\n", str);
1174   fflush (fp);
1175
1176   free (str);
1177 }
1178
1179 static int
1180 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1181      COMMAND *command;
1182      int asynchronous, pipe_in, pipe_out;
1183      struct fd_bitmap *fds_to_close;
1184 {
1185   int rv, posix_time, old_flags;
1186   time_t rs, us, ss;
1187   int rsf, usf, ssf;
1188   int cpu;
1189   char *time_format;
1190
1191 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1192   struct timeval real, user, sys;
1193   struct timeval before, after;
1194 #  if defined (HAVE_STRUCT_TIMEZONE)
1195   struct timezone dtz;                          /* posix doesn't define this */
1196 #  endif
1197   struct rusage selfb, selfa, kidsb, kidsa;     /* a = after, b = before */
1198 #else
1199 #  if defined (HAVE_TIMES)
1200   clock_t tbefore, tafter, real, user, sys;
1201   struct tms before, after;
1202 #  endif
1203 #endif
1204
1205 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1206 #  if defined (HAVE_STRUCT_TIMEZONE)
1207   gettimeofday (&before, &dtz);
1208 #  else
1209   gettimeofday (&before, (void *)NULL);
1210 #  endif /* !HAVE_STRUCT_TIMEZONE */
1211   getrusage (RUSAGE_SELF, &selfb);
1212   getrusage (RUSAGE_CHILDREN, &kidsb);
1213 #else
1214 #  if defined (HAVE_TIMES)
1215   tbefore = times (&before);
1216 #  endif
1217 #endif
1218
1219   posix_time = (command->flags & CMD_TIME_POSIX);
1220
1221   old_flags = command->flags;
1222   command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1223   rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1224   command->flags = old_flags;
1225
1226   rs = us = ss = 0;
1227   rsf = usf = ssf = cpu = 0;
1228
1229 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1230 #  if defined (HAVE_STRUCT_TIMEZONE)
1231   gettimeofday (&after, &dtz);
1232 #  else
1233   gettimeofday (&after, (void *)NULL);
1234 #  endif /* !HAVE_STRUCT_TIMEZONE */
1235   getrusage (RUSAGE_SELF, &selfa);
1236   getrusage (RUSAGE_CHILDREN, &kidsa);
1237
1238   difftimeval (&real, &before, &after);
1239   timeval_to_secs (&real, &rs, &rsf);
1240
1241   addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1242                      difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1243   timeval_to_secs (&user, &us, &usf);
1244
1245   addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1246                     difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1247   timeval_to_secs (&sys, &ss, &ssf);
1248
1249   cpu = timeval_to_cpu (&real, &user, &sys);
1250 #else
1251 #  if defined (HAVE_TIMES)
1252   tafter = times (&after);
1253
1254   real = tafter - tbefore;
1255   clock_t_to_secs (real, &rs, &rsf);
1256
1257   user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1258   clock_t_to_secs (user, &us, &usf);
1259
1260   sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1261   clock_t_to_secs (sys, &ss, &ssf);
1262
1263   cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1264
1265 #  else
1266   rs = us = ss = 0;
1267   rsf = usf = ssf = cpu = 0;
1268 #  endif
1269 #endif
1270
1271   if (posix_time)
1272     time_format = POSIX_TIMEFORMAT;
1273   else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1274     time_format = BASH_TIMEFORMAT;
1275
1276   if (time_format && *time_format)
1277     print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1278
1279   return rv;
1280 }
1281 #endif /* COMMAND_TIMING */
1282
1283 /* Execute a command that's supposed to be in a subshell.  This must be
1284    called after make_child and we must be running in the child process.
1285    The caller will return or exit() immediately with the value this returns. */
1286 static int
1287 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1288      COMMAND *command;
1289      int asynchronous;
1290      int pipe_in, pipe_out;
1291      struct fd_bitmap *fds_to_close;
1292 {
1293   int user_subshell, return_code, function_value, should_redir_stdin, invert;
1294   int ois, user_coproc;
1295   int result;
1296   COMMAND *tcom;
1297
1298   USE_VAR(user_subshell);
1299   USE_VAR(user_coproc);
1300   USE_VAR(invert);
1301   USE_VAR(tcom);
1302   USE_VAR(asynchronous);
1303
1304   subshell_level++;
1305   should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1306                           pipe_in == NO_PIPE &&
1307                           stdin_redirects (command->redirects) == 0);
1308
1309   invert = (command->flags & CMD_INVERT_RETURN) != 0;
1310   user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1311   user_coproc = command->type == cm_coproc;
1312
1313   command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1314
1315   /* If a command is asynchronous in a subshell (like ( foo ) & or
1316      the special case of an asynchronous GROUP command where the
1317      the subshell bit is turned on down in case cm_group: below),
1318      turn off `asynchronous', so that two subshells aren't spawned.
1319      XXX - asynchronous used to be set to 0 in this block, but that
1320      means that setup_async_signals was never run.  Now it's set to
1321      0 after subshell_environment is set appropriately and setup_async_signals
1322      is run.
1323
1324      This seems semantically correct to me.  For example,
1325      ( foo ) & seems to say ``do the command `foo' in a subshell
1326      environment, but don't wait for that subshell to finish'',
1327      and "{ foo ; bar ; } &" seems to me to be like functions or
1328      builtins in the background, which executed in a subshell
1329      environment.  I just don't see the need to fork two subshells. */
1330
1331   /* Don't fork again, we are already in a subshell.  A `doubly
1332      async' shell is not interactive, however. */
1333   if (asynchronous)
1334     {
1335 #if defined (JOB_CONTROL)
1336       /* If a construct like ( exec xxx yyy ) & is given while job
1337          control is active, we want to prevent exec from putting the
1338          subshell back into the original process group, carefully
1339          undoing all the work we just did in make_child. */
1340       original_pgrp = -1;
1341 #endif /* JOB_CONTROL */
1342       ois = interactive_shell;
1343       interactive_shell = 0;
1344       /* This test is to prevent alias expansion by interactive shells that
1345          run `(command) &' but to allow scripts that have enabled alias
1346          expansion with `shopt -s expand_alias' to continue to expand
1347          aliases. */
1348       if (ois != interactive_shell)
1349         expand_aliases = 0;
1350     }
1351
1352   /* Subshells are neither login nor interactive. */
1353   login_shell = interactive = 0;
1354
1355   if (user_subshell)
1356     subshell_environment = SUBSHELL_PAREN;
1357   else
1358     {
1359       subshell_environment = 0;                 /* XXX */
1360       if (asynchronous)
1361         subshell_environment |= SUBSHELL_ASYNC;
1362       if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1363         subshell_environment |= SUBSHELL_PIPE;
1364       if (user_coproc)
1365         subshell_environment |= SUBSHELL_COPROC;
1366     }
1367
1368   reset_terminating_signals ();         /* in sig.c */
1369   /* Cancel traps, in trap.c. */
1370   restore_original_signals ();
1371
1372   /* Make sure restore_original_signals doesn't undo the work done by
1373      make_child to ensure that asynchronous children are immune to SIGINT
1374      and SIGQUIT.  Turn off asynchronous to make sure more subshells are
1375      not spawned. */
1376   if (asynchronous)
1377     {
1378       setup_async_signals ();
1379       asynchronous = 0;
1380     }
1381
1382 #if defined (JOB_CONTROL)
1383   set_sigchld_handler ();
1384 #endif /* JOB_CONTROL */
1385
1386   set_sigint_handler ();
1387
1388 #if defined (JOB_CONTROL)
1389   /* Delete all traces that there were any jobs running.  This is
1390      only for subshells. */
1391   without_job_control ();
1392 #endif /* JOB_CONTROL */
1393
1394   if (fds_to_close)
1395     close_fd_bitmap (fds_to_close);
1396
1397   do_piping (pipe_in, pipe_out);
1398
1399 #if defined (COPROCESS_SUPPORT)
1400   coproc_closeall ();
1401 #endif
1402
1403   /* If this is a user subshell, set a flag if stdin was redirected.
1404      This is used later to decide whether to redirect fd 0 to
1405      /dev/null for async commands in the subshell.  This adds more
1406      sh compatibility, but I'm not sure it's the right thing to do. */
1407   if (user_subshell)
1408     {
1409       stdin_redir = stdin_redirects (command->redirects);
1410       restore_default_signal (0);
1411     }
1412
1413   /* If this is an asynchronous command (command &), we want to
1414      redirect the standard input from /dev/null in the absence of
1415      any specific redirection involving stdin. */
1416   if (should_redir_stdin && stdin_redir == 0)
1417     async_redirect_stdin ();
1418
1419   /* Do redirections, then dispose of them before recursive call. */
1420   if (command->redirects)
1421     {
1422       if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1423         exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1424
1425       dispose_redirects (command->redirects);
1426       command->redirects = (REDIRECT *)NULL;
1427     }
1428
1429   if (command->type == cm_subshell)
1430     tcom = command->value.Subshell->command;
1431   else if (user_coproc)
1432     tcom = command->value.Coproc->command;
1433   else
1434     tcom = command;
1435
1436   if (command->flags & CMD_TIME_PIPELINE)
1437     tcom->flags |= CMD_TIME_PIPELINE;
1438   if (command->flags & CMD_TIME_POSIX)
1439     tcom->flags |= CMD_TIME_POSIX;
1440   
1441   /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1442   if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1443     tcom->flags |= CMD_IGNORE_RETURN;
1444
1445   /* If this is a simple command, tell execute_disk_command that it
1446      might be able to get away without forking and simply exec.
1447      This means things like ( sleep 10 ) will only cause one fork.
1448      If we're timing the command or inverting its return value, however,
1449      we cannot do this optimization. */
1450   if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1451       ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1452       ((tcom->flags & CMD_INVERT_RETURN) == 0))
1453     {
1454       tcom->flags |= CMD_NO_FORK;
1455       if (tcom->type == cm_simple)
1456         tcom->value.Simple->flags |= CMD_NO_FORK;
1457     }
1458
1459   invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1460   tcom->flags &= ~CMD_INVERT_RETURN;
1461
1462   result = setjmp (top_level);
1463
1464   /* If we're inside a function while executing this subshell, we
1465      need to handle a possible `return'. */
1466   function_value = 0;
1467   if (return_catch_flag)
1468     function_value = setjmp (return_catch);
1469
1470   /* If we're going to exit the shell, we don't want to invert the return
1471      status. */
1472   if (result == EXITPROG)
1473     invert = 0, return_code = last_command_exit_value;
1474   else if (result)
1475     return_code = EXECUTION_FAILURE;
1476   else if (function_value)
1477     return_code = return_catch_value;
1478   else
1479     return_code = execute_command_internal (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1480
1481   /* If we are asked to, invert the return value. */
1482   if (invert)
1483     return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1484                                                      : EXECUTION_SUCCESS;
1485
1486   /* If we were explicitly placed in a subshell with (), we need
1487      to do the `shell cleanup' things, such as running traps[0]. */
1488   if (user_subshell && signal_is_trapped (0))
1489     {
1490       last_command_exit_value = return_code;
1491       return_code = run_exit_trap ();
1492     }
1493
1494   subshell_level--;
1495   return (return_code);
1496   /* NOTREACHED */
1497 }
1498
1499 #if defined (COPROCESS_SUPPORT)
1500 #define COPROC_MAX      16
1501
1502 typedef struct cpelement
1503   {
1504     struct cpelement *next;
1505     struct coproc *coproc;
1506   }
1507 cpelement_t;
1508     
1509 typedef struct cplist
1510   {
1511     struct cpelement *head;
1512     struct cpelement *tail;
1513     int ncoproc;
1514   }
1515 cplist_t;
1516
1517 static struct cpelement *cpe_alloc __P((struct coproc *));
1518 static void cpe_dispose __P((struct cpelement *));
1519 static struct cpelement *cpl_add __P((struct coproc *));
1520 static struct cpelement *cpl_delete __P((pid_t));
1521 static void cpl_reap __P((void));
1522 static void cpl_flush __P((void));
1523 static struct cpelement *cpl_search __P((pid_t));
1524 static struct cpelement *cpl_searchbyname __P((char *));
1525 static void cpl_prune __P((void));
1526
1527 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0 };
1528
1529 cplist_t coproc_list = {0, 0, 0};
1530
1531 /* Functions to manage the list of coprocs */
1532
1533 static struct cpelement *
1534 cpe_alloc (cp)
1535      Coproc *cp;
1536 {
1537   struct cpelement *cpe;
1538
1539   cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1540   cpe->coproc = cp;
1541   cpe->next = (struct cpelement *)0;
1542   return cpe;
1543 }
1544
1545 static void
1546 cpe_dispose (cpe)
1547       struct cpelement *cpe;
1548 {
1549   free (cpe);
1550 }
1551
1552 static struct cpelement *
1553 cpl_add (cp)
1554      Coproc *cp;
1555 {
1556   struct cpelement *cpe;
1557
1558   cpe = cpe_alloc (cp);
1559
1560   if (coproc_list.head == 0)
1561     {
1562       coproc_list.head = coproc_list.tail = cpe;
1563       coproc_list.ncoproc = 0;                  /* just to make sure */
1564     }
1565   else
1566     {
1567       coproc_list.tail->next = cpe;
1568       coproc_list.tail = cpe;
1569     }
1570   coproc_list.ncoproc++;
1571
1572   return cpe;
1573 }
1574
1575 static struct cpelement *
1576 cpl_delete (pid)
1577      pid_t pid;
1578 {
1579   struct cpelement *prev, *p;
1580
1581   for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1582     if (p->coproc->c_pid == pid)
1583       {
1584         prev->next = p->next;   /* remove from list */
1585         break;
1586       }
1587
1588   if (p == 0)
1589     return 0;           /* not found */
1590
1591 #if defined (DEBUG)
1592   itrace("cpl_delete: deleting %d", pid);
1593 #endif
1594
1595   /* Housekeeping in the border cases. */
1596   if (p == coproc_list.head)
1597     coproc_list.head = coproc_list.head->next;
1598   else if (p == coproc_list.tail)
1599     coproc_list.tail = prev;
1600
1601   coproc_list.ncoproc--;
1602   if (coproc_list.ncoproc == 0)
1603     coproc_list.head = coproc_list.tail = 0;
1604   else if (coproc_list.ncoproc == 1)
1605     coproc_list.tail = coproc_list.head;                /* just to make sure */
1606
1607   return (p);
1608 }
1609
1610 static void
1611 cpl_reap ()
1612 {
1613   struct cpelement *prev, *p;
1614
1615   for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1616     if (p->coproc->c_flags & COPROC_DEAD)
1617       {
1618         prev->next = p->next;   /* remove from list */
1619
1620         /* Housekeeping in the border cases. */
1621         if (p == coproc_list.head)
1622           coproc_list.head = coproc_list.head->next;
1623         else if (p == coproc_list.tail)
1624           coproc_list.tail = prev;
1625
1626         coproc_list.ncoproc--;
1627         if (coproc_list.ncoproc == 0)
1628           coproc_list.head = coproc_list.tail = 0;
1629         else if (coproc_list.ncoproc == 1)
1630           coproc_list.tail = coproc_list.head;          /* just to make sure */
1631
1632 #if defined (DEBUG)
1633         itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1634 #endif
1635
1636         coproc_dispose (p->coproc);
1637         cpe_dispose (p);
1638       }
1639 }
1640
1641 /* Clear out the list of saved statuses */
1642 static void
1643 cpl_flush ()
1644 {
1645   struct cpelement *cpe, *p;
1646
1647   for (cpe = coproc_list.head; cpe; )
1648     {
1649       p = cpe;
1650       cpe = cpe->next;
1651
1652       coproc_dispose (p->coproc);
1653       cpe_dispose (p);
1654     }
1655
1656   coproc_list.head = coproc_list.tail = 0;
1657   coproc_list.ncoproc = 0;
1658 }
1659
1660 /* Search for PID in the list of coprocs; return the cpelement struct if
1661    found.  If not found, return NULL. */
1662 static struct cpelement *
1663 cpl_search (pid)
1664      pid_t pid;
1665 {
1666   struct cpelement *cp;
1667
1668   for (cp = coproc_list.head ; cp; cp = cp->next)
1669     if (cp->coproc->c_pid == pid)
1670       return cp;
1671   return (struct cpelement *)NULL;
1672 }
1673
1674 /* Search for the coproc named NAME in the list of coprocs; return the
1675    cpelement struct if found.  If not found, return NULL. */
1676 static struct cpelement *
1677 cpl_searchbyname (name)
1678      char *name;
1679 {
1680   struct cpelement *cp;
1681
1682   for (cp = coproc_list.head ; cp; cp = cp->next)
1683     if (STREQ (cp->coproc->c_name, name))
1684       return cp;
1685   return (struct cpelement *)NULL;
1686 }
1687
1688 #if 0
1689 static void
1690 cpl_prune ()
1691 {
1692   struct cpelement *cp;
1693
1694   while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1695     {
1696       cp = coproc_list.head;
1697       coproc_list.head = coproc_list.head->next;
1698       coproc_dispose (cp->coproc);
1699       cpe_dispose (cp);
1700       coproc_list.ncoproc--;
1701     }
1702 }
1703 #endif
1704
1705 /* These currently use a single global "shell coproc" but are written in a
1706    way to not preclude additional coprocs later (using the list management
1707    package above). */
1708
1709 struct coproc *
1710 getcoprocbypid (pid)
1711      pid_t pid;
1712 {
1713   return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1714 }
1715
1716 struct coproc *
1717 getcoprocbyname (name)
1718      const char *name;
1719 {
1720   return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1721 }
1722
1723 void
1724 coproc_init (cp)
1725      struct coproc *cp;
1726 {
1727   cp->c_name = 0;
1728   cp->c_pid = NO_PID;
1729   cp->c_rfd = cp->c_wfd = -1;
1730   cp->c_rsave = cp->c_wsave = -1;
1731   cp->c_flags = cp->c_status = 0;  
1732 }
1733
1734 struct coproc *
1735 coproc_alloc (name, pid)
1736      char *name;
1737      pid_t pid;
1738 {
1739   struct coproc *cp;
1740
1741   cp = &sh_coproc;              /* XXX */
1742   coproc_init (cp);
1743
1744   cp->c_name = savestring (name);
1745   cp->c_pid = pid;
1746
1747   return (cp);
1748 }
1749
1750 void
1751 coproc_dispose (cp)
1752      struct coproc *cp;
1753 {
1754   if (cp == 0)
1755     return;
1756
1757   coproc_unsetvars (cp);
1758   FREE (cp->c_name);
1759   coproc_close (cp);
1760   coproc_init (cp);
1761 }
1762
1763 /* Placeholder for now. */
1764 void
1765 coproc_flush ()
1766 {
1767   coproc_dispose (&sh_coproc);
1768 }
1769
1770 void
1771 coproc_close (cp)
1772      struct coproc *cp;
1773 {
1774   if (cp->c_rfd >= 0)
1775     {
1776       close (cp->c_rfd);
1777       cp->c_rfd = -1;
1778     }
1779   if (cp->c_wfd >= 0)
1780     {
1781       close (cp->c_wfd);
1782       cp->c_wfd = -1;
1783     }
1784   cp->c_rsave = cp->c_wsave = -1;
1785 }
1786
1787 void
1788 coproc_closeall ()
1789 {
1790   coproc_close (&sh_coproc);
1791 }
1792
1793 void
1794 coproc_reap ()
1795 {
1796   struct coproc *cp;
1797
1798   cp = &sh_coproc;
1799   if (cp && (cp->c_flags & COPROC_DEAD))
1800     coproc_dispose (cp);
1801 }
1802
1803 void
1804 coproc_rclose (cp, fd)
1805      struct coproc *cp;
1806      int fd;
1807 {
1808   if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1809     {
1810       close (cp->c_rfd);
1811       cp->c_rfd = -1;
1812     }
1813 }
1814
1815 void
1816 coproc_wclose (cp, fd)
1817      struct coproc *cp;
1818      int fd;
1819 {
1820   if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1821     {
1822       close (cp->c_wfd);
1823       cp->c_wfd = -1;
1824     }
1825 }
1826
1827 void
1828 coproc_checkfd (cp, fd)
1829      struct coproc *cp;
1830      int fd;
1831 {
1832   int update;
1833
1834   update = 0;
1835   if (cp->c_rfd >= 0 && cp->c_rfd == fd)
1836     update = cp->c_rfd = -1;
1837   if (cp->c_wfd >= 0 && cp->c_wfd == fd)
1838     update = cp->c_wfd = -1;
1839   if (update)
1840     coproc_setvars (cp);
1841 }
1842
1843 void
1844 coproc_fdchk (fd)
1845      int fd;
1846 {
1847   coproc_checkfd (&sh_coproc, fd);
1848 }
1849
1850 void
1851 coproc_fdclose (cp, fd)
1852      struct coproc *cp;
1853      int fd;
1854 {
1855   coproc_rclose (cp, fd);
1856   coproc_wclose (cp, fd);
1857   coproc_setvars (cp);
1858 }
1859
1860 void
1861 coproc_fdsave (cp)
1862      struct coproc *cp;
1863 {
1864   cp->c_rsave = cp->c_rfd;
1865   cp->c_wsave = cp->c_wfd;
1866 }
1867
1868 void
1869 coproc_fdrestore (cp)
1870      struct coproc *cp;
1871 {
1872   cp->c_rfd = cp->c_rsave;
1873   cp->c_wfd = cp->c_wsave;
1874 }
1875
1876 void
1877 coproc_pidchk (pid, status)
1878      pid_t pid;
1879 {
1880   struct coproc *cp;
1881
1882   cp = getcoprocbypid (pid);
1883 #if 0
1884   if (cp)
1885     itrace("coproc_pidchk: pid %d has died", pid);
1886 #endif
1887   if (cp)
1888     {
1889       cp->c_status = status;
1890       cp->c_flags |= COPROC_DEAD;
1891       cp->c_flags &= ~COPROC_RUNNING;
1892 #if 0
1893       coproc_dispose (cp);
1894 #endif
1895     }
1896 }
1897
1898 void
1899 coproc_setvars (cp)
1900      struct coproc *cp;
1901 {
1902   SHELL_VAR *v;
1903   char *namevar, *t;
1904   int l;
1905 #if defined (ARRAY_VARS)
1906   arrayind_t ind;
1907 #endif
1908
1909   if (cp->c_name == 0)
1910     return;
1911
1912   l = strlen (cp->c_name);
1913   namevar = xmalloc (l + 16);
1914
1915 #if defined (ARRAY_VARS)
1916   v = find_variable (cp->c_name);
1917   if (v == 0)
1918     v = make_new_array_variable (cp->c_name);
1919   if (array_p (v) == 0)
1920     v = convert_var_to_array (v);
1921
1922   t = itos (cp->c_rfd);
1923   ind = 0;
1924   v = bind_array_variable (cp->c_name, ind, t, 0);
1925   free (t);
1926
1927   t = itos (cp->c_wfd);
1928   ind = 1;
1929   bind_array_variable (cp->c_name, ind, t, 0);
1930   free (t);
1931 #else
1932   sprintf (namevar, "%s_READ", cp->c_name);
1933   t = itos (cp->c_rfd);
1934   bind_variable (namevar, t, 0);
1935   free (t);
1936   sprintf (namevar, "%s_WRITE", cp->c_name);
1937   t = itos (cp->c_wfd);
1938   bind_variable (namevar, t, 0);
1939   free (t);
1940 #endif
1941
1942   sprintf (namevar, "%s_PID", cp->c_name);
1943   t = itos (cp->c_pid);
1944   bind_variable (namevar, t, 0);
1945   free (t);
1946
1947   free (namevar);
1948 }
1949
1950 void
1951 coproc_unsetvars (cp)
1952      struct coproc *cp;
1953 {
1954   int l;
1955   char *namevar;
1956
1957   if (cp->c_name == 0)
1958     return;
1959
1960   l = strlen (cp->c_name);
1961   namevar = xmalloc (l + 16);
1962
1963   sprintf (namevar, "%s_PID", cp->c_name);
1964   unbind_variable (namevar);  
1965
1966 #if defined (ARRAY_VARS)
1967   unbind_variable (cp->c_name);
1968 #else
1969   sprintf (namevar, "%s_READ", cp->c_name);
1970   unbind_variable (namevar);
1971   sprintf (namevar, "%s_WRITE", cp->c_name);
1972   unbind_variable (namevar);
1973 #endif  
1974
1975   free (namevar);
1976 }
1977
1978 static int
1979 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
1980      COMMAND *command;
1981      int pipe_in, pipe_out;
1982      struct fd_bitmap *fds_to_close;
1983 {
1984   int rpipe[2], wpipe[2], estat;
1985   pid_t coproc_pid;
1986   Coproc *cp;
1987   char *tcmd;
1988
1989   /* XXX -- will require changes to handle multiple coprocs */
1990   if (sh_coproc.c_pid != NO_PID)
1991     {
1992 #if 0
1993       internal_error ("execute_coproc: coproc [%d:%s] already exists", sh_coproc.c_pid, sh_coproc.c_name);
1994       return (last_command_exit_value = EXECUTION_FAILURE);
1995 #else
1996       internal_warning ("execute_coproc: coproc [%d:%s] still exists", sh_coproc.c_pid, sh_coproc.c_name);
1997 #endif
1998     }
1999   coproc_init (&sh_coproc);
2000
2001   command_string_index = 0;
2002   tcmd = make_command_string (command);
2003
2004   sh_openpipe ((int *)&rpipe);  /* 0 = parent read, 1 = child write */
2005   sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2006
2007   coproc_pid = make_child (savestring (tcmd), 1);
2008   if (coproc_pid == 0)
2009     {
2010       close (rpipe[0]);
2011       close (wpipe[1]);
2012
2013       estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2014
2015       fflush (stdout);
2016       fflush (stderr);
2017
2018       exit (estat);
2019     }
2020
2021   close (rpipe[1]);
2022   close (wpipe[0]);
2023
2024   cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2025   cp->c_rfd = rpipe[0];
2026   cp->c_wfd = wpipe[1];
2027
2028   SET_CLOSE_ON_EXEC (cp->c_rfd);
2029   SET_CLOSE_ON_EXEC (cp->c_wfd);
2030
2031   coproc_setvars (cp);
2032
2033 #if 0
2034   itrace ("execute_coproc: [%d] %s", coproc_pid, the_printed_command);
2035 #endif
2036
2037   close_pipes (pipe_in, pipe_out);
2038 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2039   unlink_fifo_list ();
2040 #endif
2041   stop_pipeline (1, (COMMAND *)NULL);
2042   DESCRIBE_PID (coproc_pid);
2043   run_pending_traps ();
2044
2045   return (EXECUTION_SUCCESS);
2046 }
2047 #endif
2048
2049 static int
2050 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2051      COMMAND *command;
2052      int asynchronous, pipe_in, pipe_out;
2053      struct fd_bitmap *fds_to_close;
2054 {
2055   int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2056   COMMAND *cmd;
2057   struct fd_bitmap *fd_bitmap;
2058
2059 #if defined (JOB_CONTROL)
2060   sigset_t set, oset;
2061   BLOCK_CHILD (set, oset);
2062 #endif /* JOB_CONTROL */
2063
2064   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2065
2066   prev = pipe_in;
2067   cmd = command;
2068
2069   while (cmd && cmd->type == cm_connection &&
2070          cmd->value.Connection && cmd->value.Connection->connector == '|')
2071     {
2072       /* Make a pipeline between the two commands. */
2073       if (pipe (fildes) < 0)
2074         {
2075           sys_error (_("pipe error"));
2076 #if defined (JOB_CONTROL)
2077           terminate_current_pipeline ();
2078           kill_current_pipeline ();
2079           UNBLOCK_CHILD (oset);
2080 #endif /* JOB_CONTROL */
2081           last_command_exit_value = EXECUTION_FAILURE;
2082           /* The unwind-protects installed below will take care
2083              of closing all of the open file descriptors. */
2084           throw_to_top_level ();
2085           return (EXECUTION_FAILURE);   /* XXX */
2086         }
2087
2088       /* Here is a problem: with the new file close-on-exec
2089          code, the read end of the pipe (fildes[0]) stays open
2090          in the first process, so that process will never get a
2091          SIGPIPE.  There is no way to signal the first process
2092          that it should close fildes[0] after forking, so it
2093          remains open.  No SIGPIPE is ever sent because there
2094          is still a file descriptor open for reading connected
2095          to the pipe.  We take care of that here.  This passes
2096          around a bitmap of file descriptors that must be
2097          closed after making a child process in execute_simple_command. */
2098
2099       /* We need fd_bitmap to be at least as big as fildes[0].
2100          If fildes[0] is less than fds_to_close->size, then
2101          use fds_to_close->size. */
2102       new_bitmap_size = (fildes[0] < fds_to_close->size)
2103                                 ? fds_to_close->size
2104                                 : fildes[0] + 8;
2105
2106       fd_bitmap = new_fd_bitmap (new_bitmap_size);
2107
2108       /* Now copy the old information into the new bitmap. */
2109       xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2110
2111       /* And mark the pipe file descriptors to be closed. */
2112       fd_bitmap->bitmap[fildes[0]] = 1;
2113
2114       /* In case there are pipe or out-of-processes errors, we
2115          want all these file descriptors to be closed when
2116          unwind-protects are run, and the storage used for the
2117          bitmaps freed up. */
2118       begin_unwind_frame ("pipe-file-descriptors");
2119       add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2120       add_unwind_protect (close_fd_bitmap, fd_bitmap);
2121       if (prev >= 0)
2122         add_unwind_protect (close, prev);
2123       dummyfd = fildes[1];
2124       add_unwind_protect (close, dummyfd);
2125
2126 #if defined (JOB_CONTROL)
2127       add_unwind_protect (restore_signal_mask, &oset);
2128 #endif /* JOB_CONTROL */
2129
2130       if (ignore_return && cmd->value.Connection->first)
2131         cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2132       execute_command_internal (cmd->value.Connection->first, asynchronous,
2133                                 prev, fildes[1], fd_bitmap);
2134
2135       if (prev >= 0)
2136         close (prev);
2137
2138       prev = fildes[0];
2139       close (fildes[1]);
2140
2141       dispose_fd_bitmap (fd_bitmap);
2142       discard_unwind_frame ("pipe-file-descriptors");
2143
2144       cmd = cmd->value.Connection->second;
2145     }
2146
2147   /* Now execute the rightmost command in the pipeline.  */
2148   if (ignore_return && cmd)
2149     cmd->flags |= CMD_IGNORE_RETURN;
2150   exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2151
2152   if (prev >= 0)
2153     close (prev);
2154
2155 #if defined (JOB_CONTROL)
2156   UNBLOCK_CHILD (oset);
2157 #endif
2158
2159   QUIT;
2160   return (exec_result);
2161 }
2162
2163 static int
2164 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2165      COMMAND *command;
2166      int asynchronous, pipe_in, pipe_out;
2167      struct fd_bitmap *fds_to_close;
2168 {
2169   REDIRECT *rp;
2170   COMMAND *tc, *second;
2171   int ignore_return, exec_result, was_error_trap, invert;
2172   volatile int save_line_number;
2173
2174   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2175
2176   switch (command->value.Connection->connector)
2177     {
2178     /* Do the first command asynchronously. */
2179     case '&':
2180       tc = command->value.Connection->first;
2181       if (tc == 0)
2182         return (EXECUTION_SUCCESS);
2183
2184       rp = tc->redirects;
2185
2186       if (ignore_return)
2187         tc->flags |= CMD_IGNORE_RETURN;
2188       tc->flags |= CMD_AMPERSAND;
2189
2190       /* If this shell was compiled without job control support,
2191          if we are currently in a subshell via `( xxx )', or if job
2192          control is not active then the standard input for an
2193          asynchronous command is forced to /dev/null. */
2194 #if defined (JOB_CONTROL)
2195       if ((subshell_environment || !job_control) && !stdin_redir)
2196 #else
2197       if (!stdin_redir)
2198 #endif /* JOB_CONTROL */
2199         tc->flags |= CMD_STDIN_REDIR;
2200
2201       exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2202       QUIT;
2203
2204       if (tc->flags & CMD_STDIN_REDIR)
2205         tc->flags &= ~CMD_STDIN_REDIR;
2206
2207       second = command->value.Connection->second;
2208       if (second)
2209         {
2210           if (ignore_return)
2211             second->flags |= CMD_IGNORE_RETURN;
2212
2213           exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2214         }
2215
2216       break;
2217
2218     /* Just call execute command on both sides. */
2219     case ';':
2220       if (ignore_return)
2221         {
2222           if (command->value.Connection->first)
2223             command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2224           if (command->value.Connection->second)
2225             command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2226         }
2227       executing_list++;
2228       QUIT;
2229       execute_command (command->value.Connection->first);
2230       QUIT;
2231       exec_result = execute_command_internal (command->value.Connection->second,
2232                                       asynchronous, pipe_in, pipe_out,
2233                                       fds_to_close);
2234       executing_list--;
2235       break;
2236
2237     case '|':
2238       was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2239       invert = (command->flags & CMD_INVERT_RETURN) != 0;
2240       ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2241
2242       line_number_for_err_trap = line_number;
2243       exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2244
2245       if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2246         {
2247           last_command_exit_value = exec_result;
2248           save_line_number = line_number;
2249           line_number = line_number_for_err_trap;
2250           run_error_trap ();
2251           line_number = save_line_number;
2252         }
2253
2254       if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2255         {
2256           last_command_exit_value = exec_result;
2257           run_pending_traps ();
2258           jump_to_top_level (ERREXIT);
2259         }
2260
2261       break;
2262
2263     case AND_AND:
2264     case OR_OR:
2265       if (asynchronous)
2266         {
2267           /* If we have something like `a && b &' or `a || b &', run the
2268              && or || stuff in a subshell.  Force a subshell and just call
2269              execute_command_internal again.  Leave asynchronous on
2270              so that we get a report from the parent shell about the
2271              background job. */
2272           command->flags |= CMD_FORCE_SUBSHELL;
2273           exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2274           break;
2275         }
2276
2277       /* Execute the first command.  If the result of that is successful
2278          and the connector is AND_AND, or the result is not successful
2279          and the connector is OR_OR, then execute the second command,
2280          otherwise return. */
2281
2282       executing_list++;
2283       if (command->value.Connection->first)
2284         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2285
2286       exec_result = execute_command (command->value.Connection->first);
2287       QUIT;
2288       if (((command->value.Connection->connector == AND_AND) &&
2289            (exec_result == EXECUTION_SUCCESS)) ||
2290           ((command->value.Connection->connector == OR_OR) &&
2291            (exec_result != EXECUTION_SUCCESS)))
2292         {
2293           if (ignore_return && command->value.Connection->second)
2294             command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2295
2296           exec_result = execute_command (command->value.Connection->second);
2297         }
2298       executing_list--;
2299       break;
2300
2301     default:
2302       command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2303       jump_to_top_level (DISCARD);
2304       exec_result = EXECUTION_FAILURE;
2305     }
2306
2307   return exec_result;
2308 }
2309
2310 #define REAP() \
2311   do \
2312     { \
2313       if (!interactive_shell) \
2314         reap_dead_jobs (); \
2315     } \
2316   while (0)
2317
2318 /* Execute a FOR command.  The syntax is: FOR word_desc IN word_list;
2319    DO command; DONE */
2320 static int
2321 execute_for_command (for_command)
2322      FOR_COM *for_command;
2323 {
2324   register WORD_LIST *releaser, *list;
2325   SHELL_VAR *v;
2326   char *identifier;
2327   int retval, save_line_number;
2328 #if 0
2329   SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2330 #endif
2331
2332   save_line_number = line_number;
2333   if (check_identifier (for_command->name, 1) == 0)
2334     {
2335       if (posixly_correct && interactive_shell == 0)
2336         {
2337           last_command_exit_value = EX_BADUSAGE;
2338           jump_to_top_level (ERREXIT);
2339         }
2340       return (EXECUTION_FAILURE);
2341     }
2342
2343   loop_level++;
2344   identifier = for_command->name->word;
2345
2346   list = releaser = expand_words_no_vars (for_command->map_list);
2347
2348   begin_unwind_frame ("for");
2349   add_unwind_protect (dispose_words, releaser);
2350
2351 #if 0
2352   if (lexical_scoping)
2353     {
2354       old_value = copy_variable (find_variable (identifier));
2355       if (old_value)
2356         add_unwind_protect (dispose_variable, old_value);
2357     }
2358 #endif
2359
2360   if (for_command->flags & CMD_IGNORE_RETURN)
2361     for_command->action->flags |= CMD_IGNORE_RETURN;
2362
2363   for (retval = EXECUTION_SUCCESS; list; list = list->next)
2364     {
2365       QUIT;
2366
2367       line_number = for_command->line;
2368
2369       /* Remember what this command looks like, for debugger. */
2370       command_string_index = 0;
2371       print_for_command_head (for_command);
2372
2373       if (echo_command_at_execute)
2374         xtrace_print_for_command_head (for_command);
2375
2376       /* Save this command unless it's a trap command and we're not running
2377          a debug trap. */
2378 #if 0
2379       if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2380 #else
2381       if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2382 #endif
2383         {
2384           FREE (the_printed_command_except_trap);
2385           the_printed_command_except_trap = savestring (the_printed_command);
2386         }
2387
2388       retval = run_debug_trap ();
2389 #if defined (DEBUGGER)
2390       /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2391          skip the command. */
2392       if (debugging_mode && retval != EXECUTION_SUCCESS)
2393         continue;
2394 #endif
2395
2396       this_command_name = (char *)NULL;
2397       v = bind_variable (identifier, list->word->word, 0);
2398       if (readonly_p (v) || noassign_p (v))
2399         {
2400           line_number = save_line_number;
2401           if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2402             {
2403               last_command_exit_value = EXECUTION_FAILURE;
2404               jump_to_top_level (FORCE_EOF);
2405             }
2406           else
2407             {
2408               dispose_words (releaser);
2409               discard_unwind_frame ("for");
2410               loop_level--;
2411               return (EXECUTION_FAILURE);
2412             }
2413         }
2414       retval = execute_command (for_command->action);
2415       REAP ();
2416       QUIT;
2417
2418       if (breaking)
2419         {
2420           breaking--;
2421           break;
2422         }
2423
2424       if (continuing)
2425         {
2426           continuing--;
2427           if (continuing)
2428             break;
2429         }
2430     }
2431
2432   loop_level--;
2433   line_number = save_line_number;
2434
2435 #if 0
2436   if (lexical_scoping)
2437     {
2438       if (!old_value)
2439         unbind_variable (identifier);
2440       else
2441         {
2442           SHELL_VAR *new_value;
2443
2444           new_value = bind_variable (identifier, value_cell(old_value), 0);
2445           new_value->attributes = old_value->attributes;
2446           dispose_variable (old_value);
2447         }
2448     }
2449 #endif
2450
2451   dispose_words (releaser);
2452   discard_unwind_frame ("for");
2453   return (retval);
2454 }
2455
2456 #if defined (ARITH_FOR_COMMAND)
2457 /* Execute an arithmetic for command.  The syntax is
2458
2459         for (( init ; step ; test ))
2460         do
2461                 body
2462         done
2463
2464    The execution should be exactly equivalent to
2465
2466         eval \(\( init \)\)
2467         while eval \(\( test \)\) ; do
2468                 body;
2469                 eval \(\( step \)\)
2470         done
2471 */
2472 static intmax_t
2473 eval_arith_for_expr (l, okp)
2474      WORD_LIST *l;
2475      int *okp;
2476 {
2477   WORD_LIST *new;
2478   intmax_t expresult;
2479   int r;
2480
2481   new = expand_words_no_vars (l);
2482   if (new)
2483     {
2484       if (echo_command_at_execute)
2485         xtrace_print_arith_cmd (new);
2486       this_command_name = "((";         /* )) for expression error messages */
2487
2488       command_string_index = 0;
2489       print_arith_command (new);
2490       if (signal_in_progress (DEBUG_TRAP) == 0)
2491         {
2492           FREE (the_printed_command_except_trap);
2493           the_printed_command_except_trap = savestring (the_printed_command);
2494         }
2495
2496       r = run_debug_trap ();
2497       /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2498          skip the command. */
2499 #if defined (DEBUGGER)
2500       if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
2501         expresult = evalexp (new->word->word, okp);
2502       else
2503         {
2504           expresult = 0;
2505           if (okp)
2506             *okp = 1;
2507         }
2508 #else
2509       expresult = evalexp (new->word->word, okp);
2510 #endif
2511       dispose_words (new);
2512     }
2513   else
2514     {
2515       expresult = 0;
2516       if (okp)
2517         *okp = 1;
2518     }
2519   return (expresult);
2520 }
2521
2522 static int
2523 execute_arith_for_command (arith_for_command)
2524      ARITH_FOR_COM *arith_for_command;
2525 {
2526   intmax_t expresult;
2527   int expok, body_status, arith_lineno, save_lineno;
2528
2529   body_status = EXECUTION_SUCCESS;
2530   loop_level++;
2531   save_lineno = line_number;
2532
2533   if (arith_for_command->flags & CMD_IGNORE_RETURN)
2534     arith_for_command->action->flags |= CMD_IGNORE_RETURN;
2535
2536   this_command_name = "((";     /* )) for expression error messages */
2537
2538   /* save the starting line number of the command so we can reset
2539      line_number before executing each expression -- for $LINENO
2540      and the DEBUG trap. */
2541   line_number = arith_lineno = arith_for_command->line;
2542   if (variable_context && interactive_shell)
2543     line_number -= function_line_number;
2544
2545   /* Evaluate the initialization expression. */
2546   expresult = eval_arith_for_expr (arith_for_command->init, &expok);
2547   if (expok == 0)
2548     {
2549       line_number = save_lineno;
2550       return (EXECUTION_FAILURE);
2551     }
2552
2553   while (1)
2554     {
2555       /* Evaluate the test expression. */
2556       line_number = arith_lineno;
2557       expresult = eval_arith_for_expr (arith_for_command->test, &expok);
2558       line_number = save_lineno;
2559
2560       if (expok == 0)
2561         {
2562           body_status = EXECUTION_FAILURE;
2563           break;
2564         }
2565       REAP ();
2566       if (expresult == 0)
2567         break;
2568
2569       /* Execute the body of the arithmetic for command. */
2570       QUIT;
2571       body_status = execute_command (arith_for_command->action);
2572       QUIT;
2573
2574       /* Handle any `break' or `continue' commands executed by the body. */
2575       if (breaking)
2576         {
2577           breaking--;
2578           break;
2579         }
2580
2581       if (continuing)
2582         {
2583           continuing--;
2584           if (continuing)
2585             break;
2586         }
2587
2588       /* Evaluate the step expression. */
2589       line_number = arith_lineno;
2590       expresult = eval_arith_for_expr (arith_for_command->step, &expok);
2591       line_number = save_lineno;
2592
2593       if (expok == 0)
2594         {
2595           body_status = EXECUTION_FAILURE;
2596           break;
2597         }
2598     }
2599
2600   loop_level--;
2601   line_number = save_lineno;
2602
2603   return (body_status);
2604 }
2605 #endif
2606
2607 #if defined (SELECT_COMMAND)
2608 static int LINES, COLS, tabsize;
2609
2610 #define RP_SPACE ") "
2611 #define RP_SPACE_LEN 2
2612
2613 /* XXX - does not handle numbers > 1000000 at all. */
2614 #define NUMBER_LEN(s) \
2615 ((s < 10) ? 1 \
2616           : ((s < 100) ? 2 \
2617                       : ((s < 1000) ? 3 \
2618                                    : ((s < 10000) ? 4 \
2619                                                  : ((s < 100000) ? 5 \
2620                                                                 : 6)))))
2621
2622 static int
2623 print_index_and_element (len, ind, list)
2624       int len, ind;
2625       WORD_LIST *list;
2626 {
2627   register WORD_LIST *l;
2628   register int i;
2629
2630   if (list == 0)
2631     return (0);
2632   for (i = ind, l = list; l && --i; l = l->next)
2633     ;
2634   fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
2635   return (STRLEN (l->word->word));
2636 }
2637
2638 static void
2639 indent (from, to)
2640      int from, to;
2641 {
2642   while (from < to)
2643     {
2644       if ((to / tabsize) > (from / tabsize))
2645         {
2646           putc ('\t', stderr);
2647           from += tabsize - from % tabsize;
2648         }
2649       else
2650         {
2651           putc (' ', stderr);
2652           from++;
2653         }
2654     }
2655 }
2656
2657 static void
2658 print_select_list (list, list_len, max_elem_len, indices_len)
2659      WORD_LIST *list;
2660      int list_len, max_elem_len, indices_len;
2661 {
2662   int ind, row, elem_len, pos, cols, rows;
2663   int first_column_indices_len, other_indices_len;
2664
2665   if (list == 0)
2666     {
2667       putc ('\n', stderr);
2668       return;
2669     }
2670
2671   cols = max_elem_len ? COLS / max_elem_len : 1;
2672   if (cols == 0)
2673     cols = 1;
2674   rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
2675   cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
2676
2677   if (rows == 1)
2678     {
2679       rows = cols;
2680       cols = 1;
2681     }
2682
2683   first_column_indices_len = NUMBER_LEN (rows);
2684   other_indices_len = indices_len;
2685
2686   for (row = 0; row < rows; row++)
2687     {
2688       ind = row;
2689       pos = 0;
2690       while (1)
2691         {
2692           indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
2693           elem_len = print_index_and_element (indices_len, ind + 1, list);
2694           elem_len += indices_len + RP_SPACE_LEN;
2695           ind += rows;
2696           if (ind >= list_len)
2697             break;
2698           indent (pos + elem_len, pos + max_elem_len);
2699           pos += max_elem_len;
2700         }
2701       putc ('\n', stderr);
2702     }
2703 }
2704
2705 /* Print the elements of LIST, one per line, preceded by an index from 1 to
2706    LIST_LEN.  Then display PROMPT and wait for the user to enter a number.
2707    If the number is between 1 and LIST_LEN, return that selection.  If EOF
2708    is read, return a null string.  If a blank line is entered, or an invalid
2709    number is entered, the loop is executed again. */
2710 static char *
2711 select_query (list, list_len, prompt, print_menu)
2712      WORD_LIST *list;
2713      int list_len;
2714      char *prompt;
2715      int print_menu;
2716 {
2717   int max_elem_len, indices_len, len;
2718   intmax_t reply;
2719   WORD_LIST *l;
2720   char *repl_string, *t;
2721
2722   t = get_string_value ("LINES");
2723   LINES = (t && *t) ? atoi (t) : 24;
2724   t = get_string_value ("COLUMNS");
2725   COLS =  (t && *t) ? atoi (t) : 80;
2726
2727 #if 0
2728   t = get_string_value ("TABSIZE");
2729   tabsize = (t && *t) ? atoi (t) : 8;
2730   if (tabsize <= 0)
2731     tabsize = 8;
2732 #else
2733   tabsize = 8;
2734 #endif
2735
2736   max_elem_len = 0;
2737   for (l = list; l; l = l->next)
2738     {
2739       len = STRLEN (l->word->word);
2740       if (len > max_elem_len)
2741         max_elem_len = len;
2742     }
2743   indices_len = NUMBER_LEN (list_len);
2744   max_elem_len += indices_len + RP_SPACE_LEN + 2;
2745
2746   while (1)
2747     {
2748       if (print_menu)
2749         print_select_list (list, list_len, max_elem_len, indices_len);
2750       fprintf (stderr, "%s", prompt);
2751       fflush (stderr);
2752       QUIT;
2753
2754       if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
2755         {
2756           putchar ('\n');
2757           return ((char *)NULL);
2758         }
2759       repl_string = get_string_value ("REPLY");
2760       if (*repl_string == 0)
2761         {
2762           print_menu = 1;
2763           continue;
2764         }
2765       if (legal_number (repl_string, &reply) == 0)
2766         return "";
2767       if (reply < 1 || reply > list_len)
2768         return "";
2769
2770       for (l = list; l && --reply; l = l->next)
2771         ;
2772       return (l->word->word);
2773     }
2774 }
2775
2776 /* Execute a SELECT command.  The syntax is:
2777    SELECT word IN list DO command_list DONE
2778    Only `break' or `return' in command_list will terminate
2779    the command. */
2780 static int
2781 execute_select_command (select_command)
2782      SELECT_COM *select_command;
2783 {
2784   WORD_LIST *releaser, *list;
2785   SHELL_VAR *v;
2786   char *identifier, *ps3_prompt, *selection;
2787   int retval, list_len, show_menu, save_line_number;
2788
2789   if (check_identifier (select_command->name, 1) == 0)
2790     return (EXECUTION_FAILURE);
2791
2792   save_line_number = line_number;
2793   line_number = select_command->line;
2794
2795   command_string_index = 0;
2796   print_select_command_head (select_command);
2797
2798   if (echo_command_at_execute)
2799     xtrace_print_select_command_head (select_command);
2800
2801 #if 0
2802   if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2803 #else
2804   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2805 #endif
2806     {
2807       FREE (the_printed_command_except_trap);
2808       the_printed_command_except_trap = savestring (the_printed_command);
2809     }
2810
2811   retval = run_debug_trap ();
2812 #if defined (DEBUGGER)
2813   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2814      skip the command. */
2815   if (debugging_mode && retval != EXECUTION_SUCCESS)
2816     return (EXECUTION_SUCCESS);
2817 #endif
2818
2819   loop_level++;
2820   identifier = select_command->name->word;
2821
2822   /* command and arithmetic substitution, parameter and variable expansion,
2823      word splitting, pathname expansion, and quote removal. */
2824   list = releaser = expand_words_no_vars (select_command->map_list);
2825   list_len = list_length (list);
2826   if (list == 0 || list_len == 0)
2827     {
2828       if (list)
2829         dispose_words (list);
2830       line_number = save_line_number;
2831       return (EXECUTION_SUCCESS);
2832     }
2833
2834   begin_unwind_frame ("select");
2835   add_unwind_protect (dispose_words, releaser);
2836
2837   if (select_command->flags & CMD_IGNORE_RETURN)
2838     select_command->action->flags |= CMD_IGNORE_RETURN;
2839
2840   retval = EXECUTION_SUCCESS;
2841   show_menu = 1;
2842
2843   while (1)
2844     {
2845       line_number = select_command->line;
2846       ps3_prompt = get_string_value ("PS3");
2847       if (ps3_prompt == 0)
2848         ps3_prompt = "#? ";
2849
2850       QUIT;
2851       selection = select_query (list, list_len, ps3_prompt, show_menu);
2852       QUIT;
2853       if (selection == 0)
2854         {
2855           /* select_query returns EXECUTION_FAILURE if the read builtin
2856              fails, so we want to return failure in this case. */
2857           retval = EXECUTION_FAILURE;
2858           break;
2859         }
2860
2861       v = bind_variable (identifier, selection, 0);
2862       if (readonly_p (v) || noassign_p (v))
2863         {
2864           if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2865             {
2866               last_command_exit_value = EXECUTION_FAILURE;
2867               jump_to_top_level (FORCE_EOF);
2868             }
2869           else
2870             {
2871               dispose_words (releaser);
2872               discard_unwind_frame ("select");
2873               loop_level--;
2874               line_number = save_line_number;
2875               return (EXECUTION_FAILURE);
2876             }
2877         }
2878
2879       retval = execute_command (select_command->action);
2880
2881       REAP ();
2882       QUIT;
2883
2884       if (breaking)
2885         {
2886           breaking--;
2887           break;
2888         }
2889
2890       if (continuing)
2891         {
2892           continuing--;
2893           if (continuing)
2894             break;
2895         }
2896
2897 #if defined (KSH_COMPATIBLE_SELECT)
2898       show_menu = 0;
2899       selection = get_string_value ("REPLY");
2900       if (selection && *selection == '\0')
2901         show_menu = 1;
2902 #endif
2903     }
2904
2905   loop_level--;
2906   line_number = save_line_number;
2907
2908   dispose_words (releaser);
2909   discard_unwind_frame ("select");
2910   return (retval);
2911 }
2912 #endif /* SELECT_COMMAND */
2913
2914 /* Execute a CASE command.  The syntax is: CASE word_desc IN pattern_list ESAC.
2915    The pattern_list is a linked list of pattern clauses; each clause contains
2916    some patterns to compare word_desc against, and an associated command to
2917    execute. */
2918 static int
2919 execute_case_command (case_command)
2920      CASE_COM *case_command;
2921 {
2922   register WORD_LIST *list;
2923   WORD_LIST *wlist, *es;
2924   PATTERN_LIST *clauses;
2925   char *word, *pattern;
2926   int retval, match, ignore_return, save_line_number;
2927
2928   save_line_number = line_number;
2929   line_number = case_command->line;
2930
2931   command_string_index = 0;
2932   print_case_command_head (case_command);
2933
2934   if (echo_command_at_execute)
2935     xtrace_print_case_command_head (case_command);
2936
2937 #if 0
2938   if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
2939 #else
2940   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2941 #endif
2942     {
2943       FREE (the_printed_command_except_trap);
2944       the_printed_command_except_trap = savestring (the_printed_command);
2945     }
2946
2947   retval = run_debug_trap();
2948 #if defined (DEBUGGER)
2949   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2950      skip the command. */
2951   if (debugging_mode && retval != EXECUTION_SUCCESS)
2952     {
2953       line_number = save_line_number;
2954       return (EXECUTION_SUCCESS);
2955     }
2956 #endif
2957
2958   wlist = expand_word_unsplit (case_command->word, 0);
2959   word = wlist ? string_list (wlist) : savestring ("");
2960   dispose_words (wlist);
2961
2962   retval = EXECUTION_SUCCESS;
2963   ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2964
2965   begin_unwind_frame ("case");
2966   add_unwind_protect ((Function *)xfree, word);
2967
2968 #define EXIT_CASE()  goto exit_case_command
2969
2970   for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2971     {
2972       QUIT;
2973       for (list = clauses->patterns; list; list = list->next)
2974         {
2975           es = expand_word_leave_quoted (list->word, 0);
2976
2977           if (es && es->word && es->word->word && *(es->word->word))
2978             pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2979           else
2980             {
2981               pattern = (char *)xmalloc (1);
2982               pattern[0] = '\0';
2983             }
2984
2985           /* Since the pattern does not undergo quote removal (as per
2986              Posix.2, section 3.9.4.3), the strmatch () call must be able
2987              to recognize backslashes as escape characters. */
2988           match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
2989           free (pattern);
2990
2991           dispose_words (es);
2992
2993           if (match)
2994             {
2995               do
2996                 {
2997                   if (clauses->action && ignore_return)
2998                     clauses->action->flags |= CMD_IGNORE_RETURN;
2999                   retval = execute_command (clauses->action);
3000                 }
3001               while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3002               if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3003                 EXIT_CASE ();
3004               else
3005                 break;
3006             }
3007
3008           QUIT;
3009         }
3010     }
3011
3012 exit_case_command:
3013   free (word);
3014   discard_unwind_frame ("case");
3015   line_number = save_line_number;
3016   return (retval);
3017 }
3018
3019 #define CMD_WHILE 0
3020 #define CMD_UNTIL 1
3021
3022 /* The WHILE command.  Syntax: WHILE test DO action; DONE.
3023    Repeatedly execute action while executing test produces
3024    EXECUTION_SUCCESS. */
3025 static int
3026 execute_while_command (while_command)
3027      WHILE_COM *while_command;
3028 {
3029   return (execute_while_or_until (while_command, CMD_WHILE));
3030 }
3031
3032 /* UNTIL is just like WHILE except that the test result is negated. */
3033 static int
3034 execute_until_command (while_command)
3035      WHILE_COM *while_command;
3036 {
3037   return (execute_while_or_until (while_command, CMD_UNTIL));
3038 }
3039
3040 /* The body for both while and until.  The only difference between the
3041    two is that the test value is treated differently.  TYPE is
3042    CMD_WHILE or CMD_UNTIL.  The return value for both commands should
3043    be EXECUTION_SUCCESS if no commands in the body are executed, and
3044    the status of the last command executed in the body otherwise. */
3045 static int
3046 execute_while_or_until (while_command, type)
3047      WHILE_COM *while_command;
3048      int type;
3049 {
3050   int return_value, body_status;
3051
3052   body_status = EXECUTION_SUCCESS;
3053   loop_level++;
3054
3055   while_command->test->flags |= CMD_IGNORE_RETURN;
3056   if (while_command->flags & CMD_IGNORE_RETURN)
3057     while_command->action->flags |= CMD_IGNORE_RETURN;
3058
3059   while (1)
3060     {
3061       return_value = execute_command (while_command->test);
3062       REAP ();
3063
3064       /* Need to handle `break' in the test when we would break out of the
3065          loop.  The job control code will set `breaking' to loop_level
3066          when a job in a loop is stopped with SIGTSTP.  If the stopped job
3067          is in the loop test, `breaking' will not be reset unless we do
3068          this, and the shell will cease to execute commands. */
3069       if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3070         {
3071           if (breaking)
3072             breaking--;
3073           break;
3074         }
3075       if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3076         {
3077           if (breaking)
3078             breaking--;
3079           break;
3080         }
3081
3082       QUIT;
3083       body_status = execute_command (while_command->action);
3084       QUIT;
3085
3086       if (breaking)
3087         {
3088           breaking--;
3089           break;
3090         }
3091
3092       if (continuing)
3093         {
3094           continuing--;
3095           if (continuing)
3096             break;
3097         }
3098     }
3099   loop_level--;
3100
3101   return (body_status);
3102 }
3103
3104 /* IF test THEN command [ELSE command].
3105    IF also allows ELIF in the place of ELSE IF, but
3106    the parser makes *that* stupidity transparent. */
3107 static int
3108 execute_if_command (if_command)
3109      IF_COM *if_command;
3110 {
3111   int return_value, save_line_number;
3112
3113   save_line_number = line_number;
3114   if_command->test->flags |= CMD_IGNORE_RETURN;
3115   return_value = execute_command (if_command->test);
3116   line_number = save_line_number;
3117
3118   if (return_value == EXECUTION_SUCCESS)
3119     {
3120       QUIT;
3121
3122       if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3123         if_command->true_case->flags |= CMD_IGNORE_RETURN;
3124
3125       return (execute_command (if_command->true_case));
3126     }
3127   else
3128     {
3129       QUIT;
3130
3131       if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3132         if_command->false_case->flags |= CMD_IGNORE_RETURN;
3133
3134       return (execute_command (if_command->false_case));
3135     }
3136 }
3137
3138 #if defined (DPAREN_ARITHMETIC)
3139 static int
3140 execute_arith_command (arith_command)
3141      ARITH_COM *arith_command;
3142 {
3143   int expok, save_line_number, retval;
3144   intmax_t expresult;
3145   WORD_LIST *new;
3146   char *exp;
3147
3148   expresult = 0;
3149
3150   save_line_number = line_number;
3151   this_command_name = "((";     /* )) */
3152   line_number = arith_command->line;
3153   /* If we're in a function, update the line number information. */
3154   if (variable_context && interactive_shell)
3155     line_number -= function_line_number;
3156
3157   command_string_index = 0;
3158   print_arith_command (arith_command->exp);
3159
3160   if (signal_in_progress (DEBUG_TRAP) == 0)
3161     {
3162       FREE (the_printed_command_except_trap);
3163       the_printed_command_except_trap = savestring (the_printed_command);
3164     }
3165
3166   /* Run the debug trap before each arithmetic command, but do it after we
3167      update the line number information and before we expand the various
3168      words in the expression. */
3169   retval = run_debug_trap ();
3170 #if defined (DEBUGGER)
3171   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3172      skip the command. */
3173   if (debugging_mode && retval != EXECUTION_SUCCESS)
3174     {
3175       line_number = save_line_number;
3176       return (EXECUTION_SUCCESS);
3177     }
3178 #endif
3179
3180   new = expand_words_no_vars (arith_command->exp);
3181
3182   /* If we're tracing, make a new word list with `((' at the front and `))'
3183      at the back and print it. */
3184   if (echo_command_at_execute)
3185     xtrace_print_arith_cmd (new);
3186
3187   if (new)
3188     {
3189       exp = new->next ? string_list (new) : new->word->word;
3190       expresult = evalexp (exp, &expok);
3191       line_number = save_line_number;
3192       if (exp != new->word->word)
3193         free (exp);
3194       dispose_words (new);
3195     }
3196   else
3197     {
3198       expresult = 0;
3199       expok = 1;
3200     }
3201
3202   if (expok == 0)
3203     return (EXECUTION_FAILURE);
3204
3205   return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3206 }
3207 #endif /* DPAREN_ARITHMETIC */
3208
3209 #if defined (COND_COMMAND)
3210
3211 static char * const nullstr = "";
3212
3213 static int
3214 execute_cond_node (cond)
3215      COND_COM *cond;
3216 {
3217   int result, invert, patmatch, rmatch, mflags, ignore;
3218   char *arg1, *arg2;
3219
3220   invert = (cond->flags & CMD_INVERT_RETURN);
3221   ignore = (cond->flags & CMD_IGNORE_RETURN);
3222   if (ignore)
3223     {
3224       if (cond->left)
3225         cond->left->flags |= CMD_IGNORE_RETURN;
3226       if (cond->right)
3227         cond->right->flags |= CMD_IGNORE_RETURN;
3228     }
3229       
3230   if (cond->type == COND_EXPR)
3231     result = execute_cond_node (cond->left);
3232   else if (cond->type == COND_OR)
3233     {
3234       result = execute_cond_node (cond->left);
3235       if (result != EXECUTION_SUCCESS)
3236         result = execute_cond_node (cond->right);
3237     }
3238   else if (cond->type == COND_AND)
3239     {
3240       result = execute_cond_node (cond->left);
3241       if (result == EXECUTION_SUCCESS)
3242         result = execute_cond_node (cond->right);
3243     }
3244   else if (cond->type == COND_UNARY)
3245     {
3246       if (ignore)
3247         comsub_ignore_return++;
3248       arg1 = cond_expand_word (cond->left->op, 0);
3249       if (ignore)
3250         comsub_ignore_return--;
3251       if (arg1 == 0)
3252         arg1 = nullstr;
3253       if (echo_command_at_execute)
3254         xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3255       result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3256       if (arg1 != nullstr)
3257         free (arg1);
3258     }
3259   else if (cond->type == COND_BINARY)
3260     {
3261       rmatch = 0;
3262       patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3263                   (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
3264                   (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3265 #if defined (COND_REGEXP)
3266       rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3267                 cond->op->word[2] == '\0');
3268 #endif
3269
3270       if (ignore)
3271         comsub_ignore_return++;
3272       arg1 = cond_expand_word (cond->left->op, 0);
3273       if (ignore)
3274         comsub_ignore_return--;
3275       if (arg1 == 0)
3276         arg1 = nullstr;
3277       if (ignore)
3278         comsub_ignore_return++;
3279       arg2 = cond_expand_word (cond->right->op,
3280                                (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3281       if (ignore)
3282         comsub_ignore_return--;
3283       if (arg2 == 0)
3284         arg2 = nullstr;
3285
3286       if (echo_command_at_execute)
3287         xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3288
3289 #if defined (COND_REGEXP)
3290       if (rmatch)
3291         {
3292           mflags = SHMAT_PWARN;
3293 #if defined (ARRAY_VARS)
3294           mflags |= SHMAT_SUBEXP;
3295 #endif
3296
3297           result = sh_regmatch (arg1, arg2, mflags);
3298         }
3299       else
3300 #endif /* COND_REGEXP */
3301         {
3302           int oe;
3303           oe = extended_glob;
3304           extended_glob = 1;
3305           result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3306                                   ? EXECUTION_SUCCESS
3307                                   : EXECUTION_FAILURE;
3308           extended_glob = oe;
3309         }
3310       if (arg1 != nullstr)
3311         free (arg1);
3312       if (arg2 != nullstr)
3313         free (arg2);
3314     }
3315   else
3316     {
3317       command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3318       jump_to_top_level (DISCARD);
3319       result = EXECUTION_FAILURE;
3320     }
3321
3322   if (invert)
3323     result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3324
3325   return result;
3326 }
3327
3328 static int
3329 execute_cond_command (cond_command)
3330      COND_COM *cond_command;
3331 {
3332   int retval, save_line_number;
3333
3334   retval = EXECUTION_SUCCESS;
3335   save_line_number = line_number;
3336
3337   this_command_name = "[[";
3338   line_number = cond_command->line;
3339   /* If we're in a function, update the line number information. */
3340   if (variable_context && interactive_shell)
3341     line_number -= function_line_number;
3342   command_string_index = 0;
3343   print_cond_command (cond_command);
3344
3345   if (signal_in_progress (DEBUG_TRAP) == 0)
3346     {
3347       FREE (the_printed_command_except_trap);
3348       the_printed_command_except_trap = savestring (the_printed_command);
3349     }
3350
3351   /* Run the debug trap before each conditional command, but do it after we
3352      update the line number information. */
3353   retval = run_debug_trap ();
3354 #if defined (DEBUGGER)
3355   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3356      skip the command. */
3357   if (debugging_mode && retval != EXECUTION_SUCCESS)
3358     {
3359       line_number = save_line_number;
3360       return (EXECUTION_SUCCESS);
3361     }
3362 #endif
3363
3364 #if 0
3365   debug_print_cond_command (cond_command);
3366 #endif
3367
3368   last_command_exit_value = retval = execute_cond_node (cond_command);
3369   line_number = save_line_number;
3370   return (retval);
3371 }
3372 #endif /* COND_COMMAND */
3373
3374 static void
3375 bind_lastarg (arg)
3376      char *arg;
3377 {
3378   SHELL_VAR *var;
3379
3380   if (arg == 0)
3381     arg = "";
3382   var = bind_variable ("_", arg, 0);
3383   VUNSETATTR (var, att_exported);
3384 }
3385
3386 /* Execute a null command.  Fork a subshell if the command uses pipes or is
3387    to be run asynchronously.  This handles all the side effects that are
3388    supposed to take place. */
3389 static int
3390 execute_null_command (redirects, pipe_in, pipe_out, async)
3391      REDIRECT *redirects;
3392      int pipe_in, pipe_out, async;
3393 {
3394   int r;
3395   int forcefork;
3396   REDIRECT *rd;
3397
3398   for (forcefork = 0, rd = redirects; rd; rd = rd->next)
3399     forcefork += rd->rflags & REDIR_VARASSIGN;
3400
3401   if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
3402     {
3403       /* We have a null command, but we really want a subshell to take
3404          care of it.  Just fork, do piping and redirections, and exit. */
3405       if (make_child ((char *)NULL, async) == 0)
3406         {
3407           /* Cancel traps, in trap.c. */
3408           restore_original_signals ();          /* XXX */
3409
3410           do_piping (pipe_in, pipe_out);
3411
3412 #if defined (COPROCESS_SUPPORT)
3413           coproc_closeall ();
3414 #endif
3415
3416           subshell_environment = 0;
3417           if (async)
3418             subshell_environment |= SUBSHELL_ASYNC;
3419           if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3420             subshell_environment |= SUBSHELL_PIPE;
3421
3422           if (do_redirections (redirects, RX_ACTIVE) == 0)
3423             exit (EXECUTION_SUCCESS);
3424           else
3425             exit (EXECUTION_FAILURE);
3426         }
3427       else
3428         {
3429           close_pipes (pipe_in, pipe_out);
3430 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3431           unlink_fifo_list ();
3432 #endif
3433           return (EXECUTION_SUCCESS);
3434         }
3435     }
3436   else
3437     {
3438       /* Even if there aren't any command names, pretend to do the
3439          redirections that are specified.  The user expects the side
3440          effects to take place.  If the redirections fail, then return
3441          failure.  Otherwise, if a command substitution took place while
3442          expanding the command or a redirection, return the value of that
3443          substitution.  Otherwise, return EXECUTION_SUCCESS. */
3444
3445       r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
3446       cleanup_redirects (redirection_undo_list);
3447       redirection_undo_list = (REDIRECT *)NULL;
3448
3449       if (r != 0)
3450         return (EXECUTION_FAILURE);
3451       else if (last_command_subst_pid != NO_PID)
3452         return (last_command_exit_value);
3453       else
3454         return (EXECUTION_SUCCESS);
3455     }
3456 }
3457
3458 /* This is a hack to suppress word splitting for assignment statements
3459    given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
3460 static void
3461 fix_assignment_words (words)
3462      WORD_LIST *words;
3463 {
3464   WORD_LIST *w;
3465   struct builtin *b;
3466   int assoc;
3467
3468   if (words == 0)
3469     return;
3470
3471   b = 0;
3472   assoc = 0;
3473
3474   for (w = words; w; w = w->next)
3475     if (w->word->flags & W_ASSIGNMENT)
3476       {
3477         if (b == 0)
3478           {
3479             b = builtin_address_internal (words->word->word, 0);
3480             if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3481               return;
3482             else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3483               words->word->flags |= W_ASSNBLTIN;
3484           }
3485         w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
3486 #if defined (ARRAY_VARS)
3487         if (assoc)
3488           w->word->flags |= W_ASSIGNASSOC;
3489 #endif
3490       }
3491 #if defined (ARRAY_VARS)
3492     /* Note that we saw an associative array option to a builtin that takes
3493        assignment statements.  This is a bit of a kludge. */
3494     else if (w->word->word[0] == '-' && strchr (w->word->word, 'A'))
3495       {
3496         if (b == 0)
3497           {
3498             b = builtin_address_internal (words->word->word, 0);
3499             if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
3500               return;
3501             else if (b && (b->flags & ASSIGNMENT_BUILTIN))
3502               words->word->flags |= W_ASSNBLTIN;
3503           }
3504         if (words->word->flags & W_ASSNBLTIN)
3505           assoc = 1;
3506       }
3507 #endif
3508 }
3509
3510 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
3511    to PATHNAME, is a directory.  Used by the autocd code below. */
3512 static int
3513 is_dirname (pathname)
3514      char *pathname;
3515 {
3516   char *temp;
3517   temp = search_for_command (pathname);
3518   return (temp ? file_isdir (temp) : file_isdir (pathname));
3519 }
3520
3521 /* The meaty part of all the executions.  We have to start hacking the
3522    real execution of commands here.  Fork a process, set things up,
3523    execute the command. */
3524 static int
3525 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
3526      SIMPLE_COM *simple_command;
3527      int pipe_in, pipe_out, async;
3528      struct fd_bitmap *fds_to_close;
3529 {
3530   WORD_LIST *words, *lastword;
3531   char *command_line, *lastarg, *temp;
3532   int first_word_quoted, result, builtin_is_special, already_forked, dofork;
3533   pid_t old_last_async_pid;
3534   sh_builtin_func_t *builtin;
3535   SHELL_VAR *func;
3536
3537   result = EXECUTION_SUCCESS;
3538   special_builtin_failed = builtin_is_special = 0;
3539   command_line = (char *)0;
3540
3541   /* If we're in a function, update the line number information. */
3542   if (variable_context && interactive_shell && sourcelevel == 0)
3543     line_number -= function_line_number;
3544
3545   /* Remember what this command line looks like at invocation. */
3546   command_string_index = 0;
3547   print_simple_command (simple_command);
3548
3549 #if 0
3550   if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3551 #else
3552   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3553 #endif
3554     {
3555       FREE (the_printed_command_except_trap);
3556       the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
3557     }
3558
3559   /* Run the debug trap before each simple command, but do it after we
3560      update the line number information. */
3561   result = run_debug_trap ();
3562 #if defined (DEBUGGER)
3563   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3564      skip the command. */
3565   if (debugging_mode && result != EXECUTION_SUCCESS)
3566     return (EXECUTION_SUCCESS);
3567 #endif
3568
3569   first_word_quoted =
3570     simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
3571
3572   last_command_subst_pid = NO_PID;
3573   old_last_async_pid = last_asynchronous_pid;
3574
3575   already_forked = dofork = 0;
3576
3577   /* If we're in a pipeline or run in the background, set DOFORK so we
3578      make the child early, before word expansion.  This keeps assignment
3579      statements from affecting the parent shell's environment when they
3580      should not. */
3581   dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
3582
3583   /* Something like `%2 &' should restart job 2 in the background, not cause
3584      the shell to fork here. */
3585   if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
3586         simple_command->words && simple_command->words->word &&
3587         simple_command->words->word->word &&
3588         (simple_command->words->word->word[0] == '%'))
3589     dofork = 0;
3590
3591   if (dofork)
3592     {
3593       /* Do this now, because execute_disk_command will do it anyway in the
3594          vast majority of cases. */
3595       maybe_make_export_env ();
3596
3597       /* Don't let a DEBUG trap overwrite the command string to be saved with
3598          the process/job associated with this child. */
3599       if (make_child (savestring (the_printed_command_except_trap), async) == 0)
3600         {
3601           already_forked = 1;
3602           simple_command->flags |= CMD_NO_FORK;
3603
3604           subshell_environment = SUBSHELL_FORK;
3605           if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
3606             subshell_environment |= SUBSHELL_PIPE;
3607           if (async)
3608             subshell_environment |= SUBSHELL_ASYNC;
3609
3610           /* We need to do this before piping to handle some really
3611              pathological cases where one of the pipe file descriptors
3612              is < 2. */
3613           if (fds_to_close)
3614             close_fd_bitmap (fds_to_close);
3615
3616           do_piping (pipe_in, pipe_out);
3617           pipe_in = pipe_out = NO_PIPE;
3618 #if defined (COPROCESS_SUPPORT)
3619           coproc_closeall ();
3620 #endif
3621
3622           last_asynchronous_pid = old_last_async_pid;
3623         }
3624       else
3625         {
3626           close_pipes (pipe_in, pipe_out);
3627 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3628           unlink_fifo_list ();
3629 #endif
3630           command_line = (char *)NULL;      /* don't free this. */
3631           bind_lastarg ((char *)NULL);
3632           return (result);
3633         }
3634     }
3635
3636   /* If we are re-running this as the result of executing the `command'
3637      builtin, do not expand the command words a second time. */
3638   if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
3639     {
3640       current_fds_to_close = fds_to_close;
3641       fix_assignment_words (simple_command->words);
3642       /* Pass the ignore return flag down to command substitutions */
3643       if (simple_command->flags & CMD_IGNORE_RETURN)    /* XXX */
3644         comsub_ignore_return++;
3645       words = expand_words (simple_command->words);
3646       if (simple_command->flags & CMD_IGNORE_RETURN)
3647         comsub_ignore_return--;
3648       current_fds_to_close = (struct fd_bitmap *)NULL;
3649     }
3650   else
3651     words = copy_word_list (simple_command->words);
3652
3653   /* It is possible for WORDS not to have anything left in it.
3654      Perhaps all the words consisted of `$foo', and there was
3655      no variable `$foo'. */
3656   if (words == 0)
3657     {
3658       this_command_name = 0;
3659       result = execute_null_command (simple_command->redirects,
3660                                      pipe_in, pipe_out,
3661                                      already_forked ? 0 : async);
3662       if (already_forked)
3663         exit (result);
3664       else
3665         {
3666           bind_lastarg ((char *)NULL);
3667           set_pipestatus_from_exit (result);
3668           return (result);
3669         }
3670     }
3671
3672   lastarg = (char *)NULL;
3673
3674   begin_unwind_frame ("simple-command");
3675
3676   if (echo_command_at_execute)
3677     xtrace_print_word_list (words, 1);
3678
3679   builtin = (sh_builtin_func_t *)NULL;
3680   func = (SHELL_VAR *)NULL;
3681   if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
3682     {
3683       /* Posix.2 says special builtins are found before functions.  We
3684          don't set builtin_is_special anywhere other than here, because
3685          this path is followed only when the `command' builtin is *not*
3686          being used, and we don't want to exit the shell if a special
3687          builtin executed with `command builtin' fails.  `command' is not
3688          a special builtin. */
3689       if (posixly_correct)
3690         {
3691           builtin = find_special_builtin (words->word->word);
3692           if (builtin)
3693             builtin_is_special = 1;
3694         }
3695       if (builtin == 0)
3696         func = find_function (words->word->word);
3697     }
3698
3699   /* In POSIX mode, assignment errors in the temporary environment cause a
3700      non-interactive shell to exit. */
3701   if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
3702     {
3703       last_command_exit_value = EXECUTION_FAILURE;
3704       jump_to_top_level (ERREXIT);
3705     }
3706
3707   add_unwind_protect (dispose_words, words);
3708   QUIT;
3709
3710   /* Bind the last word in this command to "$_" after execution. */
3711   for (lastword = words; lastword->next; lastword = lastword->next)
3712     ;
3713   lastarg = lastword->word->word;
3714
3715 #if defined (JOB_CONTROL)
3716   /* Is this command a job control related thing? */
3717   if (words->word->word[0] == '%' && already_forked == 0)
3718     {
3719       this_command_name = async ? "bg" : "fg";
3720       last_shell_builtin = this_shell_builtin;
3721       this_shell_builtin = builtin_address (this_command_name);
3722       result = (*this_shell_builtin) (words);
3723       goto return_result;
3724     }
3725
3726   /* One other possiblilty.  The user may want to resume an existing job.
3727      If they do, find out whether this word is a candidate for a running
3728      job. */
3729   if (job_control && already_forked == 0 && async == 0 &&
3730         !first_word_quoted &&
3731         !words->next &&
3732         words->word->word[0] &&
3733         !simple_command->redirects &&
3734         pipe_in == NO_PIPE &&
3735         pipe_out == NO_PIPE &&
3736         (temp = get_string_value ("auto_resume")))
3737     {
3738       int job, jflags, started_status;
3739
3740       jflags = JM_STOPPED|JM_FIRSTMATCH;
3741       if (STREQ (temp, "exact"))
3742         jflags |= JM_EXACT;
3743       else if (STREQ (temp, "substring"))
3744         jflags |= JM_SUBSTRING;
3745       else
3746         jflags |= JM_PREFIX;
3747       job = get_job_by_name (words->word->word, jflags);
3748       if (job != NO_JOB)
3749         {
3750           run_unwind_frame ("simple-command");
3751           this_command_name = "fg";
3752           last_shell_builtin = this_shell_builtin;
3753           this_shell_builtin = builtin_address ("fg");
3754
3755           started_status = start_job (job, 1);
3756           return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
3757         }
3758     }
3759 #endif /* JOB_CONTROL */
3760
3761 run_builtin:
3762   /* Remember the name of this command globally. */
3763   this_command_name = words->word->word;
3764
3765   QUIT;
3766
3767   /* This command could be a shell builtin or a user-defined function.
3768      We have already found special builtins by this time, so we do not
3769      set builtin_is_special.  If this is a function or builtin, and we
3770      have pipes, then fork a subshell in here.  Otherwise, just execute
3771      the command directly. */
3772   if (func == 0 && builtin == 0)
3773     builtin = find_shell_builtin (this_command_name);
3774
3775   last_shell_builtin = this_shell_builtin;
3776   this_shell_builtin = builtin;
3777
3778   if (builtin || func)
3779     {
3780       if (builtin)
3781         unwind_protect_int (executing_builtin); /* modified in execute_builtin */
3782       if (already_forked)
3783         {
3784           /* reset_terminating_signals (); */   /* XXX */
3785           /* Cancel traps, in trap.c. */
3786           restore_original_signals ();
3787
3788           if (async)
3789             {
3790               if ((simple_command->flags & CMD_STDIN_REDIR) &&
3791                     pipe_in == NO_PIPE &&
3792                     (stdin_redirects (simple_command->redirects) == 0))
3793                 async_redirect_stdin ();
3794               setup_async_signals ();
3795             }
3796
3797           subshell_level++;
3798           execute_subshell_builtin_or_function
3799             (words, simple_command->redirects, builtin, func,
3800              pipe_in, pipe_out, async, fds_to_close,
3801              simple_command->flags);
3802           subshell_level--;
3803         }
3804       else
3805         {
3806           result = execute_builtin_or_function
3807             (words, builtin, func, simple_command->redirects, fds_to_close,
3808              simple_command->flags);
3809           if (builtin)
3810             {
3811               if (result > EX_SHERRBASE)
3812                 {
3813                   result = builtin_status (result);
3814                   if (builtin_is_special)
3815                     special_builtin_failed = 1;
3816                 }
3817               /* In POSIX mode, if there are assignment statements preceding
3818                  a special builtin, they persist after the builtin
3819                  completes. */
3820               if (posixly_correct && builtin_is_special && temporary_env)
3821                 merge_temporary_env ();
3822             }
3823           else          /* function */
3824             {
3825               if (result == EX_USAGE)
3826                 result = EX_BADUSAGE;
3827               else if (result > EX_SHERRBASE)
3828                 result = EXECUTION_FAILURE;
3829             }
3830
3831           set_pipestatus_from_exit (result);
3832
3833           goto return_result;
3834         }
3835     }
3836
3837   if (autocd && interactive && words->word && is_dirname (words->word->word))
3838     {
3839       words = make_word_list (make_word ("cd"), words);
3840       xtrace_print_word_list (words, 0);
3841       goto run_builtin;
3842     }
3843
3844   if (command_line == 0)
3845     command_line = savestring (the_printed_command_except_trap);
3846
3847 #if defined (PROCESS_SUBSTITUTION)
3848   if ((subshell_environment & SUBSHELL_COMSUB) && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
3849     simple_command->flags &= ~CMD_NO_FORK;
3850 #endif
3851
3852   execute_disk_command (words, simple_command->redirects, command_line,
3853                         pipe_in, pipe_out, async, fds_to_close,
3854                         simple_command->flags);
3855
3856  return_result:
3857   bind_lastarg (lastarg);
3858   FREE (command_line);
3859   dispose_words (words);
3860   discard_unwind_frame ("simple-command");
3861   this_command_name = (char *)NULL;     /* points to freed memory now */
3862   return (result);
3863 }
3864
3865 /* Translate the special builtin exit statuses.  We don't really need a
3866    function for this; it's a placeholder for future work. */
3867 static int
3868 builtin_status (result)
3869      int result;
3870 {
3871   int r;
3872
3873   switch (result)
3874     {
3875     case EX_USAGE:
3876       r = EX_BADUSAGE;
3877       break;
3878     case EX_REDIRFAIL:
3879     case EX_BADSYNTAX:
3880     case EX_BADASSIGN:
3881     case EX_EXPFAIL:
3882       r = EXECUTION_FAILURE;
3883       break;
3884     default:
3885       r = EXECUTION_SUCCESS;
3886       break;
3887     }
3888   return (r);
3889 }
3890
3891 static int
3892 execute_builtin (builtin, words, flags, subshell)
3893      sh_builtin_func_t *builtin;
3894      WORD_LIST *words;
3895      int flags, subshell;
3896 {
3897   int old_e_flag, result, eval_unwind;
3898   int isbltinenv;
3899   char *error_trap;
3900
3901 #if 0
3902   /* XXX -- added 12/11 */
3903   terminate_immediately++;
3904 #endif
3905
3906   error_trap = 0;
3907   old_e_flag = exit_immediately_on_error;
3908   /* The eval builtin calls parse_and_execute, which does not know about
3909      the setting of flags, and always calls the execution functions with
3910      flags that will exit the shell on an error if -e is set.  If the
3911      eval builtin is being called, and we're supposed to ignore the exit
3912      value of the command, we turn the -e flag off ourselves and disable
3913      the ERR trap, then restore them when the command completes.  This is
3914      also a problem (as below) for the command and source/. builtins. */
3915   if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
3916         (builtin == eval_builtin || builtin == command_builtin || builtin == source_builtin))
3917     {
3918       begin_unwind_frame ("eval_builtin");
3919       unwind_protect_int (exit_immediately_on_error);
3920       error_trap = TRAP_STRING (ERROR_TRAP);
3921       if (error_trap)
3922         {
3923           error_trap = savestring (error_trap);
3924           add_unwind_protect (xfree, error_trap);
3925           add_unwind_protect (set_error_trap, error_trap);
3926           restore_default_signal (ERROR_TRAP);
3927         }
3928       exit_immediately_on_error = 0;
3929       eval_unwind = 1;
3930     }
3931   else
3932     eval_unwind = 0;
3933
3934   /* The temporary environment for a builtin is supposed to apply to
3935      all commands executed by that builtin.  Currently, this is a
3936      problem only with the `unset', `source' and `eval' builtins. */
3937
3938   isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin);
3939
3940   if (isbltinenv)
3941     {
3942       if (subshell == 0)
3943         begin_unwind_frame ("builtin_env");
3944
3945       if (temporary_env)
3946         {
3947           push_scope (VC_BLTNENV, temporary_env);
3948           if (subshell == 0)
3949             add_unwind_protect (pop_scope, (flags & CMD_COMMAND_BUILTIN) ? 0 : "1");
3950           temporary_env = (HASH_TABLE *)NULL;     
3951         }
3952     }
3953
3954   /* `return' does a longjmp() back to a saved environment in execute_function.
3955      If a variable assignment list preceded the command, and the shell is
3956      running in POSIX mode, we need to merge that into the shell_variables
3957      table, since `return' is a POSIX special builtin. */
3958   if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3959     {
3960       begin_unwind_frame ("return_temp_env");
3961       add_unwind_protect (merge_temporary_env, (char *)NULL);
3962     }
3963
3964   executing_builtin++;
3965   result = ((*builtin) (words->next));
3966
3967   /* This shouldn't happen, but in case `return' comes back instead of
3968      longjmp'ing, we need to unwind. */
3969   if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3970     discard_unwind_frame ("return_temp_env");
3971
3972   if (subshell == 0 && isbltinenv)
3973     run_unwind_frame ("builtin_env");
3974
3975   if (eval_unwind)
3976     {
3977       exit_immediately_on_error += old_e_flag;
3978       if (error_trap)
3979         {
3980           set_error_trap (error_trap);
3981           xfree (error_trap);
3982         }
3983       discard_unwind_frame ("eval_builtin");
3984     }
3985
3986 #if 0
3987   /* XXX -- added 12/11 */
3988   terminate_immediately--;
3989 #endif
3990
3991   return (result);
3992 }
3993
3994 static int
3995 execute_function (var, words, flags, fds_to_close, async, subshell)
3996      SHELL_VAR *var;
3997      WORD_LIST *words;
3998      int flags;
3999      struct fd_bitmap *fds_to_close;
4000      int async, subshell;
4001 {
4002   int return_val, result;
4003   COMMAND *tc, *fc, *save_current;
4004   char *debug_trap, *error_trap, *return_trap;
4005 #if defined (ARRAY_VARS)
4006   SHELL_VAR *funcname_v, *nfv, *bash_source_v, *bash_lineno_v;
4007   ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
4008 #endif
4009   FUNCTION_DEF *shell_fn;
4010   char *sfile, *t;
4011
4012   USE_VAR(fc);
4013
4014 #if 0   /* for bash-4.2 */
4015   if (funcnest_max > 0 && funcnest >= funcnest_max)
4016     {
4017       internal_error ("%s: maximum function nesting level exceeded (%d)", var->name, funcnest);
4018       jump_to_top_level (DISCARD);
4019     }
4020 #endif
4021
4022 #if defined (ARRAY_VARS)
4023   GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4024   GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4025   GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4026 #endif
4027
4028   tc = (COMMAND *)copy_command (function_cell (var));
4029   if (tc && (flags & CMD_IGNORE_RETURN))
4030     tc->flags |= CMD_IGNORE_RETURN;
4031
4032   if (subshell == 0)
4033     {
4034       begin_unwind_frame ("function_calling");
4035       push_context (var->name, subshell, temporary_env);
4036       add_unwind_protect (pop_context, (char *)NULL);
4037       unwind_protect_int (line_number);
4038       unwind_protect_int (return_catch_flag);
4039       unwind_protect_jmp_buf (return_catch);
4040       add_unwind_protect (dispose_command, (char *)tc);
4041       unwind_protect_pointer (this_shell_function);
4042       unwind_protect_int (loop_level);
4043       unwind_protect_int (funcnest);
4044     }
4045   else
4046     push_context (var->name, subshell, temporary_env);  /* don't unwind-protect for subshells */
4047
4048   temporary_env = (HASH_TABLE *)NULL;
4049
4050   this_shell_function = var;
4051   make_funcname_visible (1);
4052
4053   debug_trap = TRAP_STRING(DEBUG_TRAP);
4054   error_trap = TRAP_STRING(ERROR_TRAP);
4055   return_trap = TRAP_STRING(RETURN_TRAP);
4056   
4057   /* The order of the unwind protects for debug_trap, error_trap and
4058      return_trap is important here!  unwind-protect commands are run
4059      in reverse order of registration.  If this causes problems, take
4060      out the xfree unwind-protect calls and live with the small memory leak. */
4061
4062   /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4063      if the function has the trace attribute set, it inherits the DEBUG trap */
4064   if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4065     {
4066       if (subshell == 0)
4067         {
4068           debug_trap = savestring (debug_trap);
4069           add_unwind_protect (xfree, debug_trap);
4070           add_unwind_protect (set_debug_trap, debug_trap);
4071         }
4072       restore_default_signal (DEBUG_TRAP);
4073     }
4074
4075   /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4076   if (error_trap && error_trace_mode == 0)
4077     {
4078       if (subshell == 0)
4079         {
4080           error_trap = savestring (error_trap);
4081           add_unwind_protect (xfree, error_trap);
4082           add_unwind_protect (set_error_trap, error_trap);
4083         }
4084       restore_default_signal (ERROR_TRAP);
4085     }
4086
4087   /* Shell functions inherit the RETURN trap if function tracing is on
4088      globally or on individually for this function. */
4089 #if 0
4090   if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4091 #else
4092   if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
4093 #endif
4094     {
4095       if (subshell == 0)
4096         {
4097           return_trap = savestring (return_trap);
4098           add_unwind_protect (xfree, return_trap);
4099           add_unwind_protect (set_return_trap, return_trap);
4100         }
4101       restore_default_signal (RETURN_TRAP);
4102     }
4103   
4104   funcnest++;
4105 #if defined (ARRAY_VARS)
4106   /* This is quite similar to the code in shell.c and elsewhere. */
4107   shell_fn = find_function_def (this_shell_function->name);
4108   sfile = shell_fn ? shell_fn->source_file : "";
4109   array_push (funcname_a, this_shell_function->name);
4110
4111   array_push (bash_source_a, sfile);
4112   t = itos (executing_line_number ());
4113   array_push (bash_lineno_a, t);
4114   free (t);
4115 #endif
4116
4117   /* The temporary environment for a function is supposed to apply to
4118      all commands executed within the function body. */
4119
4120   remember_args (words->next, 1);
4121
4122   /* Update BASH_ARGV and BASH_ARGC */
4123   if (debugging_mode)
4124     push_args (words->next);
4125
4126   /* Number of the line on which the function body starts. */
4127   line_number = function_line_number = tc->line;
4128
4129 #if defined (JOB_CONTROL)
4130   if (subshell)
4131     stop_pipeline (async, (COMMAND *)NULL);
4132 #endif
4133
4134   fc = tc;
4135
4136   return_catch_flag++;
4137   return_val = setjmp (return_catch);
4138
4139   if (return_val)
4140     {
4141       result = return_catch_value;
4142       /* Run the RETURN trap in the function's context. */
4143       save_current = currently_executing_command;
4144       run_return_trap ();
4145       currently_executing_command = save_current;
4146     }
4147   else
4148     {
4149       /* Run the debug trap here so we can trap at the start of a function's
4150          execution rather than the execution of the body's first command. */
4151       showing_function_line = 1;
4152       save_current = currently_executing_command;
4153       result = run_debug_trap ();
4154 #if defined (DEBUGGER)
4155       /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4156          skip the command. */
4157       if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
4158         {
4159           showing_function_line = 0;
4160           currently_executing_command = save_current;
4161           result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4162
4163           /* Run the RETURN trap in the function's context */
4164           save_current = currently_executing_command;
4165           run_return_trap ();
4166           currently_executing_command = save_current;
4167         }
4168 #else
4169       result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4170
4171       save_current = currently_executing_command;
4172       run_return_trap ();
4173       currently_executing_command = save_current;
4174 #endif
4175       showing_function_line = 0;
4176     }
4177
4178   /* Restore BASH_ARGC and BASH_ARGV */
4179   if (debugging_mode)
4180     pop_args ();
4181
4182   if (subshell == 0)
4183     run_unwind_frame ("function_calling");
4184
4185 #if defined (ARRAY_VARS)
4186   /* These two variables cannot be unset, and cannot be affected by the
4187      function. */
4188   array_pop (bash_source_a);
4189   array_pop (bash_lineno_a);
4190
4191   /* FUNCNAME can be unset, and so can potentially be changed by the
4192      function. */
4193   GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4194   if (nfv == funcname_v)
4195     array_pop (funcname_a);
4196 #endif
4197   
4198   if (variable_context == 0 || this_shell_function == 0)
4199     {
4200       make_funcname_visible (0);
4201 #if defined (PROCESS_SUBSTITUTION)
4202       unlink_fifo_list ();
4203 #endif
4204     }
4205   
4206   return (result);
4207 }
4208
4209 /* A convenience routine for use by other parts of the shell to execute
4210    a particular shell function. */
4211 int
4212 execute_shell_function (var, words)
4213      SHELL_VAR *var;
4214      WORD_LIST *words;
4215 {
4216   int ret;
4217   struct fd_bitmap *bitmap;
4218
4219   bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
4220   begin_unwind_frame ("execute-shell-function");
4221   add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
4222       
4223   ret = execute_function (var, words, 0, bitmap, 0, 0);
4224
4225   dispose_fd_bitmap (bitmap);
4226   discard_unwind_frame ("execute-shell-function");
4227
4228   return ret;
4229 }
4230
4231 /* Execute a shell builtin or function in a subshell environment.  This
4232    routine does not return; it only calls exit().  If BUILTIN is non-null,
4233    it points to a function to call to execute a shell builtin; otherwise
4234    VAR points at the body of a function to execute.  WORDS is the arguments
4235    to the command, REDIRECTS specifies redirections to perform before the
4236    command is executed. */
4237 static void
4238 execute_subshell_builtin_or_function (words, redirects, builtin, var,
4239                                       pipe_in, pipe_out, async, fds_to_close,
4240                                       flags)
4241      WORD_LIST *words;
4242      REDIRECT *redirects;
4243      sh_builtin_func_t *builtin;
4244      SHELL_VAR *var;
4245      int pipe_in, pipe_out, async;
4246      struct fd_bitmap *fds_to_close;
4247      int flags;
4248 {
4249   int result, r, funcvalue;
4250 #if defined (JOB_CONTROL)
4251   int jobs_hack;
4252
4253   jobs_hack = (builtin == jobs_builtin) &&
4254                 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
4255 #endif
4256
4257   /* A subshell is neither a login shell nor interactive. */
4258   login_shell = interactive = 0;
4259
4260   if (async)
4261     subshell_environment |= SUBSHELL_ASYNC;
4262   if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4263     subshell_environment |= SUBSHELL_PIPE;
4264
4265   maybe_make_export_env ();     /* XXX - is this needed? */
4266
4267 #if defined (JOB_CONTROL)
4268   /* Eradicate all traces of job control after we fork the subshell, so
4269      all jobs begun by this subshell are in the same process group as
4270      the shell itself. */
4271
4272   /* Allow the output of `jobs' to be piped. */
4273   if (jobs_hack)
4274     kill_current_pipeline ();
4275   else
4276     without_job_control ();
4277
4278   set_sigchld_handler ();
4279 #endif /* JOB_CONTROL */
4280
4281   set_sigint_handler ();
4282
4283   if (fds_to_close)
4284     close_fd_bitmap (fds_to_close);
4285
4286   do_piping (pipe_in, pipe_out);
4287
4288   if (do_redirections (redirects, RX_ACTIVE) != 0)
4289     exit (EXECUTION_FAILURE);
4290
4291   if (builtin)
4292     {
4293       /* Give builtins a place to jump back to on failure,
4294          so we don't go back up to main(). */
4295       result = setjmp (top_level);
4296
4297       /* Give the return builtin a place to jump to when executed in a subshell
4298          or pipeline */
4299       funcvalue = 0;
4300       if (return_catch_flag && builtin == return_builtin)
4301         funcvalue = setjmp (return_catch);
4302
4303       if (result == EXITPROG)
4304         exit (last_command_exit_value);
4305       else if (result)
4306         exit (EXECUTION_FAILURE);
4307       else if (funcvalue)
4308         exit (return_catch_value);
4309       else
4310         {
4311           r = execute_builtin (builtin, words, flags, 1);
4312           fflush (stdout);
4313           if (r == EX_USAGE)
4314             r = EX_BADUSAGE;
4315           exit (r);
4316         }
4317     }
4318   else
4319     {
4320       r = execute_function (var, words, flags, fds_to_close, async, 1);
4321       fflush (stdout);
4322       exit (r);
4323     }
4324 }
4325
4326 /* Execute a builtin or function in the current shell context.  If BUILTIN
4327    is non-null, it is the builtin command to execute, otherwise VAR points
4328    to the body of a function.  WORDS are the command's arguments, REDIRECTS
4329    are the redirections to perform.  FDS_TO_CLOSE is the usual bitmap of
4330    file descriptors to close.
4331
4332    If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
4333    not undone before this function returns. */
4334 static int
4335 execute_builtin_or_function (words, builtin, var, redirects,
4336                              fds_to_close, flags)
4337      WORD_LIST *words;
4338      sh_builtin_func_t *builtin;
4339      SHELL_VAR *var;
4340      REDIRECT *redirects;
4341      struct fd_bitmap *fds_to_close;
4342      int flags;
4343 {
4344   int result;
4345   REDIRECT *saved_undo_list;
4346   sh_builtin_func_t *saved_this_shell_builtin;
4347
4348   if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
4349     {
4350       cleanup_redirects (redirection_undo_list);
4351       redirection_undo_list = (REDIRECT *)NULL;
4352       dispose_exec_redirects ();
4353       return (EX_REDIRFAIL);    /* was EXECUTION_FAILURE */
4354     }
4355
4356   saved_this_shell_builtin = this_shell_builtin;
4357   saved_undo_list = redirection_undo_list;
4358
4359   /* Calling the "exec" builtin changes redirections forever. */
4360   if (builtin == exec_builtin)
4361     {
4362       dispose_redirects (saved_undo_list);
4363       saved_undo_list = exec_redirection_undo_list;
4364       exec_redirection_undo_list = (REDIRECT *)NULL;
4365     }
4366   else
4367     dispose_exec_redirects ();
4368
4369   if (saved_undo_list)
4370     {
4371       begin_unwind_frame ("saved redirects");
4372       add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
4373     }
4374
4375   redirection_undo_list = (REDIRECT *)NULL;
4376
4377   if (builtin)
4378     result = execute_builtin (builtin, words, flags, 0);
4379   else
4380     result = execute_function (var, words, flags, fds_to_close, 0, 0);
4381
4382   /* We do this before undoing the effects of any redirections. */
4383   fflush (stdout);
4384   fpurge (stdout);
4385   if (ferror (stdout))
4386     clearerr (stdout);  
4387
4388   /* If we are executing the `command' builtin, but this_shell_builtin is
4389      set to `exec_builtin', we know that we have something like
4390      `command exec [redirection]', since otherwise `exec' would have
4391      overwritten the shell and we wouldn't get here.  In this case, we
4392      want to behave as if the `command' builtin had not been specified
4393      and preserve the redirections. */
4394   if (builtin == command_builtin && this_shell_builtin == exec_builtin)
4395     {
4396       if (saved_undo_list)
4397         dispose_redirects (saved_undo_list);
4398       redirection_undo_list = exec_redirection_undo_list;
4399       saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;      
4400       discard_unwind_frame ("saved_redirects");
4401     }
4402
4403   if (saved_undo_list)
4404     {
4405       redirection_undo_list = saved_undo_list;
4406       discard_unwind_frame ("saved redirects");
4407     }
4408
4409   if (redirection_undo_list)
4410     {
4411       cleanup_redirects (redirection_undo_list);
4412       redirection_undo_list = (REDIRECT *)NULL;
4413     }
4414
4415   return (result);
4416 }
4417
4418 void
4419 setup_async_signals ()
4420 {
4421 #if defined (__BEOS__)
4422   set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
4423 #endif
4424
4425 #if defined (JOB_CONTROL)
4426   if (job_control == 0)
4427 #endif
4428     {
4429       set_signal_handler (SIGINT, SIG_IGN);
4430       set_signal_ignored (SIGINT);
4431       set_signal_handler (SIGQUIT, SIG_IGN);
4432       set_signal_ignored (SIGQUIT);
4433     }
4434 }
4435
4436 /* Execute a simple command that is hopefully defined in a disk file
4437    somewhere.
4438
4439    1) fork ()
4440    2) connect pipes
4441    3) look up the command
4442    4) do redirections
4443    5) execve ()
4444    6) If the execve failed, see if the file has executable mode set.
4445    If so, and it isn't a directory, then execute its contents as
4446    a shell script.
4447
4448    Note that the filename hashing stuff has to take place up here,
4449    in the parent.  This is probably why the Bourne style shells
4450    don't handle it, since that would require them to go through
4451    this gnarly hair, for no good reason.
4452
4453    NOTE: callers expect this to fork or exit(). */
4454
4455 /* Name of a shell function to call when a command name is not found. */
4456 #ifndef NOTFOUND_HOOK
4457 #  define NOTFOUND_HOOK "command_not_found_handle"
4458 #endif
4459
4460 static void
4461 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
4462                       async, fds_to_close, cmdflags)
4463      WORD_LIST *words;
4464      REDIRECT *redirects;
4465      char *command_line;
4466      int pipe_in, pipe_out, async;
4467      struct fd_bitmap *fds_to_close;
4468      int cmdflags;
4469 {
4470   char *pathname, *command, **args;
4471   int nofork;
4472   pid_t pid;
4473   SHELL_VAR *hookf;
4474   WORD_LIST *wl;
4475
4476   nofork = (cmdflags & CMD_NO_FORK);  /* Don't fork, just exec, if no pipes */
4477   pathname = words->word->word;
4478
4479 #if defined (RESTRICTED_SHELL)
4480   command = (char *)NULL;
4481   if (restricted && mbschr (pathname, '/'))
4482     {
4483       internal_error (_("%s: restricted: cannot specify `/' in command names"),
4484                     pathname);
4485       last_command_exit_value = EXECUTION_FAILURE;
4486
4487       /* If we're not going to fork below, we must already be in a child
4488          process or a context in which it's safe to call exit(2).  */
4489       if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4490         exit (last_command_exit_value);
4491       else
4492         goto parent_return;
4493     }
4494 #endif /* RESTRICTED_SHELL */
4495
4496   command = search_for_command (pathname);
4497
4498   if (command)
4499     {
4500       maybe_make_export_env ();
4501       put_command_name_into_env (command);
4502     }
4503
4504   /* We have to make the child before we check for the non-existence
4505      of COMMAND, since we want the error messages to be redirected. */
4506   /* If we can get away without forking and there are no pipes to deal with,
4507      don't bother to fork, just directly exec the command. */
4508   if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
4509     pid = 0;
4510   else
4511     pid = make_child (savestring (command_line), async);
4512
4513   if (pid == 0)
4514     {
4515       int old_interactive;
4516
4517 #if 0
4518       /* This has been disabled for the time being. */
4519 #if !defined (ARG_MAX) || ARG_MAX >= 10240
4520       if (posixly_correct == 0)
4521         put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
4522 #endif
4523 #endif
4524
4525       /* Cancel traps, in trap.c. */
4526       restore_original_signals ();
4527
4528       /* restore_original_signals may have undone the work done
4529          by make_child to ensure that SIGINT and SIGQUIT are ignored
4530          in asynchronous children. */
4531       if (async)
4532         {
4533           if ((cmdflags & CMD_STDIN_REDIR) &&
4534                 pipe_in == NO_PIPE &&
4535                 (stdin_redirects (redirects) == 0))
4536             async_redirect_stdin ();
4537           setup_async_signals ();
4538         }
4539
4540       /* This functionality is now provided by close-on-exec of the
4541          file descriptors manipulated by redirection and piping.
4542          Some file descriptors still need to be closed in all children
4543          because of the way bash does pipes; fds_to_close is a
4544          bitmap of all such file descriptors. */
4545       if (fds_to_close)
4546         close_fd_bitmap (fds_to_close);
4547
4548       do_piping (pipe_in, pipe_out);
4549
4550       old_interactive = interactive;
4551       if (async)
4552         interactive = 0;
4553
4554       subshell_environment = SUBSHELL_FORK;
4555
4556       if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
4557         {
4558 #if defined (PROCESS_SUBSTITUTION)
4559           /* Try to remove named pipes that may have been created as the
4560              result of redirections. */
4561           unlink_fifo_list ();
4562 #endif /* PROCESS_SUBSTITUTION */
4563           exit (EXECUTION_FAILURE);
4564         }
4565
4566       if (async)
4567         interactive = old_interactive;
4568
4569       if (command == 0)
4570         {
4571           hookf = find_function (NOTFOUND_HOOK);
4572           if (hookf == 0)
4573             {
4574               internal_error (_("%s: command not found"), pathname);
4575               exit (EX_NOTFOUND);       /* Posix.2 says the exit status is 127 */
4576             }
4577
4578           wl = make_word_list (make_word (NOTFOUND_HOOK), words);
4579           exit (execute_shell_function (hookf, wl));
4580         }
4581
4582       /* Execve expects the command name to be in args[0].  So we
4583          leave it there, in the same format that the user used to
4584          type it in. */
4585       args = strvec_from_word_list (words, 0, 0, (int *)NULL);
4586       exit (shell_execve (command, args, export_env));
4587     }
4588   else
4589     {
4590 parent_return:
4591       /* Make sure that the pipes are closed in the parent. */
4592       close_pipes (pipe_in, pipe_out);
4593 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4594       if (variable_context == 0)
4595         unlink_fifo_list ();
4596 #endif
4597       FREE (command);
4598     }
4599 }
4600
4601 /* CPP defines to decide whether a particular index into the #! line
4602    corresponds to a valid interpreter name or argument character, or
4603    whitespace.  The MSDOS define is to allow \r to be treated the same
4604    as \n. */
4605
4606 #if !defined (MSDOS)
4607 #  define STRINGCHAR(ind) \
4608     (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
4609 #  define WHITECHAR(ind) \
4610     (ind < sample_len && whitespace (sample[ind]))
4611 #else   /* MSDOS */
4612 #  define STRINGCHAR(ind) \
4613     (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
4614 #  define WHITECHAR(ind) \
4615     (ind < sample_len && whitespace (sample[ind]))
4616 #endif  /* MSDOS */
4617
4618 static char *
4619 getinterp (sample, sample_len, endp)
4620      char *sample;
4621      int sample_len, *endp;
4622 {
4623   register int i;
4624   char *execname;
4625   int start;
4626
4627   /* Find the name of the interpreter to exec. */
4628   for (i = 2; i < sample_len && whitespace (sample[i]); i++)
4629     ;
4630
4631   for (start = i; STRINGCHAR(i); i++)
4632     ;
4633
4634   execname = substring (sample, start, i);
4635
4636   if (endp)
4637     *endp = i;
4638   return execname;
4639 }
4640
4641 #if !defined (HAVE_HASH_BANG_EXEC)
4642 /* If the operating system on which we're running does not handle
4643    the #! executable format, then help out.  SAMPLE is the text read
4644    from the file, SAMPLE_LEN characters.  COMMAND is the name of
4645    the script; it and ARGS, the arguments given by the user, will
4646    become arguments to the specified interpreter.  ENV is the environment
4647    to pass to the interpreter.
4648
4649    The word immediately following the #! is the interpreter to execute.
4650    A single argument to the interpreter is allowed. */
4651
4652 static int
4653 execute_shell_script (sample, sample_len, command, args, env)
4654      char *sample;
4655      int sample_len;
4656      char *command;
4657      char **args, **env;
4658 {
4659   char *execname, *firstarg;
4660   int i, start, size_increment, larry;
4661
4662   /* Find the name of the interpreter to exec. */
4663   execname = getinterp (sample, sample_len, &i);
4664   size_increment = 1;
4665
4666   /* Now the argument, if any. */
4667   for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
4668     ;
4669
4670   /* If there is more text on the line, then it is an argument for the
4671      interpreter. */
4672
4673   if (STRINGCHAR(i))  
4674     {
4675       for (start = i; STRINGCHAR(i); i++)
4676         ;
4677       firstarg = substring ((char *)sample, start, i);
4678       size_increment = 2;
4679     }
4680
4681   larry = strvec_len (args) + size_increment;
4682   args = strvec_resize (args, larry + 1);
4683
4684   for (i = larry - 1; i; i--)
4685     args[i] = args[i - size_increment];
4686
4687   args[0] = execname;
4688   if (firstarg)
4689     {
4690       args[1] = firstarg;
4691       args[2] = command;
4692     }
4693   else
4694     args[1] = command;
4695
4696   args[larry] = (char *)NULL;
4697
4698   return (shell_execve (execname, args, env));
4699 }
4700 #undef STRINGCHAR
4701 #undef WHITECHAR
4702
4703 #endif /* !HAVE_HASH_BANG_EXEC */
4704
4705 static void
4706 initialize_subshell ()
4707 {
4708 #if defined (ALIAS)
4709   /* Forget about any aliases that we knew of.  We are in a subshell. */
4710   delete_all_aliases ();
4711 #endif /* ALIAS */
4712
4713 #if defined (HISTORY)
4714   /* Forget about the history lines we have read.  This is a non-interactive
4715      subshell. */
4716   history_lines_this_session = 0;
4717 #endif
4718
4719 #if defined (JOB_CONTROL)
4720   /* Forget about the way job control was working. We are in a subshell. */
4721   without_job_control ();
4722   set_sigchld_handler ();
4723   init_job_stats ();
4724 #endif /* JOB_CONTROL */
4725
4726   /* Reset the values of the shell flags and options. */
4727   reset_shell_flags ();
4728   reset_shell_options ();
4729   reset_shopt_options ();
4730
4731   /* Zero out builtin_env, since this could be a shell script run from a
4732      sourced file with a temporary environment supplied to the `source/.'
4733      builtin.  Such variables are not supposed to be exported (empirical
4734      testing with sh and ksh).  Just throw it away; don't worry about a
4735      memory leak. */
4736   if (vc_isbltnenv (shell_variables))
4737     shell_variables = shell_variables->down;
4738
4739   clear_unwind_protect_list (0);
4740   /* XXX -- are there other things we should be resetting here? */
4741   parse_and_execute_level = 0;          /* nothing left to restore it */
4742
4743   /* We're no longer inside a shell function. */
4744   variable_context = return_catch_flag = funcnest = 0;
4745
4746   executing_list = 0;           /* XXX */
4747
4748   /* If we're not interactive, close the file descriptor from which we're
4749      reading the current shell script. */
4750   if (interactive_shell == 0)
4751     unset_bash_input (0);
4752 }
4753
4754 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
4755 #  define SETOSTYPE(x)  __setostype(x)
4756 #else
4757 #  define SETOSTYPE(x)
4758 #endif
4759
4760 #define READ_SAMPLE_BUF(file, buf, len) \
4761   do \
4762     { \
4763       fd = open(file, O_RDONLY); \
4764       if (fd >= 0) \
4765         { \
4766           len = read (fd, buf, 80); \
4767           close (fd); \
4768         } \
4769       else \
4770         len = -1; \
4771     } \
4772   while (0)
4773       
4774 /* Call execve (), handling interpreting shell scripts, and handling
4775    exec failures. */
4776 int
4777 shell_execve (command, args, env)
4778      char *command;
4779      char **args, **env;
4780 {
4781   int larray, i, fd;
4782   char sample[80];
4783   int sample_len;
4784
4785   SETOSTYPE (0);                /* Some systems use for USG/POSIX semantics */
4786   execve (command, args, env);
4787   i = errno;                    /* error from execve() */
4788   CHECK_TERMSIG;
4789   SETOSTYPE (1);
4790
4791   /* If we get to this point, then start checking out the file.
4792      Maybe it is something we can hack ourselves. */
4793   if (i != ENOEXEC)
4794     {
4795       if (file_isdir (command))
4796         internal_error (_("%s: is a directory"), command);
4797       else if (executable_file (command) == 0)
4798         {
4799           errno = i;
4800           file_error (command);
4801         }
4802       /* errors not involving the path argument to execve. */
4803       else if (i == E2BIG || i == ENOMEM)
4804         {
4805           errno = i;
4806           file_error (command);
4807         }
4808       else
4809         {
4810           /* The file has the execute bits set, but the kernel refuses to
4811              run it for some reason.  See why. */
4812 #if defined (HAVE_HASH_BANG_EXEC)
4813           READ_SAMPLE_BUF (command, sample, sample_len);
4814           if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4815             {
4816               char *interp;
4817               int ilen;
4818
4819               interp = getinterp (sample, sample_len, (int *)NULL);
4820               ilen = strlen (interp);
4821               errno = i;
4822               if (interp[ilen - 1] == '\r')
4823                 {
4824                   interp = xrealloc (interp, ilen + 2);
4825                   interp[ilen - 1] = '^';
4826                   interp[ilen] = 'M';
4827                   interp[ilen + 1] = '\0';
4828                 }
4829               sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
4830               FREE (interp);
4831               return (EX_NOEXEC);
4832             }
4833 #endif
4834           errno = i;
4835           file_error (command);
4836         }
4837       return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
4838     }
4839
4840   /* This file is executable.
4841      If it begins with #!, then help out people with losing operating
4842      systems.  Otherwise, check to see if it is a binary file by seeing
4843      if the contents of the first line (or up to 80 characters) are in the
4844      ASCII set.  If it's a text file, execute the contents as shell commands,
4845      otherwise return 126 (EX_BINARY_FILE). */
4846   READ_SAMPLE_BUF (command, sample, sample_len);
4847
4848   if (sample_len == 0)
4849     return (EXECUTION_SUCCESS);
4850
4851   /* Is this supposed to be an executable script?
4852      If so, the format of the line is "#! interpreter [argument]".
4853      A single argument is allowed.  The BSD kernel restricts
4854      the length of the entire line to 32 characters (32 bytes
4855      being the size of the BSD exec header), but we allow 80
4856      characters. */
4857   if (sample_len > 0)
4858     {
4859 #if !defined (HAVE_HASH_BANG_EXEC)
4860       if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
4861         return (execute_shell_script (sample, sample_len, command, args, env));
4862       else
4863 #endif
4864       if (check_binary_file (sample, sample_len))
4865         {
4866           internal_error (_("%s: cannot execute binary file"), command);
4867           return (EX_BINARY_FILE);
4868         }
4869     }
4870
4871   /* We have committed to attempting to execute the contents of this file
4872      as shell commands. */
4873
4874   initialize_subshell ();
4875
4876   set_sigint_handler ();
4877
4878   /* Insert the name of this shell into the argument list. */
4879   larray = strvec_len (args) + 1;
4880   args = strvec_resize (args, larray + 1);
4881
4882   for (i = larray - 1; i; i--)
4883     args[i] = args[i - 1];
4884
4885   args[0] = shell_name;
4886   args[1] = command;
4887   args[larray] = (char *)NULL;
4888
4889   if (args[0][0] == '-')
4890     args[0]++;
4891
4892 #if defined (RESTRICTED_SHELL)
4893   if (restricted)
4894     change_flag ('r', FLAG_OFF);
4895 #endif
4896
4897   if (subshell_argv)
4898     {
4899       /* Can't free subshell_argv[0]; that is shell_name. */
4900       for (i = 1; i < subshell_argc; i++)
4901         free (subshell_argv[i]);
4902       free (subshell_argv);
4903     }
4904
4905   dispose_command (currently_executing_command);        /* XXX */
4906   currently_executing_command = (COMMAND *)NULL;
4907
4908   subshell_argc = larray;
4909   subshell_argv = args;
4910   subshell_envp = env;
4911
4912   unbind_args ();       /* remove the positional parameters */
4913
4914   longjmp (subshell_top_level, 1);
4915   /*NOTREACHED*/
4916 }
4917
4918 static int
4919 execute_intern_function (name, function)
4920      WORD_DESC *name;
4921      COMMAND *function;
4922 {
4923   SHELL_VAR *var;
4924
4925   if (check_identifier (name, posixly_correct) == 0)
4926     {
4927       if (posixly_correct && interactive_shell == 0)
4928         {
4929           last_command_exit_value = EX_BADUSAGE;
4930           jump_to_top_level (ERREXIT);
4931         }
4932       return (EXECUTION_FAILURE);
4933     }
4934
4935   var = find_function (name->word);
4936   if (var && (readonly_p (var) || noassign_p (var)))
4937     {
4938       if (readonly_p (var))
4939         internal_error (_("%s: readonly function"), var->name);
4940       return (EXECUTION_FAILURE);
4941     }
4942
4943   bind_function (name->word, function);
4944   return (EXECUTION_SUCCESS);
4945 }
4946
4947 #if defined (INCLUDE_UNUSED)
4948 #if defined (PROCESS_SUBSTITUTION)
4949 void
4950 close_all_files ()
4951 {
4952   register int i, fd_table_size;
4953
4954   fd_table_size = getdtablesize ();
4955   if (fd_table_size > 256)      /* clamp to a reasonable value */
4956     fd_table_size = 256;
4957
4958   for (i = 3; i < fd_table_size; i++)
4959     close (i);
4960 }
4961 #endif /* PROCESS_SUBSTITUTION */
4962 #endif
4963
4964 static void
4965 close_pipes (in, out)
4966      int in, out;
4967 {
4968   if (in >= 0)
4969     close (in);
4970   if (out >= 0)
4971     close (out);
4972 }
4973
4974 static void
4975 dup_error (oldd, newd)
4976      int oldd, newd;
4977 {
4978   sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
4979 }
4980
4981 /* Redirect input and output to be from and to the specified pipes.
4982    NO_PIPE and REDIRECT_BOTH are handled correctly. */
4983 static void
4984 do_piping (pipe_in, pipe_out)
4985      int pipe_in, pipe_out;
4986 {
4987   if (pipe_in != NO_PIPE)
4988     {
4989       if (dup2 (pipe_in, 0) < 0)
4990         dup_error (pipe_in, 0);
4991       if (pipe_in > 0)
4992         close (pipe_in);
4993     }
4994   if (pipe_out != NO_PIPE)
4995     {
4996       if (pipe_out != REDIRECT_BOTH)
4997         {
4998           if (dup2 (pipe_out, 1) < 0)
4999             dup_error (pipe_out, 1);
5000           if (pipe_out == 0 || pipe_out > 1)
5001             close (pipe_out);
5002         }
5003       else
5004         {
5005           if (dup2 (1, 2) < 0)
5006             dup_error (1, 2);
5007         }
5008     }
5009 }