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