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